torch神经网络--线性回归
简单线性回归
y = 2*x + 1
import numpy as np
import torch
import torch.nn as nn
class LinearRegressionModel(nn.Module):
def __init__(self, input_dim, output_dim):
super(LinearRegressionModel, self).__init__()
self.linear = nn.Linear(input_dim, output_dim)
def forward(self, x):
out = self.linear(x)
return out
x_values = [i for i in range(11)]
x_train = np.array(x_values, dtype=np.float32)
x_train = x_train.reshape(-1, 1)
x_train.shape
y_values = [2*i+1 for i in x_values]
y_train = np.array(y_values, dtype=np.float32)
y_train = y_train.reshape(-1, 1)
y_train.shape
input_dim = 1
output_dim = 1
model = LinearRegressionModel(input_dim, output_dim)
# 如果使用GPU训练,增加以下两行代码
# device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# model.to(device)
# 指定好参数和损失函数
epochs = 1000
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
criterion = nn.MSELoss()
# 训练模型
for epoch in range(epochs):
epoch += 1
# 使用cpu时,注意转行成tensor
inputs = torch.from_numpy(x_train)
labels = torch.from_numpy(y_train)
# 如果使用GPU训练,将以上两行代码修改为
# inputs = torch.from_numpy(x_train).to(device)
# labels = torch.from_numpy(y_train).to(device)
# 梯度要清零每一次迭代
optimizer.zero_grad()
# 前向传播
outputs = model(inputs)
# 计算损失
loss = criterion(outputs, labels)
# 反向传播
loss.backward()
# 更新权重参数
optimizer.step()
# 打印
if epoch % 50 == 0:
print('epoch {}, loss {}'.format(epoch, loss.item()))
# CPU测试模型预测结果
predicted = model(torch.from_numpy(x_train).requires_grad_()).data.numpy()
# 模型的保存
torch.save(model.state_dict(), 'model.pkl')
# 模型读取
model.load_state_dict(torch.load('model.pkl'))
实例二:手写线性回归
import random
import torch
from d2l import torch as d2l
def synthetic_data(w, b, num_examples=100):
"""
生成数据 y = Xw + b + 噪声 随机
:param w:
:param b:
:param num_examples:
:return:
"""
# w = torch.tensor([2, -3.4])
# b = 4.2
# num_examples = 1000
X = torch.normal(0, # 均值
1, # 方差
(num_examples, len(w))) # 生成一个1000行,2列的矩阵
y = torch.matmul(X, w) + b
# 噪音
y += torch.normal(0,
0.01,
y.shape)
return X, y.reshape((-1, 1))
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
print('features:', features[0], '\nlabel:', labels[0])
d2l.set_figsize()
d2l.plt.scatter(features[:, 1].detach().numpy(),
labels.detach().numpy(), 1)
d2l.plt.show()
def data_iter(batch_size, features, labels):
"""
# 定义一个data_iter函数,该函数接收批量大小,特征矩阵和标签向量作为输入,生成大小为batch_size的小批量
:param batch_size:
:param features:
:param labels:
:return:
"""
num_examples = len(features)
# num_examples = 1000
# batch_size = 32
indices = list(range(num_examples))
# 这些样本是随机读取的,没有特定顺序
random.shuffle(indices)
for i in range(0, num_examples, batch_size):
# i = 1
batch_indices = torch.tensor(indices[i:min(i+batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices]
# 初始化模型参数
w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
def linreg(X, w, b):
"""线性回归模型"""
return torch.matmul(X, w) + b
# 定义损失函数
def squared_loss(y_hat, y):
"""均方损失"""
return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
# 优化器
def sgd(params, lr, batch_size):
"""
小批量随机梯度下降
:param params:
:param lr:
:param batch_size:
:return:
"""
with torch.no_grad():
for param in params:
param -= lr * param.grad / batch_size
param.grad.zero_()
batch_size = 10
lr = 0.03
num_epochs = 3
net = linreg
loss = squared_loss
for epoch in range(num_epochs):
for X, y in data_iter(batch_size, features, labels):
l = loss(net(X, w, b), y) # X和y的小批量损失
# 因为l形状是(batch_size,1),而不是一个标量。l中的所有元素被加到一起,
# 并以此计算关于[w,b]的梯度
l.sum().backward()
sgd([w, b], lr, batch_size) # 使用参数的梯度更新参数
with torch.no_grad():
train_l = loss(net(features, w, b), labels)
print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')
print(f'w的估计误差: {true_w - w.reshape(true_w.shape)}')
print(f'b的估计误差: {true_b - b}')
print(f'w的估计值: {w}')
print(f'b的估计值: {b}')
实例三:线性回归调用torch
import random
import torch
from torch.utils import data # 数据处理模块
from d2l import torch as d2l
def synthetic_data(w, b, num_examples=100):
"""
生成数据 y = Xw + b + 噪声 随机
:param w:
:param b:
:param num_examples:
:return:
"""
# w = torch.tensor([2, -3.4])
# b = 4.2
# num_examples = 1000
X = torch.normal(0, # 均值
1, # 方差
(num_examples, len(w))) # 生成一个1000行,2列的矩阵
y = torch.matmul(X, w) + b
# 噪音
y += torch.normal(0,
0.01,
y.shape)
return X, y.reshape((-1, 1))
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
print('features:', features[0], '\nlabel:', labels[0])
d2l.set_figsize()
d2l.plt.scatter(features[:, 1].detach().numpy(),
labels.detach().numpy(), 1)
d2l.plt.show()
def load_array(data_arrays, batch_size, is_train=True):
"""
构造一个pytorch数据迭代器
:param data_arrays:
:param batch_size:
:param is_train:
:return:
"""
dataset = data.TensorDataset(*data_arrays)
return data.DataLoader(dataset, batch_size, shuffle=is_train)
batch_size = 10
data_iter = load_array((features, labels), batch_size)
next(iter(data_iter))
w = torch.normal(0, 0.01, size=(2, 1), requires_grad=True)
b = torch.zeros(1, requires_grad=True)
# nn是神经网络的缩写, 模型定义
from torch import nn
net = nn.Sequential(nn.Linear(2, 1))
# 初始化模型参数
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)
# 定义损失函数
loss = nn.MSELoss()
# 定义优化算法
opt = torch.optim.SGD(net.parameters(), lr=0.03)
# 训练
num_epochs = 3
for epoch in range(num_epochs):
for X, y in data_iter:
l = loss(net(X), y)
opt.zero_grad()
l.backward()
opt.step()
l = loss(net(features), labels)
print(f'epoch {epoch + 1}, loss {l:f}')
w = net[0].weight.data
print('w的估计误差:', true_w - w.reshape(true_w.shape))
b = net[0].bias.data
print('b的估计误差:', true_b - b)
print(f'w的估计值: {w}')
print(f'b的估计值: {b}')