科学计算 - python-如何使用sympy库的diff函数对自定义的多参数函数微分?

 mobiledu2502858723 发布于 2022-10-31 22:15

尝试自己写一个批梯度下降算法,在对cost function微分时遇到了问题。
计算cost function的函数有三个参数,如何用diff来微分?

import numpy as np
from sympy import *
from pylab import *

# h(x) = theta0 + theta1 * x1 + theta2 * x2 + ...
def hypothesis(x_sample, theta):
    temp = [x * y for (x, y) in zip(x_sample, theta)]
    result = sum(temp)
    return result

# cost function (j(theta)) ...
def cost_func(x_set, y_set, theta):
    result = sum([pow(hypothesis(x_set, theta) - y, 2) for (x, y) in zip(x_set, y_set)])
    result = result / 2
    return result


def batch_theta_update(x_set, y_set, theta, learning_rate):
    for theta_j in theta:
        x_set, y_set, theta = symbols('x y z')
        gradient = diff(cost_func(x, y, z), theta_j)
        theta_j -= learning_rate * gradient
    return theta

在batch_theta_update函数中,我要计算梯度gradient,请问如何写?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有