【发布时间】:2021-04-08 09:34:06
【问题描述】:
我正在尝试从头开始在 Python 中实现梯度下降函数,我已经在 GNU Octave 中实现并工作了该函数。不幸的是我被困住了。我摆弄了一段时间并检查了 NumPy 文档,但到目前为止还没有运气。 我知道诸如 scikit-learn 之类的库,但是我的目的是学习从头开始编写这样的函数。也许我的做法是错误的。 您将在下面找到重现错误所需的所有代码。 提前感谢您的帮助。
实际结果:测试失败并出现错误 -> "ValueError: matmul: Input operand 0 does not have enough dimensions (has 0, gufunc core with signature (n?,k),(k, m?)->(n?,m?) 需要 1)"
预期结果:以及值为 [5.2148, -0.5733] 的数组
Octave 中的函数 gradientDescent():
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
theta = theta - (alpha/m)*X'*(X*theta-y);
J_history(iter) = computeCost(X, y, theta);
end
python 中的函数 gradient_descent():
from numpy import zeros
def compute_cost(X, y, theta):
m = len(y)
ans = (X.T @ theta).T - y
J = (ans @ ans.T) / (2 * m)
return J[0, 0]
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = zeros((num_iters, 1), dtype=int)
for iter in range(num_iters):
theta = theta - (alpha / m) @ X.T @ (X @ theta - y)
J_history[iter] = compute_cost(X, y, theta)
return theta
测试文件:test_ml_utils.py
import unittest
import numpy as np
from ml.ml_utils import compute_cost, gradient_descent
class TestGradientDescent(unittest.TestCase):
# TODO: implement tests for Gradient Descent function
# [theta J_hist] = gradientDescent([1 5; 1 2; 1 4; 1 5],[1 6 4 2]',[0 0]',0.01,1000);
def test_gradient_descent_00(self):
X = np.array([[1, 5], [1, 2], [1, 4], [1, 5]])
y = np.array([1, 6, 4, 2])
theta = np.zeros(2)
alpha = 0.01
num_iter = 1000
r_theta = np.array([5.2148, -0.5733])
result = gradient_descent(X, y, theta, alpha, num_iter)
self.assertEqual((round(result, 4), r_theta), 'Result is wrong!')
if __name__ == '__main__':
unittest.main()
【问题讨论】:
标签: python numpy machine-learning octave gradient-descent