神经网络(pytorch框架)回归预测

使用神经网络做回归预测。最终效果如下:

神经网络(pytorch框架)回归预测_第1张图片

引入需要的模块:

import math
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn

生成仿真数据:

def generate_data():
    y=[]
    x=[]
    for i in np.arange(0,5,0.1):
        x.append(i)
        y.append(math.cos(i)+np.random.uniform(-0.1,0.1))
    plt.scatter(x,y)
    plt.show()
    return np.array(x),np.array(y)

 构建神经网络模型:

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
                    
        self.fc =nn.Sequential(
                nn.Linear(1,10),
                nn.ReLU(),
                nn.Linear(10,1),
                )
    def forward(self, x):
        out = self.fc(x)
        return out

 训练模型:

def train(net,x,y):
    optimizer=torch.optim.Adam(net.parameters(), lr=0.01, betas=(0.90, 0.99), eps=1e-8, weight_decay=0., amsgrad=False)
    loss_func=nn.MSELoss()
    x=torch.from_numpy(x).float()
    y=torch.from_numpy(y).float()
    for e in range(500):
        outputs=net(x.view(-1,1,1))
        loss=loss_func(outputs.view(-1),y.view(-1).float())
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if (e)%10==0:
            print('epoch=',e,',loss=',loss)
            test(net,x,y,e)

测试模型,绘制并保存结果值figure文件夹下:

def test(net,x,y,e):
    predict=net(x.view(-1,1,1))
    y_pre=predict.view(-1).detach().numpy()
    plt.scatter(x,y,color='g')
    plt.plot(x,y_pre,color='r')
    plt.savefig('./figure/'+str(e)+'.png')
    plt.pause(0.05)

完整代码如下:

import math
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn


def generate_data():
    y=[]
    x=[]
    for i in np.arange(0,5,0.1):
        x.append(i)
        y.append(math.cos(i)+np.random.uniform(-0.1,0.1))
    plt.scatter(x,y)
    plt.show()
    return np.array(x),np.array(y)

class Net(nn.Module):#84,75
    def __init__(self):
        super(Net, self).__init__()
                    
        self.fc =nn.Sequential(
                nn.Linear(1,10),
                nn.ReLU(),
                nn.Linear(10,1),
                )
    def forward(self, x):
        out = self.fc(x)
        return out

def train(net,x,y):
    optimizer=torch.optim.Adam(net.parameters(), lr=0.01, betas=(0.90, 0.99), eps=1e-8, weight_decay=0., amsgrad=False)
    loss_func=nn.MSELoss()
    x=torch.from_numpy(x).float()
    y=torch.from_numpy(y).float()
    for e in range(500):
        outputs=net(x.view(-1,1,1))
        loss=loss_func(outputs.view(-1),y.view(-1).float())
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        if (e)%10==0:
            print('epoch=',e,',loss=',loss)
            test(net,x,y,e)
            
           
def test(net,x,y,e):
    predict=net(x.view(-1,1,1))
    y_pre=predict.view(-1).detach().numpy()
    plt.scatter(x,y,color='g')
    plt.plot(x,y_pre,color='r')
    plt.savefig('./figure/'+str(e)+'.png')
    plt.pause(0.05)
if __name__=='__main__':
    x,y=generate_data()
    net=Net()
    train(net,x,y)

上述保存在figure文件夹下的结果图中的gif动画绘制代码如下:(最终的gif结果图在当前文件夹下的regression.gif中)

from PIL import Image 
import imageio
import numpy as np
if __name__=='__main__':
    file_names,frames=[],[]
    for i in range(0,500,10):
        file_names.append('figure/'+str(i)+'.png')
        print(file_names)
    for image_name in file_names:
        im=Image.open(image_name)
        im=im.convert('RGB')
        im=np.array(im)
        frames.append(im)
    imageio.mimsave('regression.gif', frames, 'GIF', duration=0.1)

你可能感兴趣的:(神经网络,pytorch,回归,神经网络)