文章目录

  • 总体思路分为三部
    • 1.查看数据,对数据进行清洗,规约
      • 1.1 查看数据
      • 1.2 数据清洗,规约
      • 1.3 删除不相关的特征
      • 1.4 数据one-hot处理*
    • 2.建立模型,挑选出最优参数
      • 2.1 准备数据集,训练集,测试集
      • 2.2 建立随机森林模型
      • 2.3 通过树的大小和K折验证得到log_loss最小的值和最优树的数量
      • 2.4 通过树的深度和K折验证得到log_loss最小的值和最大深度的最优值
    • 3.绘制模型训练过程的损失值改变的图
    • 4.训练模型

总体思路分为三部

1.查看数据,对数据进行清洗,规约

1.1 查看数据

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inlinefrom sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import KFold
filename= "data.csv"
raw = pd.read_csv(filename)
print (raw.shape)
raw.head()

1.2 查看 loc_x and loc_y,# lat and lon的关系

#plt.subplot(211) first is raw second Column
alpha = 0.02
plt.figure(figsize=(10,10))# loc_x and loc_y
plt.subplot(121)
plt.scatter(kobe.loc_x, kobe.loc_y, color='R', alpha=alpha)
plt.title('loc_x and loc_y')# lat and lon
plt.subplot(122)
plt.scatter(kobe.lon, kobe.lat, color='B', alpha=alpha)
plt.title('lat and lon')

1.2 数据清洗,规约

raw['dist'] = np.sqrt(raw['loc_x']**2 + raw['loc_y']**2)#将坐标转为距离
loc_x_zero = raw['loc_x'] == 0
#print (loc_x_zero)
raw['angle'] = np.array([0]*len(raw))
raw['angle'][~loc_x_zero] = np.arctan(raw['loc_y'][~loc_x_zero] / raw['loc_x'][~loc_x_zero])
raw['angle'][loc_x_zero] = np.pi / 2   #得到坐标的角度
#统一时间
raw['remaining_time'] = raw['minutes_remaining'] * 60 + raw['seconds_remaining']
#查看各类型的唯一值
print(kobe.action_type.unique())
print(kobe.combined_shot_type.unique())
print(kobe.shot_type.unique())
print(kobe.shot_type.value_counts())

打印结果:

season值

kobe['season'].unique()


得到有用的season值

raw['season'] = raw['season'].apply(lambda x: int(x.split('-')[1]) )
raw['season'].unique()

print(kobe['team_id'].unique())
print(kobe['team_name'].unique())


team_id,team_name特征太少,需要删除

比赛球队信息

pd.DataFrame({'matchup':kobe.matchup, 'opponent':kobe.opponent})


kobe.matchup特征少,需删除

plt.figure(figsize=(5,5))
plt.scatter(raw.dist, raw.shot_distance, color='blue')
plt.title('dist and shot_distance')


将dist和 shot_distance作比较,发现特征类似,删除一个即可

shot_zone_area:

gs = kobe.groupby('shot_zone_area')
print (kobe['shot_zone_area'].value_counts())
print (len(gs))

import matplotlib.cm as cm
plt.figure(figsize=(20,10))def scatter_plot_by_category(feat):alpha = 0.1gs = kobe.groupby(feat)cs = cm.rainbow(np.linspace(0, 1, len(gs)))for g, c in zip(gs, cs):plt.scatter(g[1].loc_x, g[1].loc_y, color=c, alpha=alpha)# shot_zone_area
plt.subplot(131)
scatter_plot_by_category('shot_zone_area')
plt.title('shot_zone_area')# shot_zone_basic
plt.subplot(132)
scatter_plot_by_category('shot_zone_basic')
plt.title('shot_zone_basic')# shot_zone_range
plt.subplot(133)
scatter_plot_by_category('shot_zone_range')
plt.title('shot_zone_range')

1.3 删除不相关的特征

drops = ['shot_id', 'team_id', 'team_name', 'shot_zone_area', 'shot_zone_range', 'shot_zone_basic', \'matchup', 'lon', 'lat', 'seconds_remaining', 'minutes_remaining', \'shot_distance', 'loc_x', 'loc_y', 'game_event_id', 'game_id', 'game_date']
for drop in drops:raw = raw.drop(drop, 1)

1.4 数据one-hot处理*

combined_shot_type

print (raw['combined_shot_type'].value_counts())
pd.get_dummies(raw['combined_shot_type'], prefix='combined_shot_type')[0:2]#输出前两行


