單輸入線性回歸練習(xí)
1.導(dǎo)入需要用的模塊
# 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.初始化參數(shù)
注意:初始化參數(shù)時要初始化為向量继蜡,例如初始化為x = torch.randn(n)就是錯誤的子刮。
#初始化參數(shù)
n = 1000
x = torch.randn(n,1)
w = 3.4
b = 2
y = torch.zeros(n,1)
3.生成數(shù)據(jù)集
注意:生成數(shù)據(jù)集時,后面的隨機(jī)生成的數(shù)字要為和y一樣的隨機(jī)向量,而不能是一個數(shù)字砾层。
#2.生成數(shù)據(jù)集
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.初始化參數(shù)
注意:w.requires_grad_(requires_grad=True) 默認(rèn)的requires_grad=False(自動求導(dǎo))
#初始化訓(xùn)練參數(shù) / 讀取數(shù)據(jù)
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.分批次讀取數(shù)據(jù)
注意:random.shuffle(indices) 函數(shù)表示打亂列表的循序。
torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) :構(gòu)建多個(1*batch_size) Long類型的張量贱案。
#分批次讀取數(shù)據(jù)
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices) # random read 10 samples 打亂順序函數(shù)
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
#損失函數(shù)
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)