Kaggle:收入分类

先看一下数据的统计信息

python 复制代码
import pandas as pd   
  
# 加载数据(保留原路径,但在实际应用中建议使用相对路径或环境变量)  
data = pd.read_csv(r"C:\Users\11794\Desktop\收入分类\training.csv", encoding='utf-8', encoding_errors='replace')  
  
# 查看数据信息和描述 
data.info()
 
data.head()

data.describe()    

数据是已经处理好了的,利用代码绘制热力图查看各特征间的相关性

python 复制代码
import pandas as pd  
import seaborn as sns  
import matplotlib.pyplot as plt  
  
# 加载数据(保留原路径,但在实际应用中建议使用相对路径或环境变量)  
data = pd.read_csv(r"C:\Users\11794\Desktop\收入分类\training.csv", encoding='utf-8', encoding_errors='replace')  
  
# 绘制热力图  
# 选择数值列进行相关性分析  
numerical_columns = data.select_dtypes(include=['int64', 'float64']).columns
# 计算相关性矩阵  
correlation_matrix = data[numerical_columns].corr()  
# 绘制热力图  
plt.figure(figsize=(12, 10))  
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', linewidths=0.5)  
plt.title('Correlation Heatmap')  
plt.savefig('correlation_heatmap.png', bbox_inches='tight')  # 保存热力图到当前目录

Class列为分类目标,可以看到有些列和他的相关性达到了0.9以上,这里就能估计出来模型效果会很好。

决策树模型分类'Class'

python 复制代码
import pandas as pd    
from sklearn.model_selection import train_test_split    
from sklearn.tree import DecisionTreeClassifier  # 导入决策树分类器  
from sklearn.metrics import classification_report    
import matplotlib.pyplot as plt    
from sklearn.metrics import roc_curve, auc  
import numpy as np  
  
# 加载数据(假设数据保存在CSV文件中)    
data = pd.read_csv(r"C:\Users\11794\Desktop\收入分类\training.csv", encoding='utf-8', encoding_errors='replace')   
test_data = pd.read_csv(r"C:\Users\11794\Desktop\收入分类\testing.csv", encoding='utf-8', encoding_errors='replace')    
  
# 选择特征和目标变量    
X = data.drop(['id', 'Class'], axis=1)   
y = data['Class']  # 目标变量是'Class'列    
    
# 数据分割    
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.01, random_state=42)    
    
# 创建并训练模型    
# 使用决策树分类器  
model = DecisionTreeClassifier(max_depth=30, random_state=42)  # 修改此行  
model.fit(X_train, y_train)    
   
      
# 预测测试集并评估模型    
y_pred = model.predict(X_test)    
print(classification_report(y_test, y_pred))  # 打印分类报告  
  
# 选择test_data中的特征列    
test_X = test_data.drop(['id'], axis=1)    
# 使用训练好的模型进行预测    
test_y_pred = model.predict(test_X)

模型的准确率达到了1.0,能够完全准确分类出收入水平。

相关推荐
belong_to_you2 分钟前
python模块——tqdm
python
数模竞赛Paid answer2 分钟前
数学建模-嘉陵江铊污染事件解题全过程文档及程序
数学建模·数据分析
L_cl33 分钟前
【Python 算法零基础 4.排序 ⑪ 十大排序算法总结】
python·算法·排序算法
Vertira35 分钟前
Pytorch安装后 如何快速查看经典的网络模型.py文件(例如Alexnet,VGG)(已解决)
人工智能·pytorch·python
老歌老听老掉牙1 小时前
使用 SymPy 进行向量和矩阵的高级操作
python·线性代数·算法·矩阵·sympy
DX_dove1 小时前
pytorch3d+pytorch1.10+MinkowskiEngine安装
人工智能·pytorch·python
且慢.5891 小时前
Python——day46通道注意力(SE注意力)
python·深度学习·机器学习
善木科研1 小时前
读文献先读图:GO弦图怎么看?
机器学习·数据分析·r语言
电商API_180079052471 小时前
构建高效可靠的电商 API:设计原则与实践指南
运维·服务器·爬虫·数据挖掘·网络爬虫
简诚1 小时前
PPHGNetV2源代码解析
python·深度学习·机器学习