在Linux系统下利用PyTorch进行深度学习,可以按照以下步骤进行:
sudo apt update
sudo apt upgrade -y
sudo apt install -y python3 python3-pip
python3 -m venv pytorch_env
source pytorch_env/bin/activate
pip3 install torch torchvision torchaudio
pip3 install torch torchvision torchaudio -f https://download.pytorch.org/whl/cu118/torch_stable.html
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
source ~/.bashrc
conda create -n pytorch_env python=3.8
conda activate pytorch_env
conda install pytorch torchvision torchaudio cpuonly -c pytorch
conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia
在Python环境中输入以下代码,检查PyTorch是否正确安装:
import torch
print(torch.__version__)
print(torch.cuda.is_available()) # 检查是否检测到GPU
如果torch.cuda.is_available()
返回True
,则说明CUDA和cuDNN安装成功,PyTorch可以正常使用GPU进行深度学习任务。
import torch
import torch.nn as nn
import torch.optim as optim
class LinearModel(nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x):
return self.linear(x)
model = LinearModel()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
inputs = torch.tensor([[1.0], [2.0], [3.0]])
targets = torch.tensor([[2.0], [4.0], [6.0]])
for epoch in range(100):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print(f'Epoch {epoch+1}, Loss: {loss.item()}')
通过以上步骤,你应该能够在Linux系统下成功安装并运行PyTorch,并开始进行深度学习任务。如果在安装过程中遇到问题,可以参考PyTorch官方文档获取更多信息。