【数据科学项目1】:构建你的第一个数据科学项目_health index(2)

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

region 0
charges 0
dtype: int64


**数据转换——它涉及更改列的数据类型、创建派生列或删除重复数据等等**


**探索性数据分析**——对数据集执行单变量和多变量分析,以发现其中隐藏的一些关系


下面我们来对数值和分类变量进行数据清理和探索性数据分析。


### 探索性数据分析


**对于数值型变量的分析**



#数值型变量的可视化

直方图绘制

fig,axes = plt.subplots(1,2,figsize=(12,6))
plt.style.use(‘ggplot’)#使用ggplot主题,R语言的一个绘图包
sns.histplot( health_ins_df[‘age’] , color=“skyblue”,ax=axes[0])
sns.histplot( health_ins_df[‘bmi’] , color=“olive”,ax=axes[1])
plt.show()


![image-20220817095825845](https://img-blog.csdnimg.cn/img_convert/3fe5ba84c899770e9e352cf779bbd69e.png)


* 我们可以把年龄进行**分组转换为年龄段**
* BMI接近**正态分布**



箱线图

fig,axes=plt.subplots(1,2,figsize=(10,5))
sns.boxplot(x = ‘age’, data = health_ins_df, ax=axes[0])
sns.boxplot(x = ‘bmi’, data = health_ins_df, ax=axes[1])
plt.show()


![](https://img-blog.csdnimg.cn/img_convert/1ad49ffb54675c1b2f28779743aface3.png#pic_center)


可以看出BMI存在一些**离群值** , 现在我们来看一下这些点



outlier_list = boxplot_stats(health_ins_df.bmi).pop(0)[‘fliers’].tolist()
print(outlier_list)
#查找包含异常值的行数
outlier_bmi_rows = health_ins_df[health_ins_df.bmi.isin(outlier_list)].shape[0]
print(“bmi 中包含异常值的行数:”, outlier_bmi_rows)

#离群值占比
#Percentage of rows which are outliers
percent_bmi_outlier = (outlier_bmi_rows/health_ins_df.shape[0])*100
print("bmi离群值异常值的百分比 : ", percent_bmi_outlier)



[49.06, 48.07, 47.52, 47.41, 50.38, 47.6, 52.58, 47.74, 53.13]
bmi 中包含异常值的行数: 9
bmi离群值异常值的百分比 : 0.672645739910314


**数值变量的数据转换**



将年龄转换为分桶的

print("Minimum value for age : “, health_ins_df[‘age’].min(),”\nMaximum value for age : ", health_ins_df[‘age’].max())

‘’’
18至40岁的年龄将属于青年
41至58岁的年龄将低于中年
58岁以上将落入老年
‘’’
health_ins_df.loc[(health_ins_df[‘age’] >=18) & (health_ins_df[‘age’] <= 40), ‘age_group’] = ‘青年’
health_ins_df.loc[(health_ins_df[‘age’] >= 41) & (health_ins_df[‘age’] <= 58), ‘age_group’] = ‘中年’
health_ins_df.loc[health_ins_df[‘age’] > 58, ‘age_group’] = ‘老年’



Minimum value for age : 18
Maximum value for age : 64



去除BMI中的异常值

health_ins_df_clean = health_ins_df[~health_ins_df.bmi.isin(outlier_list)]
sns.boxplot(x = ‘bmi’, data = health_ins_df_clean)


![image-20220817100340013](https://img-blog.csdnimg.cn/img_convert/df79409d24a22f383131b4a90072017b.png#pic_center)


**对于分类型变量的分析**



fig,axes=plt.subplots(1,5,figsize=(20,8))
sns.countplot(x = ‘sex’, data = health_ins_df_clean, palette = ‘magma’,ax=axes[0])
sns.countplot(x = ‘children’, data = health_ins_df_clean, palette = ‘magma’,ax=axes[1])
sns.countplot(x = ‘smoker’, data = health_ins_df_clean, palette = ‘magma’,ax=axes[2])
sns.countplot(x = ‘region’, data = health_ins_df_clean, palette = ‘magma’,ax=axes[3])
sns.countplot(x = ‘age_group’, data = health_ins_df_clean, palette = ‘magma’,ax=axes[4])


![image-20220817101258434](https://img-blog.csdnimg.cn/img_convert/7a78842f210f7e8f2a9f1c049c09449c.png#pic_center)


数据准备完成后,下一阶段是建模。选择合适的算法将取决于数据的类型。例如,如果数据是连续的,您将应用回归建模,如果数据是分类的,您将应用分类算法建模。作为一名数据科学家,您将尝试许多模型来获得最合适的模型。


### **模型构建**


在根据**业务/技术限制**选择正确的模型之前,尝试并测试数据集上所有可能的模型。在这个阶段,你也可以尝试一些 bagging 或 boosting 技术。在这里,我分别构建了**线性回归模型、决策树回归、Gradient Boosting Regression.**


#### 简单的线性回归模型


在这里,我们首先使用线性回归模型作为基准模型。



from sklearn.linear_model import LinearRegression
lm = LinearRegression()
X = health_ins_df_processed.loc[:, health_ins_df_processed.columns != ‘charges’]#自闭哪里
y = health_ins_df_processed[‘charges’]#因变量
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)#划分训练集和测试集

lm.fit(X_train,y_train)
print(“R-Squared on train dataset={}”.format(lm.score(X_train,y_train)))#训练集R2
lm.fit(X_test,y_test)
print(“R-Squaredon test dataset={}”.format(lm.score(X_test,y_test)))#测试集R2



R-Squared on train dataset=0.7494776882061486
R-Squaredon test dataset=0.7372938495110573


从结果来看,使用简单的线性回归 
 
 
 
 
 
 R 
 
 
 2 
 
 
 
 
 R^2 
 
 
 R2为0.74,说明模型解释了数据74%的信息,我们下面来看一些更complex的模型


#### 决策树回归



X = health_ins_df_processed.loc[:, health_ins_df_processed.columns != ‘charges’]
y = health_ins_df_processed[‘charges’]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
dtr = DecisionTreeRegressor(max_depth=4,min_samples_split=5,max_leaf_nodes=10)#初始化参数
dtr.fit(X_train,y_train)
print(“R-Squared on train dataset={}”.format(dtr.score(X_train,y_train)))#训练集R2

dtr.fit(X_test,y_test)
print(“R-Squaredon test dataset={}”.format(dtr.score(X_test,y_test)))#测试集R2



R-Squared on train dataset=0.8594291626976573
R-Squaredon test dataset=0.8571718114547656


上面的参数是我随机设定,大家还可以对其进行调参能提高一定的效果,调参的代码我上传到**github**上了<https://github.com/JoJoYao996/data-science-projects>


#### Gradient Boosting Regression


**梯度提升回归模型的主要调整参数**


* **learning\_rate**:学习率,默认为0.1
* **n\_estimators**:默认为100
* **max\_depth**:单个回归估计器的最大深度。最大深度限制了树中的节点数。调整此参数以获得最佳性能;最佳值取决于输入变量的相互作用。值必须在 [1, inf) 范围内。
* **min\_samples\_split**:拆分内部节点所需的最小样本数:
* **min\_samples\_leaf**:叶节点最小样本数,这个参数会影响模型的平滑效果,尤其是在回归中。


我使用了**gridsearch来分别对这些参数调整,下面是调参之后的结果。**



#最终的模型
f_model = ensemble.GradientBoostingRegressor(learning_rate=0.015,n_estimators=250,max_depth=2,min_samples_leaf=5,
min_samples_split=2,subsample=1,loss = ‘squared_error’)
f_model.fit(X_train, y_train)
print(“Accuracy score (training): {0:.3f}”.format(f_model.score(X_train, y_train)))

f_model.fit(X_test, y_test)
print(“Accuracy score (test): {0:.3f}”.format(f_model.score(X_test, y_test)))



Accuracy score (training): 0.866
Accuracy score (test): 0.818


**查看特征的重要性**



#查看变量的重要性
feature_importance = f_model.feature_importances_
sorted_idx = np.argsort(feature_importance)#得到重要性的排序索引
fig = plt.figure(figsize=(12, 6))
pos = np.arange(sorted_idx.shape[0]) + .5
plt.barh(pos, feature_importance[sorted_idx], align=‘center’)
plt.yticks(pos, np.array(health_ins_df_processed.columns)[sorted_idx])
plt.show()


![image-20220817165712023](https://img-blog.csdnimg.cn/img_convert/b2572897f8e5554a20cf17a4e88a2492.png#pic_center)  
 **可以看出最重要的三个特征是:smoker\_no,children\_5,bmi**


### **保存模型**



保存模型

filename = ‘health_insurance_data_model.sav’
pickle.dump(f_model, open(filename, ‘wb’))



加载模型

filename = ‘health_insurance_data_model.sav’
loaded_model = pickle.load(open(filename, ‘rb’))
result = loaded_model.score(X_test, y_test)
print(result) #测试集精度



0.8180114370687565


## 4.准备总结



![img](https://img-blog.csdnimg.cn/img_convert/f05b964bf66873093e90b30b24b9df04.png)
![img](https://img-blog.csdnimg.cn/img_convert/0ea7730582b718d95d5990f2d2bf7898.png)
![img](https://img-blog.csdnimg.cn/img_convert/2e1455fb71e2cb30c4df56f5166390a1.png)

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/forums/4f45ff00ff254613a03fab5e56a57acb)**

0578)]
[外链图片转存中...(img-75LUPrpM-1715367980578)]
[外链图片转存中...(img-ov8RtYTU-1715367980578)]

**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**

**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/forums/4f45ff00ff254613a03fab5e56a57acb)**

  • 22
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值