我正在用梯度下降法对线性回归进行编码。通过使用for循环而不是张量
我认为我的代码在逻辑上是正确的,当我绘制图表时,θ值和线性模型看起来很好。但成本函数的价值很高。你能帮我吗
成本函数的值为1160934,这是异常的
def gradient_descent(alpha,x,y,ep=0.0001, max_repeat=10000000):
m = x.shape[0]
converged = False
repeat = 0
theta0 = 1.0
theta3 = -1.0
# J=sum([(theta0 +theta3*x[i]- y[i])**2 for i in range(m)]) / 2*m #######
J=1
while not converged :
grad0= sum([(theta0 +theta3*x[i]-y[i]) for i in range (m)]) / m
grad1= sum([(theta0 + theta3*x[i]-y[i])*x[i] for i in range (m)])/ m
temp0 = theta0 - alpha*grad0
temp1 = theta3 - alpha*grad1
theta0 = temp0
theta3 = temp1
msqe = (sum([(theta0 + theta3*x[i] - y[i]) **2 for i in range(m)]))* (1 / 2*m)
print(theta0,theta3,msqe)
if abs(J-msqe) <= ep:
print ('Converged, iterations: {0}', repeat, '!!!')
converged = True
J = msqe
repeat += 1
if repeat == max_repeat:
converged = True
print("max 까지 갔다")
return theta0, theta3, J
[theta0,theta3,J]=gradient_descent(0.001,X3,Y,ep=0.0000001,max_repeat=1000000)
print("************\n theta0 : {0}\ntheta3 : {1}\nJ : {2}\n"
.format(theta0,theta3,J))
在处理具有巨大差异的大型数据集时,成本很高是很正常的。此外,您的数据处理的是大量数据,因此成本相当高,规范化数据将为您提供正确的估计,因为规范化数据不需要缩放。试着这样做,从随机测试开始,每次观察成本,如果成本在很大范围内波动,那么可能会有一些错误,否则就没问题了
我认为数据集本身是相当广泛的,这就是为什么最佳拟合线显示了大量的成本函数。如果你扩展你的数据,你会看到它显著下降
相关问题 更多 >
编程相关推荐