Python AI 入门:从线性回归到图像分类
一、Python AI 的 Hello World
1.1 环境搭建
首先,我们需要搭建 Python AI 的开发环境:
# 安装 PyTorch
pip install torch torchvision
# 安装其他依赖
pip install numpy matplotlib
1.2 第一个 AI 程序
让我们来编写一个最简单的 AI 程序 - 线性回归:
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# 生成训练数据
x = torch.linspace(0, 10, 100).unsqueeze(1)
y = 2 * x + 1 + torch.randn(100, 1) * 0.5
# 定义模型
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 = torch.optim.SGD(model.parameters(), lr=0.01)
# 训练模型
epochs = 100
epoch (epochs):
outputs = model(x)
loss = criterion(outputs, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
(epoch + ) % == :
()
torch.no_grad():
predicted = model(x)
plt.scatter(x.numpy(), y.numpy(), label=)
plt.plot(x.numpy(), predicted.numpy(), , label=)
plt.legend()
plt.show()
()

