我尝试实现梯度下降,当我在示例数据集上测试它时它工作正常,但它对于波士顿数据集无法正常工作。
你能验证一下代码有什么问题吗?为什么我没有得到正确的 theta 向量?
import numpy as np
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
X = load_boston().data
y = load_boston().target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
X_train1 = np.c_[np.ones((len(X_train), 1)), X_train]
X_test1 = np.c_[np.ones((len(X_test), 1)), X_test]
eta = 0.0001
n_iterations = 100
m = len(X_train1)
tol = 0.00001
theta = np.random.randn(14, 1)
for i in range(n_iterations):
gradients = 2/m * X_train1.T.dot(X_train1.dot(theta) - y_train)
if np.linalg.norm(X_train1) < tol:
break
theta = theta - (eta * gradients)
我得到的权重向量的形状为 (14, 354)。我在这里做错了什么?
最佳答案
考虑这一点(展开一些语句以获得更好的可见性):
for i in range(n_iterations):
y_hat = X_train1.dot(theta)
error = y_hat - y_train[:, None]
gradients = 2/m * X_train1.T.dot(error)
if np.linalg.norm(X_train1) < tol:
break
theta = theta - (eta * gradients)
由于 y_hat 是 (n_samples, 1) 并且 y_train 是 (n_samples,) - 对于您的示例,n_samples 是 354 - 您需要使用虚拟轴技巧将 y_train 带到相同的维度 y_train[:, None]
.
关于python - python 中的梯度下降实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210443/