使用机器学习一起挖掘幸福感

幸福感是一个古老而深刻的话题,是人类世代追求的方向。与幸福感相关的因素成千上万、因人而异,大如国计民生,小如路边烤红薯,都会对幸福感产生影响。这些错综复杂的因素中,我们能找到其中的共性,一窥幸福感的要义吗?

在社会科学领域,幸福感的研究占有重要的位置。这个涉及了哲学、心理学、社会学、经济学等多方学科的话题复杂而有趣;同时与大家生活息息相关,每个人对幸福感都有自己的衡量标准。如果能发现影响幸福感的共性,生活中是不是将多一些乐趣;如果能找到影响幸福感的政策因素,便能优化资源配置来提升国民的幸福感。目前社会科学研究注重变量的可解释性和未来政策的落地,主要采用了线性回归和逻辑回归的方法,在收入、健康、职业、社交关系、休闲方式等经济人口因素;以及政府公共服务、宏观经济环境、税负等宏观因素上有了一系列的推测和发现。

使用文件请在快来一起挖掘幸福感!赛题与数据-天池大赛-阿里云天池 下载。

1、导入包

# 引入包
##  基础函数库
import numpy as np 
import pandas as pd

## 绘图函数库
import matplotlib.pyplot as plt
import seaborn as sns

2、我们利用Pandas自带的read_csv函数读取并转化为DataFrame格式,利用.info()查看数据的整体信息

df = pd.read_csv('./happiness_train_abbr.csv')
df.info()

3、分析并清理数据


#删除缺失数据28  work_status,work_yr,work_type,work_manage
drop_cols=['work_status','work_yr','work_type','work_manage']
df.drop(drop_cols, axis=1,inplace=True)

# family_income 缺失数据补足
df.fillna(method='ffill',inplace=True)

y = df.happiness
y.value_counts()

dft=df.copy()
# 删除时间列:survey_time
drop_cols=['happiness','survey_time']
dft.drop(drop_cols, axis=1,inplace=True)
dft.info()

# nationality,religion,religion_freq 数值变化不大,删除
drop_cols=['learn','relax','hukou','weight_jin','political','edu','gender','survey_type','province','county']
dft.drop(drop_cols, axis=1,inplace=True)

4、分析特征

data = dft
data_std = (data - data.mean()) / data.std()
data = pd.concat([y, data_std.iloc[:, 0:9]], axis=1)
data = pd.melt(data, id_vars='happiness', var_name='Features', value_name='Values')

fig, ax = plt.subplots(1,2,figsize=(30,15))

# 绘制小提琴图
sns.violinplot(x='Features', y='Values', hue='happiness', data=data,inner='quart', ax=ax[0], palette='Blues')
fig.autofmt_xdate(rotation=45)

data = dft
data_std = (data - data.mean()) / data.std()
data = pd.concat([y, data_std.iloc[:, 9:18]], axis=1)
data = pd.melt(data, id_vars='happiness', var_name='Features', value_name='Values')

# 绘制小提琴图
sns.violinplot(x='Features', y='Values', hue='happiness', data=data, inner='quart', ax=ax[1], palette='Blues')
fig.autofmt_xdate(rotation=45)

plt.show()


# learn,relax,hukou,weight_jin,political,edu,gender,suney_type差别不大,删除
plt.figure(figsize=(18,14))
sns.heatmap(round(dft.corr(),2), cmap='Blues', annot=True)
plt.show()

dfx=df.copy()
y=dfx.happiness
drop_cols=['happiness','survey_time']
dfx.drop(drop_cols, axis=1,inplace=True)
dfx.info()

5、训练数据

## 为了正确评估模型性能,将数据划分为训练集和测试集,并在训练集上训练模型,在测试集上验证模型性能。
from sklearn.model_selection import train_test_split
x=dfx
## 选择其类别为0和1的样本 (不包括类别为2的样本)
data_target_part = y
data_features_part = x

## 测试集大小为20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(data_features_part, data_target_part, test_size = 0.2, random_state = 2020)

## 导入XGBoost模型
from xgboost.sklearn import XGBClassifier
## 定义 XGBoost模型 
clf = XGBClassifier()
# 在训练集上训练XGBoost模型
clf.fit(x_train, y_train)


## 在训练集和测试集上分布利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
from sklearn import metrics

## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('The train of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The test of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))

## 查看混淆矩阵 (预测值和真实值的各类情况统计矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)

# 利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()

得到预测结果:

The train of the Logistic Regression is: 0.66546875
The test of the Logistic Regression is: 0.6275

6、优化特征值

? sns.barplot
sns.barplot(y=data_features_part.columns, x=clf.feature_importances_)

## 从sklearn库中导入网格调参函数
from sklearn.model_selection import GridSearchCV

## 定义参数取值范围
learning_rate = [0.1, 0.3, 0.6]
subsample = [0.8, 0.9]
colsample_bytree = [0.6, 0.8]
max_depth = [3,5,8]

parameters = { 'learning_rate': learning_rate,
              'subsample': subsample,
              'colsample_bytree':colsample_bytree,
              'max_depth': max_depth}
model = XGBClassifier(n_estimators = 50)

## 进行网格搜索
clf = GridSearchCV(model, parameters, cv=3, scoring='accuracy',verbose=1,n_jobs=-1)
clf = clf.fit(x_train, y_train)

## 网格搜索后的最好参数为
clf.best_params_

得到优化结果:

{'colsample_bytree': 0.6,
 'learning_rate': 0.1,
 'max_depth': 5,
 'subsample': 0.8}

7、使用新的特征参数进行训练

## 在训练集和测试集上分布利用最好的模型参数进行预测

## 定义带参数的 XGBoost模型 
clf = XGBClassifier(colsample_bytree = 0.6, learning_rate = 0.1, max_depth= 5, subsample = 0.8)
# 在训练集上训练XGBoost模型
clf.fit(x_train, y_train)

train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)

## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the test Regression is:',metrics.accuracy_score(y_test,test_predict))

## 查看混淆矩阵 (预测值和真实值的各类情况统计矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)

# 利用热力图对于结果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()

得到预测值:

The accuracy of the train Regression is: 0.7765625
The accuracy of the test Regression is: 0.63375

8、预测数据,得到预测结果

# 预测数据
dfn = pd.read_csv('./happiness_test_abbr.csv')
drop_clo=['survey_time','work_status','work_yr','work_type','work_manage']
dfn.drop(drop_clo,axis=1,inplace=True)

clf = XGBClassifier(colsample_bytree = 0.6, learning_rate = 0.1, max_depth= 5, subsample = 0.8)
# 在训练集上训练XGBoost模型
clf.fit(x_train, y_train)

new_predict = clf.predict(dfn)

9、导出数据

dfy=pd.DataFrame(new_predict)

dfy['id']=dfn['id']
dfy.info()

dfy.set_index('id')

dfy.to_csv('./happiness_test_result_wangrain.csv')

10、结束分析。

本次分析使用了XGBoost系统进行分类训练,整个过程中发现对数据的分析和处理部分有很大的主观性,还需要不断的学习、练习并掌握如何去除不必要的特征,如何合并特征。

路漫漫其修远兮,吾将上下而求索!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值