当前位置:   article > 正文

2层感知机(神经网络)实现非线性回归(非线性拟合)【pytorch】

两层非线性神经网络
  1. import torch
  2. import numpy
  3. import random
  4. from torch.autograd import Variable
  5. import torch.nn.functional as F
  6. import matplotlib.pyplot as plt
  7. x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
  8. y = x.pow(2)+0.2*torch.rand(x.size())
  9. x,y = Variable(x),Variable(y)
  10. plt.ion()
  11. class Net(torch.nn.Module):
  12. def __init__(self,n_feature,n_hidden,n_output):
  13. super(Net,self).__init__()
  14. #两层感知机
  15. self.hidden = torch.nn.Linear(n_feature,n_hidden)
  16. self.predict = torch.nn.Linear(n_hidden,n_output)
  17. def forward(self,x):
  18. x = F.relu(self.hidden(x))
  19. x = self.predict(x)
  20. return x
  21. net = Net(1,8,1) #输入节点1个,隐层节点8个,输出节点1个
  22. optimizer = torch.optim.SGD(net.parameters(),lr = 0.2)
  23. loss_func = torch.nn.MSELoss()
  24. for t in range(200):
  25. prediction = net(x)
  26. loss = loss_func(prediction,y)
  27. optimizer.zero_grad()
  28. loss.backward()
  29. optimizer.step()
  30. if t%5==0:
  31. plt.cla()
  32. plt.scatter(x.data.numpy(),y.data.numpy())
  33. plt.plot(x.data.numpy(),prediction.data.numpy(),'r-',lw=5)
  34. plt.pause(0.1)
  35. plt.ioff()
  36. plt.show()

  

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

闽ICP备14008679号