M1 Mac是苹果公司推出的基于ARM架构的芯片,与传统的x86架构有所不同。因此,在M1 Mac上安装PyTorch需要一些特殊的步骤。本文将介绍M1 Mac上安装PyTorch的实现步骤,并提供两个示例说明。
步骤一:安装Miniforge
Miniforge是一个轻量级的Anaconda发行版,专门为ARM架构的Mac电脑设计。我们可以使用Miniforge来安装Python和PyTorch。以下是安装Miniforge的步骤:
- 访问Miniforge的官方网站:https://github.com/conda-forge/miniforge/releases/latest
- 下载适用于M1 Mac的Miniforge安装包(例如
Miniforge3-MacOSX-arm64.sh
) - 打开终端,并在终端中导航到Miniforge安装包所在的目录
- 运行以下命令来安装Miniforge:
bash Miniforge3-MacOSX-arm64.sh
- 按照提示进行安装,包括选择安装路径和添加Miniforge到环境变量中
步骤二:创建虚拟环境并安装PyTorch
在安装Miniforge后,我们需要创建一个虚拟环境,并在其中安装PyTorch。以下是创建虚拟环境并安装PyTorch的步骤:
- 打开终端,并运行以下命令来创建一个名为
pytorch
的虚拟环境:
conda create --name pytorch python=3.8
- 激活虚拟环境:
conda activate pytorch
- 安装PyTorch:
conda install pytorch torchvision torchaudio -c pytorch -c conda-forge
- 验证PyTorch是否安装成功:
python -c "import torch; print(torch.__version__)"
如果输出了PyTorch的版本号,则说明安装成功。
示例一:使用PyTorch进行图像分类
以下是一个使用PyTorch进行图像分类的示例,我们将使用在M1 Mac上安装的PyTorch:
import torch
import torchvision
import torchvision.transforms as transforms
# 加载数据集
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
shuffle=True, num_workers=2)
# 定义模型
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
# 定义损失函数和优化器
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练模型
for epoch in range(2):
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 % 2000 == 1999:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
在上述代码中,我们使用PyTorch训练了一个简单的卷积神经网络,用于对CIFAR-10数据集中的图像进行分类。
示例二:使用PyTorch进行文本分类
以下是一个使用PyTorch进行文本分类的示例,我们将使用在M1 Mac上安装的PyTorch:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchtext.datasets import AG_NEWS
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
# 加载数据集
train_iter = AG_NEWS(split='train')
tokenizer = get_tokenizer('basic_english')
vocab = build_vocab_from_iterator(map(tokenizer, train_iter), specials=["<unk>"])
train_iter = AG_NEWS(split='train', vocab=vocab, tokenizer=tokenizer)
# 定义模型
class TextSentiment(nn.Module):
def __init__(self, vocab_size, embed_dim, num_class):
super().__init__()
self.embedding = nn.EmbeddingBag(vocab_size, embed_dim, sparse=True)
self.fc = nn.Linear(embed_dim, num_class)
self.init_weights()
def init_weights(self):
initrange = 0.5
self.embedding.weight.data.uniform_(-initrange, initrange)
self.fc.weight.data.uniform_(-initrange, initrange)
self.fc.bias.data.zero_()
def forward(self, text, offsets):
embedded = self.embedding(text, offsets)
return self.fc(embedded)
# 训练模型
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
num_class = len(train_iter.get_labels())
vocab_size = len(train_iter.get_vocab())
emsize = 64
model = TextSentiment(vocab_size, emsize, num_class).to(device)
criterion = torch.nn.CrossEntropyLoss().to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=4.0)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1, gamma=0.9)
def train(train_iter):
model.train()
total_loss = 0.
total_acc = 0.
for idx, (text, offsets) in enumerate(train_iter):
optimizer.zero_grad()
text, offsets = text.to(device), offsets.to(device)
output = model(text, offsets)
loss = criterion(output, train_iter.get_labels()[idx])
total_loss += loss.item()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
optimizer.step()
total_acc += (output.argmax(1) == train_iter.get_labels()[idx]).sum().item()
return total_loss / len(train_iter), total_acc / len(train_iter)
for epoch in range(5):
train_loss, train_acc = train(train_iter)
print(f'Epoch: {epoch+1:02}')
print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%')
scheduler.step()
print('Finished Training')
在上述代码中,我们使用PyTorch训练了一个简单的文本分类模型,用于对AG_NEWS数据集中的新闻进行分类。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:M1 mac安装PyTorch的实现步骤 - Python技术站