传统机器学习中,实现线性回归的方法,是先手推公式,得出 θ 的表达式,然后计算得出。但在深度学习中,方法会更简单粗暴,而且拟合效果更好。以下介绍使用 Pytorch 通过深度学习的方法,实现线性回归算法。

代码示例

1、创建x变量

import torch
x = torch.linspace(-1, 1, 100, requires_grad=True)
x = x.view(-1, 1)  # change shape
y = x**2 + 0.2 * torch.rand(x.size())

2、画图显示

from matplotlib import pyplot as plt
plt.scatter(x.data.numpy(), y.data.numpy())
plt.show()

3、建立网络模型

参考文档:https://pytorch.org/tutorials/beginner/introyt/modelsyt_tutorial.html

import torch.nn as nn
class LModule(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(1, 10)
        self.activation = nn.ReLU()
        self.linear2 = nn.Linear(10, 1)

    def forward(self, x):
        x = self.linear1(x)
        x = self.activation(x)
        x = self.linear2(x)
        return x

4、训练模型

参考文档:https://pytorch.org/tutorials/beginner/introyt/trainingyt.html

optimizer = torch.optim.SGD(lmodule.parameters(), lr=0.1)
loss_fn = nn.MSELoss()

for t in range(1000):
    pred_y = lmodule(x)
    loss = loss_fn(pred_y, y)

    optimizer.zero_grad()
    loss.backward(retain_graph=True)
    optimizer.step()

5、动图显示训练过程

from matplotlib import pyplot as plt
plt.ion() 
plt.show()

# plot and show learning process
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), pred_y.data.numpy(), 'r-', lw=5)
plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 15, 'color':  'red'})
plt.pause(0.1)

本文为 陈华 原创,欢迎转载,但请注明出处:http://www.ichenhua.cn/read/242