在 Mac 上训练机器学习模型可以通过多种工具和框架实现,以下是详细的步骤指南和工具推荐:
安装 Python
安装机器学习框架
bash
pip install tensorflow-macos
pip install tensorflow-metal # GPU 加速插件
bash
pip install torch torchvision torchaudio
bash
pip install scikit-learn
验证 GPU 加速
python
import tensorflow as tf
print(tf.config.list_physical_devices('GPU')) # 检查 GPU 是否可用
python
import torch
print(torch.backends.mps.is_available()) # 检查 MPS(Metal Performance Shaders)是否可用
bash
docker run -it tensorflow/tensorflow:latest
--platform linux/amd64
运行 x86 镜像。bash
pip install jupyterlab
jupyter lab
import torch
import torch.nn as nn
# 检查设备(M1/M2 GPU 或 CPU)
device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
# 定义简单模型
model = nn.Sequential(
nn.Linear(10, 50),
nn.ReLU(),
nn.Linear(50, 2)
model.to(device)
# 训练循环
inputs = torch.randn(100, 10).to(device)
labels = torch.randint(0, 2, (100,)).to(device)
optimizer = torch.optim.Adam(model.parameters())
for epoch in range(10):
outputs = model(inputs)
loss = nn.CrossEntropyLoss()(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(f"Epoch {epoch}, Loss: {loss.item()}")
tensorflow-metal
。device="mps"
。python
scaler = torch.cuda.amp.GradScaler() # 即使没有 CUDA,MPS 也支持
torch.utils.data.DataLoader
的 num_workers
加速数据加载。tensorflow-macos
和 tensorflow-metal
版本匹配。如果需要更复杂的模型训练,推荐结合云平台(如 Colab 或 AWS)扩展资源。