当前位置:网站首页>Pytorch implementation of regression model

Pytorch implementation of regression model

2022-06-12 06:06:00 Singing under the hedge


pytorch Implement the regression model

One 、 Code

import  torch
import  torch.nn.functional as F
import matplotlib.pyplot as plt
# Build datasets 
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)
# Building neural networks 
# Method 1 :
# class Net(torch.nn.Module):
# def __init__(self,n_feature,n_hidden,n_output):
# super(Net,self).__init__()# Inherit __init__ function 
# # Define the form of each layer 
# self.hidden = torch.nn.Linear(n_feature,n_hidden)# Hidden layer linear output 
# self.output = torch.nn.Linear(n_hidden,n_output)# Output layer linear output 
#
# def forward(self,x):
# x = F.relu(self.hidden(x))# Activation function 
# x = self.output(x)# Output value 
# return x
# net = Net(n_feature=1,n_hidden=10,n_output=1)
# Method 2 :
net = torch.nn.Sequential(
    torch.nn.Linear(1,10),
    torch.nn.ReLU(),
    torch.nn.Linear(10,1)
)
# visualization 
plt.ion()
plt.show()
# Training network 
optimizer = torch.optim.SGD(net.parameters(),lr=0.2)# Stochastic gradient descent , Pass in net All parameters of , Learning rate 
loss_func = torch.nn.MSELoss()# Loss function ( Mean square error )
for t in range(100):
    pre_y = net(x)# to net Training data , Output predicted value 
    loss = loss_func(pre_y,y)# Calculate the loss function 
    optimizer.zero_grad()# Clear the residual update parameter value of the previous step 
    loss.backward()# Error back propagation 
    optimizer.step()# Add new parameter update values to net Of parameters On 
    # mapping 
    if t%5 == 0 :
        plt.cla()
        plt.scatter(x.data.numpy(),y.data.numpy())
        plt.plot(x.data.numpy(),pre_y.data.numpy(),'r_',lw=5)
        plt.text(0.5,0,'Loss=%.4f'%loss.data.numpy(),fontdict={
    'size':20,'color':'red'})
        plt.pause(0.1)

Two 、 Realization effect

 Insert picture description here

原网站

版权声明
本文为[Singing under the hedge]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010612306976.html