线性回归练习

单输入线性回归练习

1.导入需要用的模块

# import packages and modules
%matplotlib inline
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random

2.初始化参数

注意:初始化参数时要初始化为向量,例如初始化为x = torch.randn(n)就是错误的。

#初始化参数
n = 1000
x = torch.randn(n,1)
w = 3.4
b = 2
y = torch.zeros(n,1)

3.生成数据集

注意:生成数据集时,后面的随机生成的数字要为和y一样的随机向量,而不能是一个数字。

#2.生成数据集
y = w*x + b + torch.tensor(np.random.normal(0, 0.5, size=y.size()))
print(y[0:10])
print(x.shape,y.shape)
plt.scatter(x.numpy(), y.numpy(),1);

4.初始化参数

注意:w.requires_grad_(requires_grad=True) 默认的requires_grad=False(自动求导)

#初始化训练参数 / 读取数据
X = x
w = torch.randn(1)
b = torch.zeros(1)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
print(w,b,x_len)

5.分批次读取数据

注意:random.shuffle(indices) 函数表示打乱列表的循序。
torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) :构建多个(1*batch_size) Long类型的张量。

#分批次读取数据
def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices)  # random read 10 samples 打乱顺序函数
    for i in range(0, num_examples, batch_size):
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch
        yield  features.index_select(0, j), labels.index_select(0, j)

#前向传播
def forword(X,w,b):
    w=w.view(len(w),1) # 可以不加,目的是为了确保w为相对于的矩阵。
    b=b.view(len(b),1)
    return torch.mm(X, w) + b
    
#损失函数
def squared_loss(y_hat, y): 
    return (y_hat - y.view(y_hat.size())) ** 2 / 2
    
#反向传播
def sgd(params, lr, batch_size): 
    for param in params:
        param.data -= lr * param.grad / batch_size # ues .data to operate param without gradient track

# super parameters init
lr = 0.03
num_epochs = 5000

net = forword
loss = squared_loss

# training
for epoch in range(num_epochs):  # training repeats num_epochs times
    # in each epoch, all the samples in dataset will be used once
    
    # X is the feature and y is the label of a batch sample
    for X, y in data_iter(batch_size, X, y):
        #print(X.shape,w.shape,b)
        l = loss(net(X, w, b), y).sum()  
        # calculate the gradient of batch sample loss 
        l.backward()  
        # using small batch random gradient descent to iter model parameters
        sgd([w, b], lr, batch_size)  
        # reset parameter gradient
        w.grad.data.zero_()
        b.grad.data.zero_()
    train_l = loss(net(X, w, b), y)
    #print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))

print(w,b)

你可能感兴趣的:(线性回归练习)