Pytorch入门-1

 2023-09-15 阅读 22 评论 0

摘要:Pytorch的一些常见的用法 pytorch的一些操作和numpy比较类似,对于熟悉numpy的人比较友好,下面总结一些用法: Tensor (张量) ,有32 位浮点型torch.FloatTensor 、64 位浮点型torch.DoubleTensor 、16 位整型torch.Shor tTensor 、32 位整型torch.l

Pytorch的一些常见的用法

pytorch的一些操作和numpy比较类似,对于熟悉numpy的人比较友好,下面总结一些用法:

  • Tensor (张量) ,有32 位浮点型torch.FloatTensor 、64 位浮点型torch.DoubleTensor 、16 位整型torch.Shor tTensor 、32 位整型torch.lntTensor 和64 位整型torch.LongTensor。
    针对上面的内容,写几个常见的例子:
# 定义一个三行两列给定元素的矩阵
a = torch. Tensor ([[2 , 3), [4 , 8), [7 , 9]])
b = torch. LongTensor ([[2 , 3] [4 , 8], [7 , 911])
c = torch.zeros((3 , 2))
d = torch.randn((3 , 2))# tensor和numpy之间相互转换
numpy_b = b.numpy()  # 转成numpy
torch.from_numpy(e)  # 转成tensor# 判断是否支持GPU加速
torch.cuda.is available()
  • Variable (变量)

Variable 提供了自动求导的功能,Variable 会被放入一个计算图中,然后进行前向传播,反向传播,自动求导,需要引入 torch.autograd.Variable,如想让一个tensor 变成Variable ,只需要Variable(a) 就可以了,Variable 有三个比较重要的组成属性: data , grad 和grad_fn通过data 可以取出Variable 里面的tensor 数值, grad_fn 表/j,的是得到这个Variable 的操作,比如通过加减还是乘除来得到的,最后grad 是这个Variabel 的反向传播梯度,下面给出一个例子:

X = Variable(torch.Tensor ([1]) , requìres_grad=True)
W = Variable(torch.Tensor([2]) , requires_grad=True)
b = Variable(torch.Tensor([3]) , requires_grad=True)y = w * x + b    # 构建一张计算图y.backward()  # 自动求导,这是标量求导所以可以直接这么写
# 下面计算梯度
print(x.grad)  # y.grad = 2
print(w.grad)  # w.grad = 1
print (b.grad) # b .grad =1
# 如果是矩阵求导
x = torch.randn(3)
x = Variable(x, requires_grad=True)
y = 2 * x
print(y)
y.backward(torch.FloatTensor([1, 0.1, 0.01]))
print(x. grad)

这里需要说明的是 [1, 0.1, 0.01] 这三个参数是他们得到的原本的梯度再乘上[1, 0.1, 0.01],结果是tensor([2.0000, 0.2000, 0.0200])


下面给一个用torch实现多项式回归的例子(本段代码转载自 原文):

import torch
import numpy as np
from torch import nn
from torch.autograd import Variable
from torch import optim
plt.rcParams['font.sans-serif'] = ['SimHei']  # 这里两行导入字体
plt.rcParams['axes.unicode_minus'] = Falsedef make_feature(x):x = x.unsqueeze(1)  # unsqueeze(1) 是将原来的tensor 大小由3 变成(3 , 1),return torch.cat([x**i for i in range(1,4)], 1)w_target = torch.FloatTensor([0.5,3,2.4]).unsqueeze(1)
b_target = torch.FloatTensor([0.9])def f(x):return x.mm(w_target)+b_target[0]def get_batch(batch_size=32):random = torch.randn(batch_size)  x = make_feature(random)y = f(x)if torch.cuda.is_available():return Variable(x).cuda(), Variable(y).cuda()else:return Variable(x), Variable(y)class poly_model(nn.Module):def __init__(self):super(poly_model,self).__init__();self.poly = nn.Linear(3,1)def forward(self, x):out = self.poly(x)return outif torch.cuda.is_available():model = poly_model().cuda()
else:model = poly_model()criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(),lr=1e-3)epoch = 0
while True:batch_x, batch_y = get_batch()# 向前传播output = model(batch_x)loss = criterion(output, batch_y)print_loss = loss.item()
# 重新设置梯度optimizer.zero_grad()loss.backward()  # 反向传播
# 调整参数,优化optimizer.step()epoch+= 1if print_loss < 1e-3:breakprint("epoches : {}".format(epoch))
print("==> Learned function: y = {:.2f} + {:.2f}*x + {:.2f}*x^2 + {:.2f}*x^3".format(model.poly.bias[0], model.poly.weight[0][0],model.poly.weight[0][1],model.poly.weight[0][2]))
print("==> Actual function: y = {:.2f} + {:.2f}*x + {:.2f}*x^2 + {:.2f}*x^3".format(b_target[0], w_target[0][0],w_target[1][0], w_target[2][0]))
# 下面是可视化部分predict = model(batch_x)
x = batch_x.cpu().numpy()[:, 0]  # x~1 x~2 x~3
plt.plot(x, batch_y.cpu().numpy(), 'ro')
plt.title(label='可视化真实数据')
plt.show()
# 2.可视化拟合函数
predict = predict.data.cpu().numpy()
plt.plot(x, predict, 'b')
plt.plot(x, batch_y.cpu().numpy(), 'ro')
plt.title(label='可视化拟合函数')
plt.show()
# 3.可视化训练次数和损失
plt.plot(ctn, lo)
plt.xlabel('训练次数')
plt.ylabel('损失值')
plt.title(label='训练次数与损失关系')
plt.show()

torch教程。结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


torch实现logistic回归

import torch
from torch import nn
from torch.autograd import Variable#构造数据
n_data = torch.ones(100,2)
x0 = torch.normal(2*n_data)
y0 = torch.zeros(100)
x1 = torch.normal(-2*n_data)
y1 = torch.ones(100)x = torch.cat((x0,x1)).type(torch.FloatTensor)
y = torch.cat((y0,y1)).type(torch.FloatTensor)#定义LogisticRegression
class LogisticRegression(nn.Module):def __init__(self):super(LogisticRegression,self).__init__()self.lr = nn.Linear(2,1)self.sm = nn.Sigmoid()def forward(self,x):x = self.lr(x)x = self.sm(x)return xlogistic_model = LogisticRegression()
criterion = nn.BCELoss()  # 这里是二分类问题的损失函数
optimizer = torch.optim.SGD(logistic_model.parameters(),lr = 1e-3,momentum=0.9) # 随机梯度下降#训练过程
for epoch in range(10000):x_data = Variable(x)y_data = Variable(y)out = logistic_model(x_data)loss = criterion(out,y_data)print_loss = loss.data.item()# 判断输出的结果如果大于0.5就=1,小于0.5就=0,通过这个计算这个模型的准确率mask = out.ge(0.5).float()correct = (mask == y_data).sum()acc = correct.item()/x_data.size(0)optimizer.zero_grad()loss.backward()optimizer.step()if (epoch+1)%20 == 0:print('*'*10)print('epoch {}'.format(epoch+1))print('loss is {:.4f}'.format(print_loss))print('acc is {:.4f}'.format(acc))#参数输出
w0,w1 = logistic_model.lr.weight[0]
w0 = float(w0.item())
w1 = float(w1.item())
b = float(logistic_model.lr.bias.item())print('w0:{}\n'.format(w0),'w1:{}\n'.format(w1),'b:{0}'.format(b))

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/62029.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息