线性回归
import torch
from torch import nn
import numpy as np
torch.manual_seed(1)#生成随机数种子,确保每次得到的随机数一致
num_inputs = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2
features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b #严格意义上的标签
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)
#正态分布生成偏差用来模拟真实数据
import torch.utils.data as Data
batch_size = 10
# combine featues and labels of dataset
dataset = Data.TensorDataset(features, labels)
# put dataset into DataLoader
data_iter = Data.DataLoader(
dataset=dataset, # torch TensorDataset format
batch_size=batch_size, # mini batch size
shuffle=True, # whether shuffle the data or not #将数据无序放置
num_workers=2, # read data in multithreading
)
for X, y in data_iter:
print(X, '\n', y)
break
class LinearNet(nn.Module):
def __init__(self, n_feature):
super(LinearNet, self).__init__() # call father function to init
self.linear = nn.Linear(n_feature, 1) # function prototype: `torch.nn.Linear(in_features, out_features, bias=True)`
def forward(self, x):
y = self.linear(x)
return y
net = LinearNet(num_inputs)
print(net)
#三种构建模型的方式
# ways to init a multilayer network
# method one
net = nn.Sequential(
nn.Linear(num_inputs, 1)
# other layers can be added here
)
# method two
net = nn.Sequential()
net.add_module('linear', nn.Linear(num_inputs, 1))
# net.add_module ......
# method three
from collections import OrderedDict
net = nn.Sequential(OrderedDict([
('linear', nn.Linear(num_inputs, 1))
# ......
]))
print(net)
print(net[0]) #此时网络什么都没有
from torch.nn import init
#权重与偏置的定义
init.normal_(net[0].weight, mean=0.0, std=0.01)
init.constant_(net[0].bias, val=0.0) # or you can use `net[0].bias.data.fill_(0)` to modify it directly
for param in net.parameters():
print(param)
loss = nn.MSELoss() # nn built-in squared loss function
# function prototype: `torch.nn.MSELoss(size_average=None, #reduce=None, reduction='mean')`
import torch.optim as optim
optimizer = optim.SGD(net.parameters(), lr=0.03) # built-in random gradient descent function
print(optimizer) # function prototype: `torch.optim.SGD(params, lr=, momentum=0, dampening=0, weight_decay=0, nesterov=False)`
num_epochs = 3
for epoch in range(1, num_epochs + 1):
for X, y in data_iter:
output = net(X) #前面构建的网络模型
l = loss(output, y.view(-1, 1)) #计算预测值与真实值的差距
optimizer.zero_grad() # reset gradient, equal to net.zero_grad() #重置梯度,防止梯度叠加
l.backward() #反向传播计算梯度
optimizer.step() #权重与偏置的更新
print('epoch %d, loss: %f' % (epoch, l.item()))
# result comparision
dense = net[0]
print(true_w, dense.weight.data)
print(true_b, dense.bias.data)
下一步是学习__init__,forward()函数的使用
本文详细介绍了如何使用PyTorch实现线性回归,从数据生成、模型构建到训练过程,深入浅出地解析了每个步骤,是理解和实践机器学习不可多得的教程。

3054

被折叠的 条评论
为什么被折叠?



