鱼C论坛

 找回密码
 立即注册
查看: 96|回复: 1

[技术交流] abalone年龄预测案例

[复制链接]
发表于 2024-4-12 17:14:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 yinda_peng 于 2024-4-12 17:24 编辑
  由abalone的特征、标签数据来预测其年龄
  1. import pandas as pd

  2. ## 读取数据
  3. columns = ['Abalone sex','Longest shell length','Vertical length','Whole height','Whole weight','Shucked weight','Viscera weight','Shell weight','age']
  4. df = pd.read_csv('./input/abalone-data.txt',names=columns, header=None, sep=",")
  5. ## 查看数据前5行
  6. df.head()
复制代码
记得更换路径
  1. ## 查看数据集的基本信息
  2. df.info()
  3. # 返回各类数据的统计变量
  4. df.describe()
  5. # 可观测到数据近似服从正态分布

  6. import seaborn as sb

  7. # 查看各变量两两之间的数据关系,同一变量使用直方图

  8. sb.pairplot(df)
  9. # 绘制热力图,查看各变量间的线性相关性

  10. # 变量之间的线性关系默认使用皮尔森相关系数(-1,1)进行衡量

  11. sb.heatmap(df.corr(),annot=True,cmap='Greens')
复制代码

  接下来对数据做一些处理,并完成求闭式解后得到的预测结果的验证

  1. # 处理数据

  2. def loadDataset(filepath):
  3.     data = []
  4.     label = []
  5.    
  6.     # 读取(r)的方式打开 filepath 路径下的数据集
  7.     # with 语句可实现自动调用 close的功能
  8.    
  9.     with open(filepath,'r') as f:
  10.         
  11.         #  读取文件的所有行,返回一个列表,每一行为一个元素
  12.         # 元素的数据类型为字符型,末尾部分存在符号:\n,需要删除
  13.         files = f.readlines()
  14.         
  15.         # 观察数据,第一列为鲍鱼性别,转为整型数据
  16.         # 分出特征与标签
  17.         
  18.         for line in files:
  19.             line = line.strip('\n').split(',')
  20.             # 去掉末尾符号:\n,将字符串以','为分隔符转化为一系列字符并存入一个列表中
  21.             if line[0]=='M':
  22.                 line[0] = 0
  23.             elif line[0] == 'F':
  24.                 line[0] = 1
  25.             else:
  26.                 line[0]=2
  27.             # 利用 for循环 将 字符类型 强制转换为 浮点类型   
  28.             line = [float(i) for i in line]
  29.             data.append(line[:-1])
  30.             label.append(line[-1])
  31.     return data,label

  32. abalonedata,abalonelabel = loadDataset('./input/abalone-data.txt')
  33. # 划分数据集
  34. from sklearn.model_selection import train_test_split
  35. x_train,x_test,y_train,y_test = train_test_split(np.array(abalonedata),np.array(abalonelabel),test_size=0.2)
  36. print(x_train)
  37. print(y_train)

  38. # 按列添加偏置项
  39. x_train_1 = np.c_[x_train,np.ones(len(x_train))]
  40. x_test_1 = np.c_[x_test,np.ones(len(x_test))]
  41. # 求闭式解
  42. w=np.linalg.pinv(x_train_1).dot(y_train)
  43. print(w)
  44. # 验证预测结果
  45. # 从测试集中随机抽取某个样本数据 x得到预测结构y_predict与对应的标签数据 y进行对比

  46. # 随机抽取样本序号
  47. a = np.random.choice(list(range(len(y_test))))

  48. # 取出样本序号对应的样本与标签
  49. test_data,test_label = x_test[a],y_test[a]
  50. print(test_label)
  51. predict_label = np.sum(np.c_[test_data.reshape(1,-1),np.ones(1)] * w)
  52. print(predict_label)
  53. # 评价指标:均值绝对误差 与 均方误差
  54. from sklearn.metrics import mean_absolute_error,mean_squared_error

  55. # 对整个测试集进行预测,并计算与测试标签之间的误差
  56. predict_label = x_test_1.dot(w.reshape(-1,1))
  57. print(mean_squared_error(y_test,predict_label),mean_absolute_error(y_test,predict_label))
复制代码



数据集.zip

49.37 KB, 下载次数: 0

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-4-12 17:15:23 | 显示全部楼层
这是一个用于预测abalone(一种贻贝)年龄的案例。我们首先要导入必要的包,并读取数据集。

  1. import pandas as pd

  2. # 读取数据
  3. columns = ['Sex', 'Length', 'Diameter', 'Height', 'Whole weight',
  4.            'Shucked weight', 'Viscera weight', 'Shell weight', 'Rings']
  5. df = pd.read_csv('./input/abalone-data.txt',names=columns, header=None, sep=",")
  6. # 查看数据前5行
  7. df.head()
  8. # 查看数据集的基本信息
  9. df.info()
  10. # 返回各类数据的统计变量
  11. df.describe()
复制代码


接下来,我们可以使用seaborn库绘制两个变量之间的关系图和热力图,以了解它们之间的线性相关性。

  1. import seaborn as sb

  2. # 查看各变量两两之间的数据关系,同一变量使用直方图
  3. sb.pairplot(df)
  4. # 绘制热力图,查看各变量间的线性相关性。变量之间的线性关系默认使用皮尔森相关系数(-1,1)进行衡量
  5. sb.heatmap(df.corr(),annot=True)
复制代码


接下来,我们需要对数据进行处理并完成闭式解。

  1. import numpy as np

  2. # 处理数据
  3. def loadDataset(filepath):
  4.     data = []
  5.     label = []
  6.    
  7.     with open(filepath,'r') as f:
  8.         files = f.readlines()
  9.         
  10.         for line in files:
  11.             line = line.strip('\n').split(',')
  12.             
  13.             if line=='M':
  14.                 line = 0
  15.             elif line == 'F':
  16.                 line = 1
  17.             else:
  18.                 line=2
  19.             
  20.             line = [float(elem) for elem in line]
  21.             
  22.             data.append(line)
  23.             label.append(line)
  24.     return data,label

  25. abalonedata,abalonelabel = loadDataset('./input/abalone-data.txt')

  26. from sklearn.model_selection import train_test_split

  27. x_train,x_test,y_train,y_test = train_test_split(np.array(abalonedata),np.array(abalonelabel),test_size=0.2)

  28. # 按列添加偏置项
  29. x_train_1 = np.c_[np.ones(len(x_train)), x_train]
  30. x_test_1 = np.c_[np.ones(len(x_test)), x_test]

  31. # 求闭式解
  32. w=np.linalg.pinv(x_train_1).dot(y_train)
复制代码


最后,我们可以验证预测结果,并计算均值绝对误差和均方误差作为评价指标。

  1. # 验证预测结果
  2. a = np.random.choice(list(range(len(y_test))))
  3. test_data,test_label = x_test,y_test
  4. predict_label = np.sum(x_test_1 * w)

  5. # 评价指标:均值绝对误差 与 均方误差
  6. from sklearn.metrics import mean_absolute_error,mean_squared_error

  7. predict_label = x_test_1.dot(w.reshape(-1,1))
  8. print(mean_squared_error(y_test,predict_label),mean_absolute_error(y_test,predict_label))
复制代码


希望这个案例能帮助到你!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-1 20:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表