分类变量one-hot处理

categorical_vars = ['action_type', 'combined_shot_type', 'shot_type', 'opponent', 'period', 'season']
for var in categorical_vars:raw = pd.concat([raw, pd.get_dummies(raw[var], prefix=var)], 1)raw = raw.drop(var, 1)

2.建立模型,挑选出最优参数

2.1 准备数据集,训练集,测试集

train_kobe = raw[pd.notnull(raw['shot_made_flag'])]
train_kobe = train_kobe.drop('shot_made_flag', 1) #x_train
train_label = train_kobe['shot_made_flag']  #y_train
test_kobe = raw[pd.isnull(raw['shot_made_flag'])]
test_kobe = test_kobe.drop('shot_made_flag', 1)  #x_test

2.2 建立随机森林模型

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import confusion_matrix,log_loss
import time
`import numpy as np
range_m = np.logspace(0,2,num=5).astype(int)
range_m #树的深度

range_n = np.logspace(0,2,num=3).astype(int)
range_n#树的数量

2.3 通过树的大小和K折验证得到log_loss最小的值和最优树的数量

# find the best n_estimators for RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import KFoldprint('Finding best n_estimators for RandomForestClassifier...')
min_score = 100000
best_n = 0
scores_n = []for n in range_n:print("the number of trees : {0}".format(n))t1 = time.time()rfc_score = 0.rfc = RandomForestClassifier(n_estimators=n)for train_k, test_k in KFold(len(train_kobe), n_folds=10, shuffle=True):rfc.fit(train_kobe.iloc[train_k], train_label.iloc[train_k])#rfc_score += rfc.score(train.iloc[test_k], train_y.iloc[test_k])/10pred = rfc.predict(train_kobe.iloc[test_k])rfc_score += log_loss(train_label.iloc[test_k], pred) / 10scores_n.append(rfc_score)if rfc_score < min_score:min_score = rfc_scorebest_n = nt2 = time.time()print('Done processing {0} trees ({1:.3f}sec)'.format(n, t2-t1))
print(best_n, min_score)

2.4 通过树的深度和K折验证得到log_loss最小的值和最大深度的最优值

# find best max_depth for RandomForestClassifier
print('Finding best max_depth for RandomForestClassifier...')
min_score = 100000
best_m = 0
scores_m = []
range_m = np.logspace(0,2,num=3).astype(int)
for m in range_m:print("the max depth : {0}".format(m))t1 = time.time()rfc_score = 0.rfc = RandomForestClassifier(max_depth=m, n_estimators=best_n)for train_k, test_k in KFold(len(train_kobe), n_folds=10, shuffle=True):rfc.fit(train_kobe.iloc[train_k], train_label.iloc[train_k])#rfc_score += rfc.score(train.iloc[test_k], train_y.iloc[test_k])/10pred = rfc.predict(train_kobe.iloc[test_k])rfc_score += log_loss(train_label.iloc[test_k], pred) / 10scores_m.append(rfc_score)if rfc_score < min_score:min_score = rfc_scorebest_m = mt2 = time.time()print('Done processing {0} trees ({1:.3f}sec)'.format(m, t2-t1))
print(best_m, min_score)

3.绘制模型训练过程的损失值改变的图

plt.figure(figsize=(10,5))
plt.subplot(121)
plt.plot(range_n, scores_n)
plt.ylabel('score')
plt.xlabel('number of trees')plt.subplot(122)
plt.plot(range_m, scores_m)
plt.ylabel('score')
plt.xlabel('max depth')

4.训练模型

model = RandomForestClassifier(n_estimators=best_n, max_depth=best_m)
model.fit(train_kobe, train_label)

机器学习实战之科比数据集分析(随机森林寻最优值参数)相关推荐

  1. 机器学习实战7-sklearn集成学习和随机森林

    集成方法:聚合一组预测器(比如分类器或回归器)的预测,得到的预测结果也比最好的单个预测器要好. 例如,你可以训练一组决策树分类器,每一棵树都基于训练集不同的随机子集进行训练.做出预测时,你只需要获得所 ...

  2. 【ML】基于机器学习的心脏病预测研究(附代码和数据集,随机森林模型)

    写在前面: 首先感谢兄弟们的订阅,让我有创作的动力,在创作过程我会尽最大努力,保证作品的质量,如果有问题,可以私信我,让我们携手共进,共创辉煌. 之前创作过心脏病预测研究文章如下: [ML]基于机器学 ...

  3. 机器学习(九)决策树,随机森林

    机器学习(九)决策树,随机森林 文章目录 机器学习(九)决策树,随机森林 一.决策树 1.1 如何理解决策树 1.2 信息论的一些基础 1.3 信息论与决策树的关系 1.3.1 信息增益 1.4 常见 ...

  4. 词袋模型 matlab,【火炉炼AI】机器学习051-视觉词袋模型+极端随机森林建立图像分类器...

    [火炉炼AI]机器学习051-视觉词袋模型+极端随机森林建立图像分类器 (本文所使用的Python库和版本号: Python 3.6, Numpy 1.14, scikit-learn 0.19, m ...

  5. 机器学习实战-65:主成因分析降维算法(Principal Component Analysis)

    机器学习实战-65:主成因分析降维算法(PCA) 深度学习原理与实践(开源图书)-总目录,建议收藏,告别碎片阅读! 机器学习分为监督学习.无监督学习和半监督学习(强化学习).无监督学习最常应用的场景是 ...

  6. 【R代码 (葡萄酒)及其可视化分析 #随机森林-支持向量机】

    在 R代码 (葡萄酒)及其可视化分析 #随机森林-支持向量机 library(ggplot2)#绘图工具 library(tidyverse)#ggplot2/dplyr等万能包 read.csv(& ...

  7. 西瓜书+实战+吴恩达机器学习(十三)监督学习之随机森林 Random Forest

    文章目录 0. 前言 1. 随机森林算法 如果这篇文章对你有一点小小的帮助,请给个关注,点个赞喔,我会非常开心的~ 0. 前言 Bagging:对数据集进行有放回采样,采mmm次构成一个新的数据集,基 ...

  8. 机器学习实践之集成方法(随机森林和AdaBoost元算法提高分类性能)

       本文根据最近学习机器学习书籍网络文章的情况,特将一些学习思路做了归纳整理,详情如下.如有不当之处,请各位大拿多多指点,在此谢过. (未添加文章标签,特此补上,2018.1.14记.) 一.概述 ...

  9. 随机森林python_实战:用Python实现随机森林

    摘要: 随机森林如何实现?为什么要用随机森林?看这篇足够了! 因为有Scikit-Learn这样的库,现在用Python实现任何机器学习算法都非常容易.实际上,我们现在不需要任何潜在的知识来了解模型如 ...

最新文章

  1. 学习Python编程开发可以从事的岗位有哪些?
  2. git2.29.2.2怎么安装_制作Win10安装U盘时install.wim大于4G怎么办?
  3. GridView中实现单选RadioButton
  4. LaTeX 使用 bib 管理参考文献时,引用网络资源 URL 导致排版难看的问题
  5. 使用C# lock同时访问共享数据
  6. Spring,Reactor和ElasticSearch:使用伪造的测试数据进行标记
  7. 【渝粤题库】陕西师范大学200651线性代数 作业(高起专、高起本)
  8. C#中ToString格式大全
  9. [转载] 字符串太长 pep8_Python f字符串– PEP 498 –文字字符串插值
  10. 移动端js事件-了解
  11. MySQL 手工注入常用语句
  12. oracle上浮下浮分析函数_Oracle分析函数简析
  13. . 在第一代计算机时代 编程采用,在第一代计算机时代,编程采用什么语言
  14. WIN10专业版如何调整系统字体大小
  15. HikariPool-1 - Exception during pool initialization. Could not create connection
  16. 绘制奥林匹克标志——利用python turtle画奥运五环
  17. linux pipe2函数,pipe()函数 Unix/Linux
  18. 多边形面积计算公式, 根据GPS经纬度计算面积
  19. 花菁染料CY3标记聚乙二醇修饰的活性基团MAL/SH/NH2-星戈瑞
  20. 驱动中同步与异步发送IRP

热门文章

  1. 嵌入式软件工程师笔试题-1(含答案讲解)
  2. 对于windows10家庭版无法勾选Hyper-V的问题的解决
  3. mac系统清理软件MacClean支持文件类型分享
  4. ES6代码转ES5代码
  5. 微信小程序wxs文件,(indexOf方法)
  6. Android自定义日历源码收集
  7. CityEngine 2013部署安装
  8. 新的一步,从现在开始
  9. Pytorch 中 CAM绘制热度图
  10. MySQL基础环节余胜军课堂笔记