【问题标题】:Gradient descent for linear regression with numpy使用 numpy 进行线性回归的梯度下降
【发布时间】: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


【解决方案1】:

每个观察有 5 个特征,X 包含 1000 个观察:

X = rng.rand(1000, 5) * 10  # X.shape == (1000, 5)

创建与X 完全线性相关的y(没有失真):

real_weights = np.array([2.2, 4, -4, 1, 2]).reshape(-1, 1)
real_bias = 0.9
y = X @ real_weights + real_bias  # y.shape == (1000, 1)

线性回归的 G.D. 实现:

笔记: w(权重)是您的 theta 变量。 我还添加了b(偏差)的计算。

def GD(X, y, eta=0.1, n_iter=20):
    # Initialize weights and a bias (all zeros):
    w = np.zeros((X.shape[1], 1))  # w.shape == (5, 1)
    b = 0
    # Gradient descent
    for i in range(n_iter):
        errors = X @ w + b - y  # errors.shape == (1000, 1)
        dw = 2 * np.mean(errors * X, axis=0).reshape(5, 1)
        db = 2 * np.mean(errors)
        w -= eta * dw
        b -= eta * db
    return w

测试:

w, b = GD(X, y, eta=0.003, n_iter=5000)
print(w, b)
[[ 2.20464905]
 [ 4.00510139]
 [-3.99569374]
 [ 1.00444026]
 [ 2.00407476]] 0.7805448262466914

请注意,您的函数 SGD 也包含一些错误。我会解决它并稍后添加到我的答案中。

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多