import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt # torch.manual_seed(1) # reproducible x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # x data (tensor), shape=(100, 1)
y = x.pow(2) + 0.2*torch.rand(x.size()) # noisy y data (tensor), shape=(100, 1) # torch can only train on Variable, so convert them to Variable
# The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors
# x, y = Variable(x), Variable(y) # plt.scatter(x.data.numpy(), y.data.numpy())
# plt.show() 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) # hidden layer
self.predict = torch.nn.Linear(n_hidden, n_output) # output layer def forward(self, x):
x = F.relu(self.hidden(x)) # activation function for hidden layer
x = self.predict(x) # linear output
return x net = Net(n_feature=1, n_hidden=10, n_output=1) # define the network
print(net) # net architecture optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
loss_func = torch.nn.MSELoss() # this is for regression mean squared loss plt.ion() # something about plotting for t in range(200):
prediction = net(x) # input x and predict based on x loss = loss_func(prediction, y) # must be (1. nn output, 2. target) optimizer.zero_grad() # clear gradients for next train
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients if t % 5 == 0:
# plot and show learning process
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1) plt.ioff()
plt.show()

最新文章

  1. 基于 SailingEase WinForm Framework 开发优秀的客户端应用程序(目录)
  2. manachor
  3. ubuntu安装eclipse配置jdk环境
  4. JQuery mobile 实例 api
  5. 设计模式:职责链模式(Chain Of Responsibility)
  6. [ 转]Android快速开发–使用ORMLite操作数据库
  7. 使用HttpClient访问被保护资源
  8. [ZOJ 1010] Area (计算几何)
  9. unity3d 雪与沙的渲染
  10. openlayers调用瓦片地图分析
  11. MySQL单行函数
  12. 【转】Powershell与jenkins集成部署的运用(powershell运用)
  13. [转]Go语言中的make和new
  14. [Model] ResNet
  15. MATLAB 的条件分支语句
  16. SQL数据库简单的建立与操作
  17. SQLSERVER2012里的扩展事件初尝试(上)
  18. Tomcat性能优化方案
  19. 面试-Hash是怎么实现的?
  20. Zabbix学习之路(三)之使用SMTP发送邮件报警及定制邮件报警内容

热门文章

  1. 趣谈编程史第2期-这个世界缺少对C语言的敬畏,你不了解的C语言科普
  2. 重拾c++第二天(4):复合类型
  3. Spring-cloud微服务实战【二】:eureka注册中心(上)
  4. 如何设计一个优雅的RESTFUL的接口
  5. FileUpload的控件上传excel
  6. SpringCloud之Ribbon(四)
  7. ssm之spring+springmvc+mybatis整合初探
  8. Flsak学习笔记(1)
  9. .net core webapi搭建(2)跨域
  10. 【数据结构】FHQ Treap详解