python - 矢量化线性回归

标签 python numpy linear-algebra linear-regression

这是我尝试使用 numpy 和线性代数进行线性回归的尝试:

def linear_function(w , x , b):
    return np.dot(w , x) + b

x = np.array([[1, 1,1],[0, 0,0]])
y = np.array([0,1])

w = np.random.uniform(-1,1,(1 , 3))

print(w)
learning_rate = .0001

xT = x.T
yT = y.T

for i in range(30000):

    h_of_x = linear_function(w , xT , 1)
    loss = h_of_x - yT

    if i % 10000 == 0:
        print(loss , w)
    w = w + np.multiply(-learning_rate , loss)

linear_function(w , x , 1)

这会导致错误:

ValueError                                Traceback (most recent call last)
<ipython-input-137-130a39956c7f> in <module>()
     24     if i % 10000 == 0:
     25         print(loss , w)
---> 26     w = w + np.multiply(-learning_rate , loss)
     27 
     28 linear_function(w , x , 1)

ValueError: operands could not be broadcast together with shapes (1,3) (1,2) 

这似乎适用于降低训练集维度:

import numpy as np

def linear_function(w , x , b):
    return np.dot(w , x) + b

x = np.array([[1, 1],[0, 0]])
y = np.array([0,1])

w = np.random.uniform(-1,1,(1 , 2))

print(w)
learning_rate = .0001

xT = x.T
yT = y.T

for i in range(30000):

    h_of_x = linear_function(w , xT , 1)
    loss = h_of_x - yT

    if i % 10000 == 0:
        print(loss , w)
    w = w + np.multiply(-learning_rate , loss)

linear_function(w , x , 1)

print(linear_function(w , x[0] , 1))
print(linear_function(w , x[1] , 1))

哪个返回:

[[ 0.68255806 -0.49717912]]
[[ 1.18537894  0.        ]] [[ 0.68255806 -0.49717912]]
[[ 0.43605474  0.        ]] [[-0.06676614 -0.49717912]]
[[ 0.16040755  0.        ]] [[-0.34241333 -0.49717912]]
[ 0.05900769]
[ 1.]

[ 0.05900769] & [ 1.] 接近训练示例,因此看来此实现是正确的。抛出错误的实现有什么问题?我没有正确实现 2 -> 3 的维度扩展?

最佳答案

我列出了以下问题:

  1. 您的数组形状不一致。这可能会导致广播/点出现问题,尤其是在梯度下降期间。修复您的初始化。我还建议使用 b 扩充 w 并使用一列 1 扩充 X

  2. 我觉得你的损失函数和梯度计算不正确。一般来说,不推荐使用曼哈顿距离作为损失函数,因为它不是一个足够的距离度量。我会使用欧氏距离并尝试最小化平方和(这称为 OLS regression )。然后,我们按如下方式进行梯度计算。

  3. 您的更新规则将根据 (2) 相应更改。

  4. 确保为您的代码设置停止条件。您不想超过最佳值。通常,当梯度变化不大时就应该停止。

完整列表:

# input, augmented
x = np.array([[1, 1, 1], [0, 0, 0]])
x = np.column_stack((np.ones(len(x)), x))
# predictions
y = np.array([[0, 1]])   
# weights, augmented with bias
w = np.random.uniform(-1, 1, (1, 4))

learning_rate = .0001

loss_old = np.inf
for i in range(30000):  
    h_of_x = w.dot(x.T)
    loss = ((h_of_x - y) ** 2).sum()

    if abs(loss_old - loss) < 1e-5:
        break

    w = w - learning_rate * (h_of_x - y).dot(x)
    loss_old = loss

其他建议/改进

接下来,考虑这里正则化的使用。 L1 (ridge) 和 L2 (lasso) 都是不错的选择。

最后,线性回归有一个封闭形式的解决方案,保证收敛于局部最优(梯度下降只保证局部最优)。这很快,但计算量大(因为它涉及计算逆)。查看权衡 here .

w = y.dot(np.linalg.inv(x.dot(x.T)).dot(x))

当 xT.x 不可逆时,您需要进行正则化。

请记住,线性回归只能为线性决策边界建模。如果您确信您的实现是正确的,并且您的损失仍然很严重,则您的数据可能不适用于其当前的向量空间,因此您将需要非线性基函数来转换它(这实际上是非线性的回归)。

关于python - 矢量化线性回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50156643/

相关文章:

python - 在 Heroku 上出现错误 "ImportError: No module named"但在本地却没有

python - 将焦点放在 Tkinter 窗口上(取决于平台?)

python - Pandas 每 n 行 groupby 模式

python - 基于一个引用数组向数组添加和删除元素

python - 执行大点/张量点积同时仅保留对角线条目的最有效方法

python - 查找两点之间字符串的最佳方法

python - python opencv中如何统计某个像素值的像素个数?

numpy - 在 numpy 中创建倾斜/连续移位矩阵的最快方法

c# - 将 2D 仿射变换矩阵转换为 3D 仿射变换矩阵

python - 为什么 Mathematica 和 Python 在处理奇异矩阵方程时的答案不同?