我是靠谱客的博主 怕黑小懒虫,最近开发中收集的这篇文章主要介绍随机森林算法python实现瞎BB代码样本数据,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

随机森林算法python实现

  • 瞎BB
  • 代码
    • 导入数据
    • 切分训练集测试集
    • 找到最有用的几个属性
    • 根据上面的代码更改属性
    • 参数组合遍历找最优
    • 随机森林
  • 样本数据

瞎BB

1.实现根据样本数据(用眼距离distance、最长持续用眼时长duration、总用眼时长total_time、户外运动时长outdoor、用眼角度angle、健康环境光照用眼比例proportion)判别是否需要近视预警
2.样本实在太少,结果还行,原理都是一样的

代码

导入数据

import pandas
patients = pandas.read_csv("data.csv")
patients.head(5)

切分训练集测试集

from sklearn.model_selection import train_test_split
patients_data=patients.loc[:,'distance':'proportion']
patients_target=patients.loc[:,'warning']
data_train,data_test,target_train,target_test=train_test_split(patients_data,patients_target,test_size=0.1,random_state=42)

找到最有用的几个属性

import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
import matplotlib.pyplot as plt
predictors = ["distance", "duration", "total_time", "outdoor", "angle", "proportion"]

selector = SelectKBest(f_classif, k=5)
selector.fit(data_train, target_train)

scores = -np.log10(selector.pvalues_)

plt.bar(range(len(predictors)), scores)
plt.xticks(range(len(predictors)), predictors, rotation='vertical')
plt.show()

根据上面的代码更改属性

predictors_best = ["distance", "total_time", "angle", "proportion"]
data_train = data_train[predictors_best]
data_test = data_test[predictors_best]

参数组合遍历找最优

from sklearn.model_selection import GridSearchCV
tree_param_grid = { 'min_samples_split': list((2,3,4)),'n_estimators':list((3,5,10,15,20,25,30,35,40,45,50))}
grid = GridSearchCV(RandomForestClassifier(),param_grid=tree_param_grid, cv=kf)#(算法,调节参数(用字典形式),交叉验证次数)
grid.fit(data_train, target_train)#训练集
grid.cv_results_ , grid.best_params_, grid.best_score_#得分,最优参数,最优得分

随机森林

from sklearn import model_selection
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(random_state=1, n_estimators=35, min_samples_split=2, min_samples_leaf=2)
#交叉验证
kf = model_selection.KFold(n_splits=3)
scores = model_selection.cross_val_score(rf, data_train, target_train, cv=kf)
print(scores.mean())

样本数据

sampledistancedurationtotal_timeoutdoorangleproportionwarning(1 yes 0 no)
1207234414811811
234682631357501
325983573212641
437652911578890
53415116216918631
63017825914632501
720351343723680
839111169874520
9224426513614761
10391512191402550
11211791846418601
1225412417116721
131817128613135891
14323323610229501
152013322612417811
16171482366632751
1734111214575880
18248516315514321
193216527614633521
202512435917133700
2131511674725470
2231633525822441
2316581644513730
24293732610433681
253447197595660
263612318516526700
27251261714523331
283184983730511
29309215311414480
302917827814627451

最后

以上就是怕黑小懒虫为你收集整理的随机森林算法python实现瞎BB代码样本数据的全部内容,希望文章能够帮你解决随机森林算法python实现瞎BB代码样本数据所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(66)

评论列表共有 0 条评论

立即
投稿
返回
顶部