pytorch学习(四)回归问题

我们学习pytorch的目的是进行深度学习,而深度学习可以干哪些事呢?主要有两个:1)回归问题,2)分类问题。何谓回归,线性回归大家一定都学过,通俗来讲就是给定坐标系下一些点,来用一条曲线进行拟合,以描绘这些样本点的变化趋势,这就是回归。
下面就通过代码实例来学习,通过一些数据来拟合一条回归曲线。具体讲解请参考莫烦pythons(代码来源)

# 首先导入所需要的模块
import torch  
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
#  构建数据
x = torch.unsqueeze(torch.linspace(-1, 1, 100), dim=1)  # x data (tensor), shape=(100, 1)
#  因为在torch中数据是有维度的,通过linspace生成的是[-1, 1]之间的100个一维数据格式为[1, 2, 3]这样的,通过unaqueeze可以使这些数据有维度,通过dim=1参数设定这些数在列上,如果设定dim=0则设定这些数在行上,此时这100个数为一列,它的shape为(100, 1),形式是[[1], [2]]这样的,这一操作是必须的,可以死记住
y = x.pow(2) + 0.2*torch.rand(x.size())                 # noisy y data (tensor), shape=(100, 1)

# torch can only train on Variable, so convert them to Variable
# The code below is deprecated in Pytorch 0.4. Now, autograd directly supports tensors
# 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)   # hidden layer
        self.predict = torch.nn.Linear(n_hidden, n_output)   # output layer

    def forward(self, x):
        x = F.relu(self.hidden(x))      # activation function for hidden layer
        x = self.predict(x)             # linear output
        return x

net = Net(n_feature=1, n_hidden=10, n_output=1)     # define the network
print(net)  # net architecture

optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
loss_func = torch.nn.MSELoss()  # this is for regression mean squared loss

plt.ion()   # something about plotting

for t in range(200):
    prediction = net(x)     # input x and predict based on x

    loss = loss_func(prediction, y)     # must be (1. nn output, 2. target)

    optimizer.zero_grad()   # clear gradients for next train
    loss.backward()         # backpropagation, compute gradients
    optimizer.step()        # apply gradients

    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.numpy(), fontdict={'size': 20, 'color':  'red'})
        plt.pause(0.1)

plt.ioff()
plt.show()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch一个流行的深度学习框架,它提供了丰富的工具和函数来进行迁移学习回归任务。迁移学习是指利用已经训练好的模型在新的任务上进行微调或者特征提取的技术。 在PyTorch中,可以使用预训练的模型作为基础模型,然后根据具体任务进行微调或者特征提取。以下是一般的迁移学习回归的步骤: 1. 加载预训练模型:PyTorch提供了一些常用的预训练模型,如ResNet、VGG等。可以使用torchvision库来加载这些模型。 2. 冻结模型参数:为了保持预训练模型的特征提取能力,通常会冻结模型的参数,即不对其进行更新。可以通过设置requires_grad=False来实现。 3. 替换或添加全连接层:根据具体任务的输出要求,可以替换或者添加全连接层。全连接层通常用于将模型的输出映射到具体的回归结果。 4. 定义损失函数和优化器:根据回归任务的特点,选择适当的损失函数和优化器。常见的损失函数有均方误差(MSE)和平均绝对误差(MAE)等。 5. 训练模型:使用训练数据对模型进行训练,通过反向传播算法更新模型的参数。可以根据具体情况选择合适的训练策略,如学习率调整、正则化等。 6. 评估模型:使用测试数据对训练好的模型进行评估,计算回归任务的指标,如均方根误差(RMSE)、平均绝对误差(MAE)等。 7. 进行预测:使用训练好的模型对新的样本进行预测,得到回归结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值