码迷,mamicode.com
首页 > 其他好文 > 详细

04-pytorch

时间:2019-07-07 12:21:57      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:mat   optimize   show   二维   优化器   function   def   att   ram   

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

标签:mat   optimize   show   二维   优化器   function   def   att   ram   

原文地址:https://www.cnblogs.com/liu247/p/11145597.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!