实现随机梯度下降法作业
import random
A = [[1,6], [2,5], [8,6], [4,7]]
y = [19,28,19,21]
theta = [2,5]
lr = 0.005
loss = 50
iters = 1
e = 0.0001
while loss>e and iters <1000:
loss = 0
i = random.randint(0, 3)
h = theta[0]*A[i][0] + theta[1]*A[i][1]
theta[0] = theta[0] + lr*(y[i]-h)*A[i][0]
theta[1] = theta[1] + lr*(y[i]-h)*A[i][1]
E = 0
E = theta[0]*A[i][0] + theta[1]*A[i][1] - y[i]
E = E*E
loss = loss +E
iters = iters +1
print ('theta=',theta)
print ('iters=',iters)