使用加利福尼亚房价数据集(California housing dataset)来实现线性回归,并展示训练和测试损失随训练周期的变化

import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import time

# 加载加利福尼亚房价数据集
housing = fetch_california_housing()
data, target = housing.data, housing.target

# 数据标准化处理
scaler = StandardScaler()
data = scaler.fit_transform(data)

# 将数据转换为 PyTorch 张量
data = torch.tensor(data, dtype=torch.float32)
target = torch.tensor(target, dtype=torch.float32).view(-1, 1)

# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=42)

# 定义线性回归模型
class LinearRegressionModel(nn.Module):
    def __init__(self):
        super(LinearRegressionModel, self).__init__()
        self.linear = nn.Linear(data.shape[1], 1)  # 输入特征数为数据集的特征数

    def forward(self, x):
        return self.linear(x)

def train_model(device, x_train, y_train, x_test, y_test, batch_size, learning_rate):
    # 将数据移动到指定设备
    x_train = x_train.to(device)
    y_train = y_train.to(device)
    x_test = x_test.to(device)
    y_test = y_test.to(device)
    
    model = LinearRegressionModel().to(device)
    criterion = nn.MSELoss()
    optimizer = optim.SGD(model.parameters(), lr=learning_rate)
    
    num_epochs = 100
    train_losses = []
    test_losses = []

    start_time = time.time()

    for epoch in range(num_epochs):
        model.train()
        
        # 迭代所有数据集的批次
        for i in range(0, len(x_train), batch_size):
            x_batch = x_train[i:i+batch_size]
            y_batch = y_train[i:i+batch_size]

            predictions = model(x_batch)
            loss = criterion(predictions, y_batch)
            train_losses.append(loss.item())
            
            optimizer.zero_grad()
            loss.backward()
            
            # 梯度裁剪
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
            
            optimizer.step()
        
        # 测试集上的损失
        model.eval()
        with torch.no_grad():
            test_predictions = model(x_test)
            test_loss = criterion(test_predictions, y_test)
            test_losses.append(test_loss.item())
        
        if (epoch + 1) % 10 == 0:
            print(f'Device: {device}, Epoch [{epoch+1}/{num_epochs}], Train Loss: {loss.item():.4f}, Test Loss: {test_loss.item():.4f}')

    end_time = time.time()
    training_time = end_time - start_time
    
    return model, train_losses, test_losses, training_time

# 设置批处理大小和学习率
batch_size = 32
learning_rate = 0.001  # 降低学习率

# 在CPU上训练
cpu_device = torch.device("cpu")
cpu_model, cpu_train_losses, cpu_test_losses, cpu_time = train_model(cpu_device, x_train, y_train, x_test, y_test, batch_size, learning_rate)

# 绘制训练损失随训练周期的变化图
plt.figure(figsize=(10, 5))
plt.plot(range(len(cpu_train_losses)), cpu_train_losses, label='CPU Training Loss')
plt.title('Training Loss over Iterations')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.show()

# 绘制测试损失随训练周期的变化图
plt.figure(figsize=(10, 5))
plt.plot(range(len(cpu_test_losses)), cpu_test_losses, label='CPU Test Loss')
plt.title('Test Loss over Epochs')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.grid(True)
plt.show()

# 打印训练时间
print(f"CPU training time: {cpu_time:.2f} seconds")

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
很好,这是一个不错的练习。下面是一个简单的PyTorch实现AlexNet的代码,以及使用mnist数据集进行训练测试的代码: ```python import torch import torch.nn as nn class AlexNet(nn.Module): def __init__(self, num_classes=10): super(AlexNet, self).__init__() self.features = nn.Sequential( nn.Conv2d(1, 64, kernel_size=11, stride=4, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(64, 192, kernel_size=5, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(192, 384, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(384, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), ) self.avgpool = nn.AdaptiveAvgPool2d((6, 6)) self.classifier = nn.Sequential( nn.Dropout(), nn.Linear(256 * 6 * 6, 4096), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(inplace=True), nn.Linear(4096, num_classes), ) def forward(self, x): x = self.features(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.classifier(x) return x # define the device for the model device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # define the model model = AlexNet(num_classes=10).to(device) # define the loss function and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9) # load the mnist dataset train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = torchvision.datasets.MNIST(root='./data', train=False, transform=transforms.ToTensor(), download=True) # create data loaders train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=True) # train the model for epoch in range(10): for i, (images, labels) in enumerate(train_loader): # move the images and labels to the device images = images.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward pass outputs = model(images) loss = criterion(outputs, labels) # backward pass and optimize loss.backward() optimizer.step() # print statistics if (i+1) % 100 == 0: print(f'Epoch [{epoch+1}/{10}], Step [{i+1}/{len(train_loader)}], Loss: {loss.item():.4f}') # evaluate the model model.eval() correct = 0 total = 0 with torch.no_grad(): for images, labels in test_loader: # move the images and labels to the device images = images.to(device) labels = labels.to(device) # forward pass outputs = model(images) _, predicted = torch.max(outputs.data, 1) # calculate accuracy total += labels.size(0) correct += (predicted == labels).sum().item() print(f'Accuracy: {100 * correct / total}%') ``` 在这个示例中,我们使用了PyTorch实现了AlexNet模型,并使用mnist数据集进行训练测试。我们首先定义了AlexNet模型,然后定义了训练所需的损失函数和优化器。接下来,我们使用torchvision加载mnist数据集,并创建了数据加载器。在训练循环中,我们将每个批次的图像和标签移动到设备上,并执行正向传递、反向传递和优化步骤。在测试循环中,我们将模型设置为评估模式,并计算测试集上的精度。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值