织梦模板网站,附近网站建设公司,当雄网站建设,任务网站开发【【Pytorch】学习记录分享3——PyTorch 自动微分与线性回归 1. autograd 包#xff0c;自动微分2. 线性模型回归演示3. GPU进行模型训练 小结#xff1a;只需要将前向传播设置好#xff0c;调用反向传播接口#xff0c;即可实现反向传播的链式求导
1. autograd 包#x… 【【Pytorch】学习记录分享3——PyTorch 自动微分与线性回归 1. autograd 包自动微分2. 线性模型回归演示3. GPU进行模型训练 小结只需要将前向传播设置好调用反向传播接口即可实现反向传播的链式求导
1. autograd 包自动微分
自动微分是机器学习工具包必备的工具它可以自动计算整个计算图的微分。
PyTorch内建了一个叫做torch.autograd的自动微分引擎该引擎支持的数据类型为浮点数Tensor类型 ( half, float, double and bfloat16) 和复数Tensor 类型(cfloat, cdouble)
PyTorch中与自动微分相关的常用的Tensor属性和函数
属性requires_grad 默认值为False表明该Tensor不会被自动微分引擎计算微分。设置为True表明让自动微分引擎计算该Tensor的微分 属性grad存储自动微分的计算结果即调用backward()方法后的计算结果 方法backward(): 计算微分一般不带参数等效于backward(torch.tensor(1.0))。若backward()方法在DAG的root上调用它会依据链式法则自动计算DAG所有枝叶上的微分。 方法no_grad()禁用自动微分上下文管理 一般用于模型评估或推理计算这些不需要执行自动微分计算的地方以减少内存和算力的消耗。另外禁止在模型参数上自动计算微分即不允许更新该参数即所谓的冻结参数(frozen parameters)。 zero_grad()方法PyTorch的微分是自动积累的需要用zero_grad()方法手动清零
# 模型z xw b激活函数Softmax
x torch.ones(5) # 输入张量,shape(5,)
labels torch.zeros(3) # 标签值,shape(3,)
w torch.randn(5,3,requires_gradTrue) # 模型参数需要计算微分, shape(5,3)
b torch.randn(3, requires_gradTrue) # 模型参数需要计算微分, shape(3,)
z xw b # 模型前向计算
outputs torch.nn.functional.softmax(z) # 激活函数
print(z: ,z)
print(outputs: ,outputs)
loss torch.nn.functional.binary_cross_entropy(outputs, labels)
# 查看loss函数的微分计算函数
print(Gradient function for loss , loss.grad_fn)
# 调用loss函数的backward()方法计算模型参数的微分
loss.backward()
# 查看模型参数的微分值
print(w: ,w.grad)
print(b.grad: ,b.grad)小姐
方法描述.requires_grad 设置为True会开始跟踪针对 tensor 的所有操作.backward()张量的梯度将累积到 .grad 属性
import torchxtorch.rand(1)
btorch.rand(1,requires_gradTrue)
wtorch.rand(1,requires_gradTrue)
y w * x
z y bx.requires_grad, w.requires_grad,b.requires_grad,y.requires_grad,z.requires_gradprint(x: ,x, end\n),print(b: ,b ,end\n),print(w: ,w ,end\n)
print(y: ,y, end\n),print(z: ,z, end\n)# 反向传播计算
z.backward(retain_graphTrue) #注意如果不清空b每一次更新都会自我累加起来依次为1 2 3 4 。。。w.grad
b.grad运行结果 反向传播求导原理
2. 线性模型回归演示 import torch
import torch.nn as nn## 线性回归模型 本质上就是一个不加 激活函数的 全连接层
class LinearRegressionModel(nn.Module):def __init__(self, input_size, output_size):super(LinearRegressionModel, self).__init__()self.linear nn.Linear(input_size, output_size)def forward(self, x):out self.linear(x)return out
input_size 1
output_size 1model LinearRegressionModel(input_size, output_size)
model# 指定号参数和损失函数
epochs 500
learning_rate 0.01
optimizer torch.optim.SGD(model.parameters(), lrlearning_rate)
criterion nn.MSELoss()# train model
for epoch in range(epochs):epochs1#注意 将numpy格式的输入数据转换成 tensorinputs torch.from_numpy(x_train)labels torch.from_numpy(y_train)#每次迭代梯度清零optimizer.zero_grad()#前向传播outputs model(inputs)#计算损失loss criterion(outputs, labels)#反向传播loss.backward()#updates weight and parametersoptimizer.step()if epoch % 50 0:print(Epoch: {}, Loss: {}.format(epoch, loss.item()))# predict model test,预测结果并且奖结果转换成np格式
predicted model(torch.from_numpy(x_train).requires_grad_()).data.numpy()
predicted#model save
torch.save(model.state_dict(),model.pkl)#model 读取
model.load_state_dict(torch.load(model.pkl)) 3. GPU进行模型训练
只需要 将模型和数据传入到“cuda”中运行即可,详细实现见截图
import torch
import torch.nn as nn
import numpy as np# #构建一个回归方程 y 2*x1#构建输如数据将输入numpy格式转成tensor格式
x_values [i for i in range(11)]
x_train np.array(x_values,dtypenp.float32)
x_train x_train.reshape(-1,1)y_values [2*i 1 for i in x_values]
y_train np.array(y_values, dtypenp.float32)
y_train y_train.reshape(-1,1)## 线性回归模型 本质上就是一个不加 激活函数的 全连接层
class LinearRegressionModel(nn.Module):def __init__(self, input_size, output_size):super(LinearRegressionModel, self).__init__()self.linear nn.Linear(input_size, output_size)def forward(self, x):out self.linear(x)return outinput_size 1
output_size 1model LinearRegressionModel(input_size, output_size)device torch.device(cuda if torch.cuda.is_available() else cpu)
model.to(device)# 指定号参数和损失函数
epochs 500
learning_rate 0.01
optimizer torch.optim.SGD(model.parameters(), lrlearning_rate)
criterion nn.MSELoss()# train model
for epoch in range(epochs):epochs1#注意 将numpy格式的输入数据转换成 tensorinputs torch.from_numpy(x_train)labels torch.from_numpy(y_train)#每次迭代梯度清零optimizer.zero_grad()#前向传播outputs model(inputs)#计算损失loss criterion(outputs, labels)#反向传播loss.backward()#updates weight and parametersoptimizer.step()if epoch % 50 0:print(Epoch: {}, Loss: {}.format(epoch, loss.item()))# predict model test,预测结果并且奖结果转换成np格式
predicted model(torch.from_numpy(x_train).requires_grad_()).data.numpy()
predicted#model save
torch.save(model.state_dict(),model.pkl)