书本源码
import numpy as np
import matplotlib.pyplot as plt
# 读入训练数据
train = np.loadtxt('click.csv', delimiter=',', dtype='int', 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.size), x, x ** 2]).T
X = to_matrix(train_z)
# 预测函数
def f(x):
return np.dot(x, theta)
# 均方误差
def MSE(x, y):
return (1 / x.shape[0]) * np.sum((y - f(x)) ** 2)
# 学习率
ETA = 1e-3
# 误差的差值
diff = 1
# 更新次数
count = 0
# 重复学习
error = MSE(X, train_y)
while diff > 1e-2:
# 使用随机梯度下降法更新参数
# premutation() 随机产生序列
p = np.random.permutation(X.shape[0])
# 变量 x y 遍历 zip 标准化序列的行列元素
for x, y in zip(X[p,:], train_y[p]):
theta = theta - ETA * (f(x) - y) * x
# 计算与上一次误差的差值
current_error = MSE(X, train_y)
diff = error - current_error
error = current_error
# 输出日志
count += 1
log = '第 {} 次 : theta = {}, 差值 = {:.4f}'
print(log.format(count, theta, diff))
# 绘图确认
x = np.linspace(-3, 3, 100)
plt.plot(train_z, train_y, 'o')
plt.plot(x, f(to_matrix(x)))
plt.show()
p = np.random.permutation(X.shape[0])
for x, y in zip(X[p,:], train_y[p]):
书本关于随机梯度下降的代码实现有这两段代码,当时不太理解,所以看看这两段代码做了什么。
p = np.random.permutation(X.shape[0])
第一个代码声明了一个 p ,等号右边调用两个函数 premutation() 和 shape() 。
先看被 premutation() 括住的 shape() 函数。该函数用于查看矩阵或者矩阵某一维度的维数。比如给出一个 X 矩阵。
查看整个矩阵或某一维度的信息有。
再来理解 premutation() ,该函数返回一个随机的初始化序列,序列长度和数值的范围就是 shape() 传入的参数。比如下面这个图片,传入了一个 20 参数,那么就会随机一个包含 20 个数字且数值不大于 20 的随机序列。这就可以理解传入一个 shape() 有什么用了。
for x, y in zip(X[p,:], train_y[p]):
再来理解另外一行代码,从简单的开始理解,先看右边的 train_y[p] 。
上面的图片展示了原始的一维向量、p的随机序列和传入了 p 随机序列后向量的结果。可以看到新的向量里元素的位置跟原本的发生了变化,而用带颜色的下划线画出了变化前后元素位置与随机序列的索引之间的关系。
这意味着打乱后新序列的元素有这个关系,新序列的元素 ——> 随机序列的元素 ——> 原序列的元素。
同理,用同样的思路来看矩阵 X 的切片 X[p,:] 。
可以看到具有同样的性质,只不过原来单个元素的位置互换在这里变成了行向量之间的互换。这种对应关系跟索引存储具有一定相似性。
np.random.permutation()函数的使用
shape用法