深度学习中有两大类问题:回归和分类。
本篇博客主要介绍采用PyTorch来解决回归问题。
下面是示例代码:
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
# 生成假数据
# torch.unsqueeze() 的作用是将一维变二维,torch只能处理二维的数据
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1) # x data (tensor), shape(100, 1)
# 0.2 * torch.rand(x.size())增加噪点
y = x.pow(2) + 0.2 + 0.2 * torch.rand(x.size())
# 将Tensor转换为torch
x, y = Variable(x), Variable(y)
# 打印数据散点图
# plt.scatter(x.data.numpy(), y.data.numpy())
# plt.show()
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