主要参考莫烦regression讲解:
关系拟合 (回归) – PyTorch | 莫烦Python
回归问题是一类非常简单但是非常经典的问题,如预测房价
有很多种解决方式,比如NG的机器学习课程matlab作业
用tf也可以写,但是就是挺麻烦的
但是用pytorch写出来真的很轻松,并且特别好理解
以下是代码(基本和莫烦大大一样,我只是重新用手敲了一遍!)
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import matplotlib.pyplot as plt
#fake data
x = torch.unsqueeze(torch.linspace(-1,1,100), dim=1)
y = x.pow(2) + 0.2*torch.rand(x.size())
#Variable
x,y = Variable(x), Variable(y)
#plot
#plt.scatter(x.data.numpy(), y.data.numpy())
#plt.show()
#class
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(1,10,1)
plt.ion()
plt.show()
optimizer = torch.optim.SGD(net.parameters(), lr=0.5)
loss_func = torch.nn.MSELoss()
for t in range(1000):
prediction = net(x)
loss = loss_func(prediction, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 接着上面来
if t % 5 == 0:
# plot and show learning process
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.data[0], fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1)