PyTorch 是一个流行的开源机器学习库,广泛用于深度学习领域。以下是如何在您的系统上安装 PyTorch 的步骤。

系统要求

在安装 PyTorch 之前,请确保您的系统满足以下要求:

  • 操作系统:Linux、macOS 或 Windows
  • Python 版本:Python 3.6 - 3.9

安装步骤

  1. 选择合适的 PyTorch 版本
    根据您的系统配置和需求,选择合适的 PyTorch 版本。您可以在 PyTorch 官网找到详细的版本信息。

  2. 安装 PyTorch
    使用以下命令进行安装:

    pip install torch torchvision torchaudio
    

    或者,如果您需要 GPU 加速,可以使用:

    pip install torch torchvision torchaudio -f https://download.pytorch.org/whl/torch_stable.html
    
  3. 验证安装
    安装完成后,可以通过运行以下 Python 代码来验证 PyTorch 是否安装成功:

    import torch
    print(torch.__version__)
    

    如果输出 PyTorch 的版本号,则表示安装成功。

图片示例

以下是一个简单的 PyTorch 模型示例:

import torch
import torch.nn as nn
import torch.optim as optim

# 创建一个简单的神经网络
class SimpleNet(nn.Module):
    def __init__(self):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(10, 5)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(5, 1)

    def forward(self, x):
        x = self.fc1(x)
        x = self.relu(x)
        x = self.fc2(x)
        return x

# 实例化模型、损失函数和优化器
model = SimpleNet()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

# 输入数据
x = torch.randn(1, 10)
y = torch.randn(1, 1)

# 训练模型
optimizer.zero_grad()
output = model(x)
loss = criterion(output, y)
loss.backward()
optimizer.step()

# 打印输出
print("Output:", output)
print("Loss:", loss.item())

更多 PyTorch 示例