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

相关推荐
callJJ9 小时前
Spring AI 文本聊天模型完全指南:ChatModel 与 ChatClient
java·大数据·人工智能·spring·spring ai·聊天模型
是店小二呀9 小时前
CANN 异构计算的极限扩展:从算子融合到多卡通信的统一优化策略
人工智能·深度学习·transformer
冻感糕人~9 小时前
收藏备用|小白&程序员必看!AI Agent入门详解(附工业落地实操关联)
大数据·人工智能·架构·大模型·agent·ai大模型·大模型学习
予枫的编程笔记9 小时前
【Linux入门篇】Ubuntu和CentOS包管理不一样?apt与yum对比实操,看完再也不混淆
linux·人工智能·ubuntu·centos·linux包管理·linux新手教程·rpm离线安装
陈西子在网上冲浪9 小时前
当全国人民用 AI 点奶茶时,你的企业官网还在“人工建站”吗?
人工智能
victory04319 小时前
hello_agent第九章总结
人工智能·agent
骇城迷影9 小时前
Makemore 核心面试题大汇总
人工智能·pytorch·python·深度学习·线性回归
Leoobai9 小时前
当我花30分钟让AI占领了我的树莓派
人工智能
AI资源库9 小时前
Remotion 一个用 React 程序化制作视频的框架
人工智能·语言模型·音视频
Web3VentureView9 小时前
SYNBO Protocol AMA回顾:下一个起点——什么将真正推动比特币重返10万美元?
大数据·人工智能·金融·web3·区块链