PyTorch 是一个流行的开源机器学习库,用于应用深度学习。以下是如何在您的系统上安装 PyTorch 的步骤。
系统要求
安装步骤
- 打开终端。
- 使用以下命令安装 PyTorch:
pip install torch torchvision torchaudio
如果您需要 GPU 支持,请使用:
pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
- 安装完成后,您可以使用以下命令验证安装:
import torch
print(torch.__version__)
示例
安装完成后,您可以尝试以下示例代码:
import torch
# 创建一个简单的神经网络
x = torch.randn(5, 3) # 随机生成一个 5x3 的张量
y = torch.randn(5, 1) # 随机生成一个 5x1 的张量
# 定义一个线性层
linear = torch.nn.Linear(3, 1)
# 前向传播
output = linear(x)
# 计算损失
loss = torch.mean((output - y) ** 2)
# 打印损失
print(loss.item())
更多信息,请访问我们的 PyTorch 教程页面。