y = 2 + 3✖️size - 4✖️years + 2✖️floors
#y = theta_0 + theta_1 * size - theta_2 * years + theta_3 * floors
import numpy as np
m = 10
size = np.random.randint(80,120,10)
years = np.random.randint(1,10,10)
floors = np.random.randint(1,20,10)
labels = 2 + 3*size - 4*years + 2*floors
def sgd (lr, m):
theta0, theta1, theta2, theta3 = 0, 0, 0, 0
grad_theta0, grad_theta1, grad_theta2, grad_theta3 = 0, 0, 0, 0
for a in range(1000):
for i in range(m):
grad_theta0 += theta0 + theta1*size[i] + theta2*years[i] + theta3*floors[i] - labels[i]
grad_theta1 += (theta0 + theta1*size[i] + theta2*years[i] + theta3*floors[i] - labels[i]) * size[i]
grad_theta2 += (theta0 + theta1*size[i] + theta2*years[i] + theta3*floors[i] - labels[i]) * years[i]
grad_theta3 += (theta0 + theta1*size[i] + theta2*years[i] + theta3*floors[i] - labels[i]) * floors[i]
#print(grad_theta0)
theta0 -= lr * grad_theta0 / m
theta1 -= lr * grad_theta1 / m
theta2 -= lr * grad_theta2 / m
theta3 -= lr * grad_theta3 / m
grad_theta0, grad_theta1, grad_theta2, grad_theta3 = 0, 0, 0, 0
print (theta0)
lr = 0.001
sgd (lr, m)
问题1:1/2=0
import numpy as np
size = nd.random.randint(80,120,20)
这里使用的numpy结果用mxnet的ndarray去获取随机数去了。
正确改法:
size = nd.random.randint(80,120,20)
问题2:不收敛。还未解决。
//20201020晚解决
需要对数据集进行归一化。