04-pytorch

Posted liu247

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了04-pytorch相关的知识,希望对你有一定的参考价值。

import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
# 把一维变二维
x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
y = x.pow(2) + 0.2*torch.rand(x.size())
x, y= Variable(x),Variable(y)

打印散点图

# plt.scatter(x.data.numpy(),y.data.numpy())
# plt.show()

定义时必须要继承torch.nn.Module

        继承两次
        然后定义每层的结点数

然后进行向前传播的过程

# 定义神经网络
class Net(torch.nn.Module):
    def __init__(self,n_feature,n_hidden,n_output,):
        super(Net,self).__init__()
        self.hidden = torch.nn.Linear(n_feature,n_hidden)
        self.predict = torch.nn.Linear(n_hidden,n_output)
        
    
    def forward(self,x):
        x = F.relu(self.hidden(x))
        x = self.predict(x)
        return x
net = Net(1,10,1)
# 打印这个神经网络
print(net)
# 定义优化器和损失函数
optimizer = torch.optim.SGD(net.parameters(),lr=0.5)
loss_func = torch.nn.MSELoss()
Net(
  (hidden): Linear(in_features=1, out_features=10, bias=True)
  (predict): Linear(in_features=10, out_features=1, bias=True)
)
for i in range(100):
    prediction = net(x)
    
    loss = loss_func(prediction,y)
    # 优化
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    if i % 20 == 0:
        # 打印误差
            print(loss)
tensor(0.1574, grad_fn=<MseLossBackward>)
tensor(0.0912, grad_fn=<MseLossBackward>)
tensor(0.0687, grad_fn=<MseLossBackward>)
tensor(0.0310, grad_fn=<MseLossBackward>)
tensor(0.0188, grad_fn=<MseLossBackward>)

只能预测torch格式的数据

        先变torch,在变Variable
       在预测使用net(x)
x1 = torch.FloatTensor([1])
x1 = torch.unsqueeze(x1,dim=1)
x1 = Variable(x1)
net(x1)
tensor([[0.9546]], grad_fn=<AddmmBackward>)

以上是关于04-pytorch的主要内容,如果未能解决你的问题,请参考以下文章