mxnet和gluon学习笔记1——linear regression

参考李沐的课件与教材,将重点部分做了注释

1. ndarray实现

%matplotlib inline
from IPython import display
from matplotlib import pyplot as plt
from mxnet import autograd, nd
import random

# 本函数已保存在 gluonbook 包中方便以后使用。
def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    #print('indices=',indices)
    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)  # take 函数根据索引返回对应元素。yield生成器用法

def use_svg_display():
    # 用矢量图显示。
    display.set_matplotlib_formats('svg')

def set_figsize(figsize=(3.5, 2.5)):
    use_svg_display()
    # 设置图的尺寸。
    plt.rcParams['figure.figsize'] = figsize
    
def linreg(X, w, b):  # 本函数已保存在 gluonbook 包中方便以后使用。
    return nd.dot(X, w) + b

def squared_loss(y_hat, y):  # 本函数已保存在 gluonbook 包中方便以后使用。
    return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2

def sgd(params, lr, batch_size):  # 本函数已保存在 gluonbook 包中方便以后使用。
    for param in params:
        #param[:] = param - lr * param.grad / batch_size #要原地操作,否则会重新创建新param,这样是没有attach_grad的
        param[:] = param - lr * param.grad / batch_size 
        print('param',param)
        print('param[:] ', param[:] )

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)

set_figsize()
plt.scatter(features[:, 1].asnumpy(), labels.asnumpy(), 1)
batch_size = 10

for X, y in data_iter(batch_size, features, labels):
    print(X, y)
    print('-'*20)
    break
    
w = nd.random.normal(scale=0.01, shape=(num_inputs, 1))
b = nd.zeros(shape=(1,))    

w.attach_grad()
b.attach_grad()

#train the model
lr = 0.01
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()))
    
print('w', w)
print('b', b)

注: yield

'''
带yield的函数是一个生成器,而不是一个函数了,
这个生成器有一个函数就是next函数,next就相当于“下一步”生成哪个数,
这一次的next开始的地方是接着上一次的next停止的地方执行的,
所以调用next的时候,生成器并不会从foo函数的开始执行,只是接着上一步停止的地方开始,
然后遇到yield后,return出要生成的数,此步就结束。
'''


def foo():
    print("starting...")
    while True:
        res = yield 11
        print("res:",res)
g = foo() #因为foo函数中有yield关键字,所以foo函数并不会真的执行,而是先得到一个生成器g(相当于一个对象)
print(next(g))
print("*"*10)
print(next(g))
print(g.send(1)) #先把7赋值给了res,然后执行next的作用,

2.gluon实现

from mxnet import autograd, nd
from mxnet.gluon import data as gdata
from mxnet.gluon import nn
from mxnet import init
from mxnet.gluon import loss as gloss
from mxnet import gluon

# generate the data
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)

batch_size = 10
# 将训练数据的特征和标签组合。
dataset = gdata.ArrayDataset(features, labels)
# 随机读取小批量。
data_iter = gdata.DataLoader(dataset, batch_size, shuffle=True)

# show the data
for X, y in data_iter:
    print('X',X)
    print('y', y)
    break # only the first batch
    
net = nn.Sequential() #实例可以看作是一个串联各个层的容器
net.add(nn.Dense(1))  #定义该层输出个数为 1
#note:无需指定每一层输入的形状
net.initialize(init.Normal(sigma=0.01))
loss = gloss.L2Loss()  # 平方损失又称 L2 范数损失

trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.03})

#<trainer.step>
#For normal parameter updates, `step()` should be used, which internally calls
#`allreduce_grads()` and then `update()`. 
#Batch size of data processed. Gradient will be normalized by `1/batch_size`.
#Set this to 1 if you normalized loss manually with `loss = mean(loss)`.
num_epochs = 3
for epoch in range(1, num_epochs + 1):
    for X, y in data_iter:
        with autograd.record():
            l = loss(net(X), y)
        l.backward()
        trainer.step(batch_size)# NOTE!
    l = loss(net(features), labels)
    print('epoch %d, loss: %f' % (epoch, l.mean().asnumpy()))
    #print('grad', net[0].weight.grad())

#putput
dense = net[0]
print(true_w, dense.weight.data())
print(true_b, dense.bias.data())

猜你喜欢

转载自blog.csdn.net/Yang_He0105/article/details/89792060
今日推荐