随机梯度下降法的做法是使用一下表达式(我前面的博客有讲到公式推理过程)来更新参数,表达式中的k 是随机选择的
现在有了训练数据的矩阵X,把行的顺序随机地予以调整,然后重复应用更新表达式就行了。
import numpy as np
import matplotlib.pyplot as plt
#读入训练数据
train = np.loadtxt('D:/NoteBook/sourcecode-cn/click.csv', delimiter=',', skiprows=1)
train_x = train[:,0]
train_y = train[:,1]
#标准化
mu = train_x.mean()
sigma = train_x.std()
def standardize(x):
return (x - mu)/ sigma
train_z = standardize(train_x)
#用随机数对参数初始化
theta = np.random.rand(3)
#创建训练数据矩阵
def to_matrix(x):
return np.vstack([np.ones(x.shape[0]), x, x**2]).T
X = to_matrix(train_z)
#预测函数
def f(x):
return np.dot(x, theta)
#均方误差的历史纪录
errors