pytorch FC_regression

import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
torch.manual_seed(100)

## 生成数据
x = torch.linspace(-1, 1, 100).view(-1,1)  # shape=(100, 1),(batch,dim)
y = x.pow(2) + 0.2*torch.rand(x.shape)  # shape=(100, 1),(batch,dim)
# plt.scatter(x.numpy(), y.numpy())
# plt.show()

## 构建网络
class Net(torch.nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.hidden = torch.nn.Linear(1, 10)
        self.output = torch.nn.Linear(10, 1)

    def forward(self, x):
        x = F.relu(self.hidden(x))
        x = self.output(x)
        return x

## 初始化网络,优化器和损失函数
net = Net()
optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
mse = torch.nn.MSELoss()
## 开始训练
for t in range(200):
    prediction = net(x)
    loss = mse(prediction, y)
    optimizer.zero_grad() 
    loss.backward()
    optimizer.step() 
    
    # 可视化
    if t % 5 == 0:
        plt.scatter(x.numpy(), y.numpy())
        plt.plot(x.numpy(), prediction.detach().numpy(), 'r-', lw=5)
        plt.text(0.5, 0, 'Loss=%.4f' % loss.detach().numpy(), fontdict={'size': 20, 'color':  'red'})
        plt.pause(0.2)
        plt.clf() # 清除当前图像
plt.show()

参考:
https://github.com/MorvanZhou/PyTorch-Tutorial/blob/master/tutorial-contents/301_regression.py

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值