【发布时间】:2022-08-14 00:48:03
【问题描述】:
我想用 numpy 实现梯度下降以进行线性回归,但我在这段代码中有一些错误:
import numpy as np
# Code Example
rng = np.random.RandomState(10)
X = 10*rng.rand(1000, 5) # feature matrix
y = 0.9 + np.dot(X, [2.2, 4, -4, 1, 2]) # target vector
# GD implementation for linear regression
def GD(X, y, eta=0.1, n_iter=20):
theta = np.zeros((X.shape[0], X.shape[1]))
for i in range(n_iter):
grad = 2 * np.mean((np.dot(theta.T, X) - y) * X)
theta = theta - eta * grad
return theta
# SGD implementation for linear regression
def SGD(X, y, eta=0.1, n_iter=20):
theta = np.zeros(1, X.shape[1])
for i in range(n_iter):
for j in range(X.shape[0]):
grad = 2 * np.mean((np.dot(theta.T, X[j,:]) - y[j]) * X[j,:])
theta = theta - eta * grad
return theta
# MSE loss for linear regression with numpy
def MSE(X, y, theta):
return np.mean((X.dot(theta.T) - y)**2)
# linear regression with GD and MSE with numpy
theta_gd = GD(X, y)
theta_sgd = SGD(X, y)
print(\'MSE with GD: \', MSE(X, y, theta_gd))
print(\'MSE with SGD: \', MSE(X, y, theta_sgd))
错误是
grad = 2 * np.mean((np.dot(theta.T, X) - y) * X)
ValueError: operands could not be broadcast together with shapes (5,5) (1000,)
我无法解决它。
-
欢迎来到堆栈溢出。
np.dot(theta.T, X).shape是 (5,5),但y.shape是 (1000,)。他们不能broadcast together 做减法(因为他们的形状)。要解决此问题,您必须了解您要尝试使用这些操作做什么。 -
谢谢您的回答。我知道你想说什么,我对线性回归的梯度下降有疑问,我的问题不是代码问题。我对我的数学和机器学习问题有疑问
标签: python numpy machine-learning linear-regression gradient-descent