当前位置:网站首页>Pytorch build progression

Pytorch build progression

2022-06-26 08:54:00 Thick Cub with thorns

pytorch build Regression

Introduction to neural network construction

import torch
import matplotlib.pyplot as plt
from torch.autograd import Variable
import torch.nn.functional as F

x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)
y = x.pow(2) + 0.2 * torch.rand(x.size())

X, Y = Variable(x), Variable(y)

plt.scatter(X.data.numpy(), Y.data.numpy())
plt.show()

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-wMxlF2h6-1644318579449)(img/1.png)]

Construction noise scatter

Building neural network

class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_output):
        #  features , Hidden layer , Output layer 
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)
        self.predict = torch.nn.Linear(n_hidden, n_output)


    def forward(self, x): #  The process of forward transmission 
        x = F.relu(self.hidden(x))
        x = self.predict(x) #  The value range is not changed during prediction 
        return x


net = Net(1, 10, 1)
print(net)

out

Net(
  (hidden): Linear(in_features=1, out_features=10, bias=True)
  (predict): Linear(in_features=10, out_features=1, bias=True)
)

The optimizer optimizes

plt.ion() #  Real time printing 
plt.show()

#  Optimizing neural networks 

optimizer = torch.optim.SGD(net.parameters(), lr=0.5)
loss_func = torch.nn.MSELoss()

for i in range(100): #  Train 100 steps 
    prediction = net(x) #

    loss = loss_func(prediction, y) #  error 

    optimizer.zero_grad() #  First the gradient is reduced to 0
    loss.backward() #  Reverse transfer 
    optimizer.step() #  Optimize the gradient 

    if i % 5 == 0:
        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.item(), fontdict={
    'size': 20, 'color': 'red'})
        plt.pause(0.1)

plt.ioff()
plt.show()

out

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-a9WHfeK6-1644318579451)(img/2.png)]

.pause(0.1)

plt.ioff()
plt.show()




**out**

[ Outside the chain picture transfer in ...(img-a9WHfeK6-1644318579451)]



原网站

版权声明
本文为[Thick Cub with thorns]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170554154811.html