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,能够完全准确分类出收入水平。

相关推荐
MyhEhud9 分钟前
kotlin @JvmStatic注解的作用和使用场景
开发语言·python·kotlin
yzx99101317 分钟前
支持向量机案例
算法·机器学习·支持向量机
狐凄23 分钟前
Python实例题:pygame开发打飞机游戏
python·游戏·pygame
漫谈网络30 分钟前
Telnet 类图解析
python·自动化·netdevops·telnetlib·网络自动化运维
农夫山泉2号2 小时前
【python】—conda新建python3.11的环境报错
python·conda·python3.11
ZHOU_WUYI3 小时前
Flask Docker Demo 项目指南
python·docker·flask
Narutolxy6 小时前
大模型数据分析破局之路20250512
人工智能·chatgpt·数据分析
码上淘金7 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo7 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
2301_787552878 小时前
console-chat-gpt开源程序是用于 AI Chat API 的 Python CLI
人工智能·python·gpt·开源·自动化