Pytorch从入门到精通(一):线性模型

本文通过一个简单的学习时长与成绩的关系预测问题,介绍了如何使用Python的numpy包及PyTorch框架实现线性回归模型,并采用梯度下降法进行参数优化。

我们先来看一个问题,然后看人工智能如何计算出最后的答案。

问题很简单:一个人学习时长(单位:小时)和他成绩的对应关系如下,求出他在学习四小时后的成绩。

其实这个问题一个5岁小孩都能一眼看出来,但是如何让人工智能计算出来呢。

我们借助Python的numpy包,然后用梯度下降法计算出结果:

import numpy as np
x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

w = 1.0  # a random guess: random value

# our model forward pass


def forward(x):
    return x * w


# Loss function
def loss(x, y):
    y_pred = forward(x)
    return (y_pred - y) * (y_pred - y)


# compute gradient
def gradient(x, y):  # d_loss/d_w
    return 2 * x * (x * w - y)

# Before training
print("predict (before training)",  4, forward(4))

# Training loop
for epoch in range(10):
    for x_val, y_val in zip(x_data, y_data):
        grad = gradient(x_val, y_val)
        w = w - 0.01 * grad
        print("\tgrad: ", x_val, y_val, round(grad, 2))
        l = loss(x_val, y_val)

    print("progress:", epoch, "w=", round(w, 2), "loss=", round(l, 2))

# After training
print("predict (after training)",  "4 hours", forward(4))

再使用pytorch,来实现一样的功能:

import torch
from torch.autograd import Variable

x_data = Variable(torch.Tensor([[1.0], [2.0], [3.0]]))
y_data = Variable(torch.Tensor([[2.0], [4.0], [6.0]]))


class Model(torch.nn.Module):

    def __init__(self):
        """
        In the constructor we instantiate two nn.Linear module
        """
        super(Model, self).__init__()
        self.linear = torch.nn.Linear(1, 1)  # One in and one out

    def forward(self, x):
        """
        In the forward function we accept a Variable of input data and we must return
        a Variable of output data. We can use Modules defined in the constructor as
        well as arbitrary operators on Variables.
        """
        y_pred = self.linear(x)
        return y_pred

# our model
model = Model()


# Construct our loss function and an Optimizer. The call to model.parameters()
# in the SGD constructor will contain the learnable parameters of the two
# nn.Linear modules which are members of the model.
criterion = torch.nn.MSELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

# Training loop
for epoch in range(500):
        # Forward pass: Compute predicted y by passing x to the model
    y_pred = model(x_data)

    # Compute and print loss
    loss = criterion(y_pred, y_data)
    print(epoch, loss.data[0])

    # Zero gradients, perform a backward pass, and update the weights.
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()


# After training
hour_var = Variable(torch.Tensor([[4.0]]))
y_pred = model(hour_var)
print("predict (after training)",  4, model(hour_var).data[0][0])
### PyTorch 入门精通教程 #### 了解 PyTorch 及其优势 PyTorch 是当前最流行的深度学习框架之,因其易用性、灵活性和动态计算图的特性而受到广泛欢迎。无论是在学术研究还是工业应用中,PyTorch 均展现出卓越的表现[^3]。 #### 安装 PyTorch 为了开始使用 PyTorch,需先完成环境配置工作。对于拥有 NVIDIA 显卡特别是 30 系列显卡的用户来说,在安装过程中可能会遇到些特定问题;可以参考相关博客获取详细的安装指南[^4]。通常情况下,可以通过 pip 或 conda 来轻松安装最新版本的 PyTorch: ```bash pip install torch torchvision torchaudio ``` 或者使用 Anaconda 进行安装: ```bash conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch ``` #### 使用 Jupyter Notebook 编写代码 Jupyter Notebook 提供了个交互式的编程环境,非常适合用于探索性和实验性的开发过程。在该环境中编写 Python 代码能够更方便地测试不同的想法并即时查看结果。创建个新的 Jupyter Notebook 文件来启动第PyTorch 实验是个不错的选择。 #### 掌握基本概念与操作 熟悉张量(Tensor)、自动求导机制以及神经网络模块是构建任何复杂模型的基础。以下是几个简单的例子展示这些核心组件的工作方式: ##### 创建张量 ```python import torch # 创建个随机初始化的二维张量 x = torch.rand(5, 3) print(x) # 创建全零或全矩阵 zeros = torch.zeros((2, 2)) ones = torch.ones((2, 2)) # 查看形状属性 print(zeros.shape) ``` ##### 自动求导功能 ```python # 启用梯度跟踪模式 y = x.requires_grad_(True).sum() y.backward() # 计算反向传播后的梯度 print(x.grad) # 输出每个元素对应的偏导数 ``` ##### 构建简单线性回归模型 ```python from torch import nn class LinearRegressionModel(nn.Module): def __init__(self): super().__init__() self.linear_layer = nn.Linear(in_features=784, out_features=1) model_0 = LinearRegressionModel() loss_fn = nn.L1Loss() # L1损失函数 optimizer = torch.optim.SGD(params=model_0.parameters(), lr=0.01) # 随机梯度下降优化器 ``` 随着对上述基础知识的理解加深,后续还可以进步探讨更多高级主题如卷积神经网络(CNNs),循环神经网络(RNNs),迁移学习等,并尝试解决更加复杂的实际问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值