pytorch之 regression

复制代码
 1 import torch
 2 import torch.nn.functional as F
 3 import matplotlib.pyplot as plt
 4 
 5 # torch.manual_seed(1)    # reproducible
 6 
 7 x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)  # x data (tensor), shape=(100, 1)
 8 y = x.pow(2) + 0.2*torch.rand(x.size())                 # noisy y data (tensor), shape=(100, 1)
 9 
10 # torch can only train on Variable, so convert them to Variable
11 # The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors
12 # x, y = Variable(x), Variable(y)
13 
14 # plt.scatter(x.data.numpy(), y.data.numpy())
15 # plt.show()
16 
17 
18 class Net(torch.nn.Module):
19     def __init__(self, n_feature, n_hidden, n_output):
20         super(Net, self).__init__()
21         self.hidden = torch.nn.Linear(n_feature, n_hidden)   # hidden layer
22         self.predict = torch.nn.Linear(n_hidden, n_output)   # output layer
23 
24     def forward(self, x):
25         x = F.relu(self.hidden(x))      # activation function for hidden layer
26         x = self.predict(x)             # linear output
27         return x
28 
29 net = Net(n_feature=1, n_hidden=10, n_output=1)     # define the network
30 print(net)  # net architecture
31 
32 optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
33 loss_func = torch.nn.MSELoss()  # this is for regression mean squared loss
34 
35 plt.ion()   # something about plotting
36 
37 for t in range(200):
38     prediction = net(x)     # input x and predict based on x
39 
40     loss = loss_func(prediction, y)     # must be (1. nn output, 2. target)
41 
42     optimizer.zero_grad()   # clear gradients for next train
43     loss.backward()         # backpropagation, compute gradients
44     optimizer.step()        # apply gradients
45 
46     if t % 5 == 0:
47         # plot and show learning process
48         plt.cla()
49         plt.scatter(x.data.numpy(), y.data.numpy())
50         plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)
51         plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color':  'red'})
52         plt.pause(0.1)
53 
54 plt.ioff()
55 plt.show()
复制代码

 

posted @   _Meditation  阅读(350)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示