基于PyTorch的鲍鱼年龄线性回归

本例使用了一个Abalone(https://archive.ics.uci.edu/dataset/1/abalone)数据集(已经下载好的数据集->📎abalone.zip),其中abalone.data是数据,abalone.names是本案例数据的英文解释。以下是数据集的中文解释:

复制代码
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import torch
import torch.nn as nn
import torch.optim as optim

data = pd.read_csv(r'C:\Users\86198\Downloads\abalone (1)\abalone.data', sep=',')
# print(data.head())
column_names = ['Sex', 'Length', 'Diameter', 'Height', 'Whole_weight',
                'Shucked_weight', 'Viscera_weight', 'Shell_weight', 'Rings']
data.columns = column_names
data = pd.get_dummies(data, columns=['Sex'])
print(data.keys())

X = data[['Sex_F', 'Sex_M', 'Sex_I', 'Length', 'Diameter',
          'Height', 'Whole_weight', 'Shucked_weight', 'Viscera_weight', 'Shell_weight']]
# 选取 'Rings' 列作为目标变量,即模型要预测的对象,通常代表了鲍鱼的年龄相关信息 y = data['Rings']
y = data['Rings']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

X_train_tensor = torch.tensor(X_train_scaled, dtype=torch.float32)
X_test_tensor = torch.tensor(X_test_scaled, dtype=torch.float32)
y_train_tensor = torch.tensor(y_train.values, dtype=torch.float32).view(-1, 1)
y_test_tensor = torch.tensor(y_test.values, dtype=torch.float32).view(-1, 1)


class LinearRegressionModel(nn.Module):
    def __init__(self, input_size):
        super(LinearRegressionModel, self).__init__()
        self.linear = nn.Linear(input_size, 1)

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


input_size = X_train_tensor.shape[1]
model = LinearRegressionModel(input_size)

criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.1)

num_epochs = 1000
for epoch in range(num_epochs):
    model.train()
    optimizer.zero_grad()

    outputs = model(X_train_tensor)
    loss = criterion(outputs, y_train_tensor)
    loss.backward()
    optimizer.step()

model.eval()
with torch.no_grad():
    predictions = model(X_test_tensor)
    test_loss = criterion(predictions, y_test_tensor)


predictions = predictions.detach().cpu().numpy()
y_test_numpy = y_test_tensor.detach().cpu().numpy()

plt.figure(0)
plt.scatter(y_test_numpy, predictions, c='blue')

plt.plot([min(y_test_numpy), max(y_test_numpy)], [min(y_test_numpy), max(y_test_numpy)],
         linestyle='--', color='red', linewidth=2)
plt.xlabel('Actual Values')
plt.ylabel('Predicted Values')
plt.title('Regression Results')

plt.figure(1)
sorted_indices = X_test.index.argsort()
# 根据排序后的索引获取对应的实际值
y_test_sorted = y_test.iloc[sorted_indices]

# 将预测值转换为Series类型,并且根据排序后的索引获取对应的值
y_pred_sorted = pd.Series(predictions.squeeze()).iloc[sorted_indices]

# 绘制实际值的曲线,用圆形标记
plt.plot(y_test_sorted.values, label='Acatual Values', marker='o')
# 绘制预测值的曲线,用*标记
plt.plot(y_pred_sorted.values, label='Predicted Values', marker='*')

# 设置轴标签和标题
plt.xlabel('Sorted Index')
plt.ylabel('Values')
plt.title('Actual vs Predicted Values in Linear Regression')
plt.show()

代码视频讲解:https://www.bilibili.com/video/BV1nPvCBVEZC/

相关推荐
苍何fly8 分钟前
首个国产芯片训练的多模态 SOTA 模型,已免费开源!
人工智能·经验分享
2401_841495649 分钟前
具身智能:从理论到现实,人工智能的下一场革命
人工智能·算法·机器人·硬件·具身智能·通用智能·专用智能
方见华Richard22 分钟前
对话量子场论:语言如何产生认知粒子V0.3
人工智能·交互·学习方法·原型模式·空间计算
wfeqhfxz258878226 分钟前
基于YOLO12-A2C2f-DFFN-DYT-Mona的铁件部件状态识别与分类系统_1
人工智能·分类·数据挖掘
2501_9415079426 分钟前
脊柱结构异常检测与分类:基于Cascade-RCNN和HRNetV2p-W32模型的改进方案
人工智能·分类·数据挖掘
珊珊而川27 分钟前
MBE(Model-based Evaluation) LLM-as-a-Judge
人工智能
想用offer打牌34 分钟前
Spring AI vs Spring AI Alibaba
java·人工智能·后端·spring·系统架构
qwerasda12385237 分钟前
车辆超载检测系统:基于YOLO11-C3k2-RFCAConv的高精度识别模型实现与性能评估_1
人工智能
Coco恺撒38 分钟前
【脑机接口】难在哪里,【人工智能】如何破局(1.用户篇)
人工智能·深度学习·开源·生活·人机交互·智能家居
sunlifenger39 分钟前
上海兆越人员定位系统,多元技术赋能,精准守护工业安全
网络·人工智能·安全