Python安装Pytorch最新图文教程
Pytorch 是一个由 Facebook 开源的深度学习框架,具有易于使用、动态计算图等特点。本文将详细讲解如何在 Python 上安装 Pytorch 最新版本。
步骤一:安装 Anaconda
首先需要在官网 https://www.anaconda.com/download/ 上下载对应系统的安装包,然后进行安装,安装过程中可以选择是否将 Anaconda 加入到系统 path,建议勾选此选项。
步骤二:创建虚拟环境
在命令行中运行以下命令来创建一个名为 pytorch
的虚拟环境:
conda create --name pytorch python=3
创建完成后,激活虚拟环境:
conda activate pytorch
步骤三:安装 Pytorch
在命令行中运行以下命令来安装最新版本的 Pytorch:
conda install pytorch torchvision torchaudio -c pytorch
如果需要安装特定版本的 Pytorch,可以在命令最后加上指定版本号,例如:
conda install pytorch==1.9.0 torchvision torchaudio -c pytorch
示例一:使用 Pytorch 进行 MNIST 手写数字识别
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
# 定义 transform
transform = transforms.Compose([
transforms.ToTensor(),
])
# 加载数据集
trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
testset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True)
testloader = torch.utils.data.DataLoader(testset, batch_size=32, shuffle=False)
# 定义模型
class MNISTNet(nn.Module):
def __init__(self):
super(MNISTNet, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2)
self.pool1 = nn.MaxPool2d(kernel_size=2)
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=2)
self.pool2 = nn.MaxPool2d(kernel_size=2)
self.fc1 = nn.Linear(in_features=32*7*7, out_features=128)
self.fc2 = nn.Linear(in_features=128, out_features=10)
def forward(self, x):
x = self.conv1(x)
x = torch.relu(x)
x = self.pool1(x)
x = self.conv2(x)
x = torch.relu(x)
x = self.pool2(x)
x = x.view(-1, 32*7*7)
x = self.fc1(x)
x = torch.relu(x)
x = self.fc2(x)
return x
net = MNISTNet()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=1e-3)
# 开始训练
for epoch in range(5):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' % (epoch+1, i+1, running_loss/100))
running_loss = 0.0
示例二:使用 Pytorch 进行图像风格转换
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
# 加载预训练的 VGG19 模型
vgg = models.vgg19(pretrained=True).features
# 选择需要用到的卷积层
conv_layers = [4, 9, 18, 27, 36]
# 定义 transform
transform = transforms.Compose([
transforms.Resize(512),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# 加载内容图像和风格图像
content_image = Image.open('content.jpg').convert('RGB')
style_image = Image.open('style.jpg').convert('RGB')
# 对图像进行 transform 并转换为 Pytorch Tensor
content_tensor = transform(content_image).unsqueeze(0)
style_tensor = transform(style_image).unsqueeze(0)
# 将 content_tensor 和 style_tensor 送入 VGG19,提取对应的 feature
def get_features(tensor, model, layers):
features = {}
for name, layer in model._modules.items():
tensor = layer(tensor)
if int(name) in layers:
features[name] = tensor
return features
content_features = get_features(content_tensor, vgg, conv_layers)
style_features = get_features(style_tensor, vgg, conv_layers)
# 定义 Gram 矩阵
def gram_matrix(tensor):
_, C, H, W = tensor.size()
tensor = tensor.view(C, H*W)
gram = torch.matmul(tensor, tensor.t())
return gram
# 计算 content image 和 style image 的 Gram 矩阵
style_grams = {layer: gram_matrix(style_features[layer]) for layer in style_features}
content_grams = {layer: gram_matrix(content_features[layer]) for layer in content_features}
# 定义合成图像
target = content_tensor.clone().requires_grad_(True)
# 定义损失函数和优化器
content_weight = 1
style_weight = 100000
target_features = get_features(target, vgg, conv_layers)
optimizer = optim.Adam([target], lr=0.01)
# 开始训练
for i in range(1000):
target_features = get_features(target, vgg, conv_layers)
content_loss = 0.
for layer in content_features:
content_loss += torch.mean(torch.pow(target_features[layer] - content_features[layer], 2))
style_loss = 0.
for layer in style_features:
style_loss += torch.mean(torch.pow(gram_matrix(target_features[layer]) - style_grams[layer], 2))
total_loss = content_weight * content_loss + style_weight * style_loss
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
if i % 100 == 0:
print('iteration:', i, 'total loss:', total_loss.item())
# 保存合成图像
result_tensor = target.detach().squeeze().clamp_(0, 1)
result_image = transforms.ToPILImage()(result_tensor)
result_image.save('result.jpg')
至此,你已经成功安装了最新版本的 Pytorch,并了解了两个示例的使用。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python安装Pytorch最新图文教程 - Python技术站