当前位置:   article > 正文

pytorch白话入门笔记1.6-快速搭建神经网络_torch1.6需要python

torch1.6需要python

目录

 

1.快速搭建神经网络

(1)代码

(2)运行结果


1.快速搭建神经网络

(1)代码

  1. import torch
  2. from torch.autograd import Variable
  3. import torch.nn.functional as F
  4. import matplotlib.pyplot as plt
  5. n_data= torch.ones(100,2)
  6. x0 = torch.normal(2*n_data,1)
  7. y0 = torch.zeros(100)
  8. x1 = torch.normal(-2*n_data,1)
  9. y1 = torch.ones(100)
  10. x = torch.cat((x0,x1),0).type(torch.FloatTensor)
  11. y = torch.cat((y0,y1),0).type(torch.LongTensor)
  12. x,y = Variable(x),Variable(y)
  13. # plt.scatter(x.data.numpy()[:,0],x.data.numpy()[:,1],c= y.data.numpy(),s=100,lw =0,cmap ='RdYlGn')
  14. # plt.show()
  15. # Net __init__()
  16. # methord 1
  17. class Net(torch.nn.Module):#继承module
  18. def __init__(self,n_features,n_hidden,n_output):
  19. super(Net,self).__init__()#官方步骤,继承
  20. self.hidden = torch.nn.Linear(n_features,n_hidden)
  21. self.predict = torch.nn.Linear(n_hidden,n_output)#预测
  22. def forward(self,x):
  23. # 前向传递过程,搭建神经网络
  24. x = F.relu(self.hidden(x))#一个function
  25. x = self.predict(x)
  26. return x
  27. net = Net(2,10,2) #输入、隐藏层、输出分别为1101
  28. #哪个位置为1就是其对应分类
  29. #methord 2【新的快速搭建方法】
  30. net2 = torch.nn.Sequential(
  31. #一层一层磊神经层
  32. torch.nn.Linear(2,10),
  33. torch.nn.ReLU(),#层的类
  34. torch.nn.Linear(10,2),
  35. )
  36. print(net)
  37. print(net2)

(2)运行结果

  1. Net(
  2. (hidden): Linear(in_features=2, out_features=10, bias=True)
  3. (predict): Linear(in_features=10, out_features=2, bias=True)
  4. )
  5. Sequential(
  6. (0): Linear(in_features=2, out_features=10, bias=True)
  7. (1): ReLU()
  8. (2): Linear(in_features=10, out_features=2, bias=True)
  9. )
  10. Process finished with exit code 0

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/358181
推荐阅读
相关标签
  

闽ICP备14008679号