基于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/

相关推荐
八月瓜科技6 分钟前
擎策·知海全球专利数据库 专业专利检索赋能 规避无效研发提效创新
大数据·数据库·人工智能·科技·aigc
百胜软件@百胜软件12 分钟前
社区生鲜零售革命:8万亿赛道的效率突围与生态重构
人工智能·重构·零售
jinanwuhuaguo16 分钟前
OpenClaw v2026.3.22-beta.1 深度技术分析报告:从单智能体操作系统到多智能体协作平台的范式跃迁
运维·人工智能·语言模型·自然语言处理·visual studio code·openclaw
天辛大师17 分钟前
天辛大师也谈大模型GEO技术,虚构与误导的重读
大数据·人工智能·决策树·随机森林·启发式算法
金融小师妹20 分钟前
基于多因子流动性模型的“黄金闪崩”解析:利率预期强化与资金再平衡驱动的金价8%下跌机制
大数据·人工智能·svn·能源
weixin_3077791321 分钟前
2025年中国研究生数学建模竞赛A题:通用神经网络处理器下的核内调度问题——解决方案与实现
开发语言·人工智能·python·数学建模·性能优化
新缸中之脑21 分钟前
Okara AI CMO:市场营销智能体
人工智能
Tony沈哲23 分钟前
AI 正在进入本地时代,我开源了一个推理平台—— 支持多模型 / Agent / Workflow 的工程实现
人工智能·算法·llm
黎阳之光23 分钟前
AI赋能安全新生态 黎阳之光锚定国家政策筑造数智防线
大数据·人工智能·算法·安全·数字孪生
WHD30624 分钟前
企业数据安全体系建设指南:从风险识别到技术落地的全流程(2026版)
大数据·网络·人工智能·安全·系统架构·密码学·安全架构