优化算法:小批量随机梯度降低javascript
每次随机选择小样本,求小批量数据样本的平均损失函数的导数,修改模型参数。css
矢量计算:html
那么预测表达式为 y^ = XW + bhtml5
%matplotlib inline
from IPython import display
from matplotlib import pyplot as plt
from mxnet import autograd,nd
import random
num_inputs = 2
num_examples = 1000
true_w = [2,-3.4]
true_b = 4.2
features = nd.random.normal(scale=1,shape=(num_examples,num_inputs))
labels = true_w[0]*features[:,0] + true_w[1]*features[:,1] + true_b
labels += nd.random.normal(scale=0.01,shape=labels.shape)
features[0],labels[0]
def use_svg_display():
display.set_matplotlib_format('svg')
def set_figsize(figsize=(3.5,2.5)):
use_svg_display()
plt.rcParams['figure.figsize'] = figsize
set_figsize
plt.scatter(features[:,1].asnumpy(),labels.asnumpy(),1)
读取数据java
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
j = nd.array(indices[i: min(i + batch_size, num_examples)])
yield features.take(j), labels.take(j)
batch_size = 10
for X,y in data_iter(batch_size,features,labels):
print(X,y)
break
w = nd.random.normal(scale=0.01,shape=(num_inputs,1))
b = nd.zeros(shape=(1,))
w,b
w,b是迭代对象,建立他们的梯度python
w.attach_grad()
b.attach_grad()
计算函数jquery
def linreg(X, w, b): # 本函数已保存在 gluonbook 包中方便之后使用。
return nd.dot(X, w) + b
损失函数linux
def squared_loss(y_hat, y): # 本函数已保存在 gluonbook 包中方便之后使用。
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
定义优化算法android
def sgd(params, lr, batch_size): # 本函数已保存在 gluonbook 包中方便之后使用。
for param in params:
param[:] = param - lr * param.grad / batch_size
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
for epoch in range(num_epochs): # 训练模型一共须要 num_epochs 个迭代周期。
# 在一个迭代周期中,使用训练数据集中全部样本一次(假设样本数可以被批量大小整除)。
# X 和 y 分别是小批量样本的特征和标签。
for X, y in data_iter(batch_size, features, labels):
with autograd.record():
l = loss(net(X, w, b), y) # l 是有关小批量 X 和 y 的损失。
l.backward() # 小批量的损失对模型参数求梯度。
sgd([w, b], lr, batch_size) # 使用小批量随机梯度降低迭代模型参数。
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().asnumpy()))
true_w,w
true_b,b