【发布时间】:2023-03-18 20:14:02
【问题描述】:
我尝试实现随机梯度下降算法。 第一个解决方案有效:
def gradientDescent(x,y,theta,alpha):
xTrans = x.transpose()
for i in range(0,99):
hypothesis = np.dot(x,theta)
loss = hypothesis - y
gradient = np.dot(xTrans,loss)
theta = theta - alpha * gradient
return theta
此解决方案提供了正确的 theta 值,但以下算法 不工作:
def gradientDescent2(x,y,theta,alpha):
xTrans = x.transpose();
for i in range(0,99):
hypothesis = np.dot(x[i],theta)
loss = hypothesis - y[i]
gradientThetaZero= loss * x[i][0]
gradientThetaOne = loss * x[i][1]
theta[0] = theta[0] - alpha * gradientThetaZero
theta[1] = theta[1] - alpha * gradientThetaOne
return theta
我不明白为什么解决方案2不起作用,基本上它 和第一个算法一样。
我使用以下代码产生数据:
def genData():
x = np.random.rand(100,2)
y = np.zeros(shape=100)
for i in range(0, 100):
x[i][0] = 1
# our target variable
e = np.random.uniform(-0.1,0.1,size=1)
y[i] = np.sin(2*np.pi*x[i][1]) + e[0]
return x,y
并按以下方式使用它:
x,y = genData()
theta = np.ones(2)
theta = gradientDescent2(x,y,theta,0.005)
print(theta)
我希望你能帮助我! 最好的问候,菲利克斯
【问题讨论】:
-
如果你用 print、shape 和 break 语句调试你的代码,你就会明白为什么它们不一样
-
我正确理解:解决方案 1(您发布的第一个代码 sn-p)不是随机梯度下降,但解决方案 2 是您尝试更改解决方案 1让它变成随机梯度下降?另外,在你的
genData代码中,为什么要设置x[i][0]=1,所以x的整个第一列都是1? -
第一列是1,因为x0 = 1
标签: python numpy gradient-descent