【发布时间】:2019-11-29 04:45:03
【问题描述】:
我正在尝试在 python 中从头开始实现梯度下降算法,这应该相当容易。但是,我现在一直在摸索我的代码,无法让它工作。
我生成数据如下:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('darkgrid')
#Defining the x array.
x=np.array(range(1,100))
#Defining the y array.
y=10+2*x.ravel()
y=y+np.random.normal(loc=0, scale=70, size=99)
然后定义参数:
alpha = 0.01 # Which will be the learning rate
NbrIter = 100 # Representing the number of iteration
m = len(y)
theta = np.random.randn(2,1)
我的GD如下:
for iter in range(NbrIter):
theta = theta - (1/m) * alpha * ( X.T @ ((X @ theta) - y) )
我得到的是一个巨大的矩阵,这意味着我对线性代数有一些问题。但是,我真的看不出问题出在哪里。
(玩弄矩阵以尝试使它们匹配,我达到了具有正确形式(2x1)的theta: theta = theta - (1/m) * alpha * ( X.T @ ((X @ theta).T - y).T ) 但它看起来确实是错误的,并且实际值相差甚远(array([[-8.92647663e+148], [-5.92079000e+150]])) )
【问题讨论】:
标签: python numpy optimization gradient-descent