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

PenguinGoHack
  • 227

尝试自己写一个批梯度下降算法,在对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,请问如何写?

回复
阅读 6.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