PyTorch实现可视化一元线性回归的Demo2(神经网络版)

一、环境

OS:Ubuntu 18.04
Environment: PyTorch&Anaconda3
Editor: Spyder

二、代码部分

比使用二乘法手工回归的版本:PyTorch实现可视化一元线性回归的Demo
有如下差别:
1、使用了神经网络
2、使用了自带的loss函数

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 28 17:38:22 2020

@author: ftimes
"""

import torch
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F

x = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
                    [9.779], [6.182], [7.59], [2.167], [7.042],
                    [10.791], [5.313], [7.997], [3.1]], dtype=np.float32)

y = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
                    [3.366], [2.596], [2.53], [1.221], [2.827],
                    [3.465], [1.65], [2.904], [1.3]], dtype=np.float32) 


plt.title('initial value')
plt.figure(1)    
plt.plot(x, y, 'bo')


#trans to tensor
x = torch.from_numpy(x)
y = torch.from_numpy(y)



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)   
        self.predict = torch.nn.Linear(n_hidden, n_output)   
    def forward(self, x):   
        x = F.relu(self.hidden(x))      
        x = self.predict(x)             
        return x

net = Net(n_feature=1, n_hidden=10, n_output=1)

# optimizer 
learningRate=1e-2
optimizer = torch.optim.SGD(net.parameters(), learningRate)
loss_func = torch.nn.MSELoss()

print("Please input times of update: ")
times=int(input())

for t in range(times):
    prediction = net(x)
    loss = loss_func(prediction, y)   
    optimizer.zero_grad()  
    loss.backward()    
    optimizer.step()
    
plt.figure(2)
plt.title('after update')
plt.plot(x.data.numpy(), y.data.numpy(), 'bo', label='real')
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', label='estimated')
plt.legend()

三、示例

Please input times of update:

100

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值