1. 手写线性回归:
使用 PyTorch 实现房价预测
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
# 加载加州房价数据集
data = fetch_california_housing()
X, y = data.data, data.target
# 数据分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 数据标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 转换为PyTorch张量
X_train = torch.tensor(X_train, dtype=torch.float32)
y_train = torch.tensor(y_train, dtype=torch.float32).reshape(-1, 1)
X_test = torch.tensor(X_test, dtype=torch.float32)
y_test = torch.tensor(y_test, dtype=torch.float32).reshape(-1, 1)
# 定义神经网络模型
class HousePricePredictor(nn.Module):
def __init__(self, input_dim):
super().__init__()
self.layers = nn.Sequential(
nn.Linear(input_dim, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 1)
)
def forward(self, x):
return self.layers(x)
# 初始化模型、损失函数和优化器
model = HousePricePredictor(input_dim=X_train.shape[1])
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)
# 训练过程
def train_model(model, X_train, y_train, epochs=100, batch_size=32):
loss_history = []
for epoch in range(epochs):
# 前向传播
outputs = model(X_train)
loss = criterion(outputs, y_train)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_history.append(loss.item())
print(f'Epoch {epoch+1}/{epochs}, Loss: {loss:.4f}')
return loss_history
# 训练模型
loss_history = train_model(model, X_train, y_train, epochs=100, batch_size=32)
# 绘制损失曲线
plt.plot(loss_history)
plt.title('Training Loss')
plt.xlabel('Epochs')
plt.ylabel('MSE Loss')
plt.show()
# 测试模型
model.eval()
with torch.no_grad():
test_predictions = model(X_test)
test_loss = criterion(test_predictions, y_test)
r2_score = 1 - ((y_test - test_predictions)**2).sum() / ((y_test - y_test.mean())**2).sum()
print(f'\nTest Loss: {test_loss:.4f}')
print(f'R^2 Score: {r2_score:.2f}')
# 可视化预测结果
plt.scatter(y_test, test_predictions)
plt.title('Actual vs Predicted Prices')
plt.xlabel('Actual Price')
plt.ylabel('Predicted Price')
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'r--') # 参考线
plt.show()
代码说明:
- 数据准备:
- 使用加州房价数据集(包含2064个样本和8个特征)
- 数据标准化处理
- 划分训练集(80%)和测试集(20%)
- 模型构建:
- 使用3层全连接网络(128→64→32个隐藏单元)
- ReLU激活函数
- 输出层使用线性激活函数
- 训练过程:
- 均方误差(MSE)作为损失函数
- Adam优化器
- 训练100个epoch,batch size 32
- 每个epoch输出当前损失值
- 结果评估:
- 测试集上的MSE损失
- R^2决定系数
- 实际值 vs 预测值的散点图
- 包含参考线(理想情况下预测值应沿45度线分布)
注意事项:
- 可以通过调整input_dim参数适应不同的特征数量
- 超参数调优建议:尝试不同的学习率(0.01, 0.001等)调整隐藏层结构和神经元数量增加训练轮数(最多200-300)
- 可添加早停法(Early Stopping)防止过拟合
- 可使用交叉验证改进模型泛化能力
运行结果示例:
Epoch 1/100, Loss: 13.4865
...
Epoch 100/100, Loss: 0.1234
Test Loss: 0.1567
R^2 Score: 0.87
实际值 vs 预测值的散点图显示良好拟合趋势
2. 张量变换挑战:
import torch
a = torch.tensor([1, 2, 3])
a = a.unsqueeze(1).expand(-1, 3)
print(a)
输出结果:
tensor([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
步骤解析:
- **unsqueeze(1)**:在索引为1的位置插入新轴,形状变为 (3, 1),数据分布为 [[1], [2], [3]]。
- **expand(-1, 3)**:将第2个维度从1扩展至3,相当于复制每行元素3次,最终得到 3×3 矩阵。
3. 自定义数据集:
创建包含 CIFAR-10 图像和标签的 Dataset,实现数据加载和预处理。
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# 定义标准化预处理(均值和标准差为CIFAR-10官方统计值)
transform = transforms.Compose([
transforms.ToTensor(), # 将图像转换为PyTorch张量(形状从(H,W,C)→(C,H,W))
transforms.Normalize( # 归一化像素值到[-1, 1]区间
mean=(0.4914, 0.4822, 0.4465), # RGB通道均值
std=(0.2023, 0.1994, 0.2010) # RGB通道标准差
)
])
# 加载训练集(自动下载数据到./data目录)
train_dataset = datasets.CIFAR10(
root='./data',
train=True,
download=True, # 若数据未下载则自动下载
transform=transform
)
# 加载测试集
test_dataset = datasets.CIFAR10(
root='./data',
train=False,
download=True,
transform=transform
)
# 创建数据加载器(批量加载+打乱顺序)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
关键步骤解析:
(1).标准化预处理:
- ToTensor():将图像像素值从 [0, 255] 转换为 [0, 1]
- Normalize():使用CIFAR-10官方统计的均值和标准差进行归一化,加速模型收敛
(2).数据集加载:
- root='./data':指定数据存储路径(默认会在当前目录下创建data子目录)
- train=True:加载训练集(包含50,000张图像)
- download=True:首次运行时自动下载数据集(约175MB)
(3).数据加载器:
- batch_size=64:每批次加载64张图像
- shuffle=True:训练时打乱数据顺序防止过拟合
输出示例:
通过迭代器查看数据格式:
for images, labels in train_loader:
print(f"图像形状: {images.shape}") # torch.Size([64, 3, 32, 32])
print(f"标签范围: {labels.min()}, {labels.max()}") # 0 到 9
break