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

2023-05-16

文章目录

  • 总体思路分为三部
    • 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 inline

from 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.1
    gs = 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 KFold

print('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])/10
        pred = rfc.predict(train_kobe.iloc[test_k])
        rfc_score += log_loss(train_label.iloc[test_k], pred) / 10
    scores_n.append(rfc_score)
    if rfc_score < min_score:
        min_score = rfc_score
        best_n = n
        
    t2 = 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])/10
        pred = rfc.predict(train_kobe.iloc[test_k])
        rfc_score += log_loss(train_label.iloc[test_k], pred) / 10
    scores_m.append(rfc_score)
    if rfc_score < min_score:
        min_score = rfc_score
        best_m = m
    
    t2 = 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

  • 布谷鸟搜索算法

    布谷鸟搜索 xff08 Cuckoo Search xff0c 缩写 CS xff09 xff0c 也叫杜鹃搜索 xff0c 是由剑桥大学杨新社 xff08 音译自 xff1a Xin She Yang xff09 教授和S 戴布 xff0
  • 【IMX6ULL学习笔记之Linux系统移植05】——学习总结以及遇到的问题

    学习总结 此时Linux系统已经完毕 xff0c 此时的启动方式 xff0c U boot从内存卡启动 xff0c 然后通过bootcmd命令配合bootargs参数引导U boot从网络服务器 xff08 Ubuntu xff09 指定位
  • 各种dns:百度DNS/阿里DNS/114DNS/腾讯DNS/谷歌DNS/OpenDNS 对比评测

    不知道大家有没有过网络是正常的 xff0c QQ可以正常登录 游戏也可以正常玩 xff0c 但是网页无论如何都打不开 这就是电脑网络设置的DNS服务器有问题 xff0c 不是其故障就是不工作了 换了DNS服务器成功解决问题 下边给大家分享一
  • 【IMX6ULL学习笔记之Linux系统移植06】——笔记本安装Ubuntu系统开发

    背景 最近置办了一台台式机 xff0c 笔记本电脑性能看不上了 xff0c 就空置下来 xff0c 把笔记本安装成Ubuntu系统 xff0c 专门用来嵌入式学习 重新移植Linux系统 xff0c 再次学习 总结 U boot的seten
  • 【IMX6ULL学习笔记之驱动学习01】前言

    系统烧写 经过前面的移植 xff0c 现在我们已经移植好了Uboot和Linux Kernel xff0c 制作好了根文件系统 系统通过SD卡启动Uboot xff0c Uboot引导程序将Linux镜像文件 设备树文件和根文件系统从Ubu
  • 【IMX6ULL学习笔记之驱动学习02】LED字符设备驱动

    字符设备驱动开发 配置开发环境 新建一个VScode文档 xff0c 先配置开发环境 Ctrl span class token operator 43 span Shift span class token operator 43 spa
  • 第八章——常用数据排序算法之归并排序

    第八章 常用数据排序算法 概述 插入排序 选择排序和冒泡排序这些算法有一个共同的特点 xff0c 为了将N个无序数据进行排序最多需进行N 1轮处理 xff0c 每轮处理范围大小不同 xff08 2 N 1 xff09 xff0c 平均约N
  • ERROR:Did not find a cmdline Flattened Device Tree

    span class token operator 61 span span class token operator gt span bootz span class token number 80800000 span span cla
  • Linux中的英文简称的名字全称

    Linux中英文简称的全称 知道全称能更方便的记忆 ALSA xff08 Advanced Linux Sound Architecture xff09 高级Linux声音架构V4L2 xff08 Video for linux2 xff0
  • LeetCode_26

    删除有序数组中的重复项 给你一个 升序排列 的数组 nums xff0c 请你 原地 删除重复出现的元素 xff0c 使每个元素 只出现一次 xff0c 返回删除后数组的新长度 元素的 相对顺序 应该保持 一致 由于在某些语言中不能改变数组
  • 快乐的shell命令行

    快乐的shell命令行 PART1 基础 1 权限 超级用户权限 普通用户 2 复制粘贴 复制 xff1a 鼠标左键沿着文本拖动高亮的文本被复制到X管理的缓冲区 xff08 或者双击一个单词 xff09 粘贴 xff1a 鼠标中键 3 简单
  • Linux三剑客(grep、awk、sed)

    Linux三剑客 xff08 grep awk sed xff09 grep xff08 文本过滤工具 xff09 A 10显示匹配字符串后面10行内容 n显示匹配字符串在匹配文件中的行号 w整个字符串匹配 c显示匹配个数 C 10显示匹配
  • 查询Linux内核中的结构体/函数定义

    查询Linux内核中的结构体 函数定义 下载 安装Ctags 下载ctags源码https ctags sourceforge net 解压tar zxvf ctags 5 8 tar gz配置 configure编译make安装sudo
  • 新广告法违规词、敏感词在线检测工具

    新广告法的上线实行 xff0c 限制了很多的违规词 xff0c 敏感词的使用 xff0c 极限用语的处罚由原来的退一赔三变更为罚款二十万元起 如何确定广告中是否存在有敏感词呢 小龙经过多方努力 xff0c 终于开发出了新广告法违规词 敏感词
  • Linux应用学习——GDB调试

    GDB调试学习记录 常用操作 以client c为例 span class token macro property span class token directive hash span span class token directi
  • Linux学习笔记

    Linux学习笔记 Linux驱动 GPIO GIC中断 Cortex A7中断管理器GIC IIC设备框架 SPI设备框架 MISC驱动框架 Input设备框架 Platform设备框架 USB设备 Linux应用开发 Shell 快乐的
  • Cortex-A7中断控制器GIC

    Cortex A7中断控制器GIC 中断号 芯片内部的中断都会引起IRQ InterruptGIC将所有的中断源 最多1020个中断ID 分为三类 SPI SharedPeripheralInterrupt 共享中断 xff0c 外部中断都
  • Linux应用学习——多进程

    进程 当一个进程正常终止时可以通过int atexit void function void 注册进程终止处理函数 PART1 进程相关概念 进程是一个动态的过程 xff0c 而非一个静态的文件 xff0c 是程序的一次运行过程 xff0c
  • Linux应用学习——多线程

    多线程 PART1 线程相关概念 线程时参与系统调度的最小单位 被包含在进程之中 xff0c 是进程中的实际运行单位 一个进程可以创建多个线程 xff0c 多个线程实现并发运行 xff0c 每个线程执行不同的任务 线程时最基本的运行单位 x

随机推荐

  • Linux编程小工具

    编程小技巧 1 函数 结构体查询 需求背景 xff1a 安装了ctag安装使用ctag可以通过vim t 34 i2c client 34 来查询i2c client结构体的信息 不方便的地方 xff1a 需要进入指定的目录下才行 Git
  • Linux应用学习_网络开发

    Linux应用学习 网络开发 1 TCP套接字编程 1 1 套接字 1 1 1 通用套接字sockaddr span class token keyword struct span span class token class name s
  • Linux应用学习——高级I/O复用

    高级I O 阻塞I O 阻塞 xff0c 进入休眠状态 xff0c 让出CPU的使用权 xff0c 等待阻塞的条件为真普通文件一定是以非阻塞的方式进行I O操作文件默认是通过阻塞式操作的 fd span class token operat
  • 《从0到1大话操作系统》--(2)纸质内存中的数据结构

    你一定听过那句著名的等式 xff1a 程序 61 数据结构 43 算法 你可能不相信 xff0c 一个叫尼古拉斯 沃斯 xff08 Niklaus Wirth xff09 的瑞士计算机科学家 xff0c 凭这句话 xff0c 获得了图灵奖
  • 《从0到1大话操作系统》--(1)万物起源:编码

    古希腊毕达哥拉斯学派的世界观人为世界的本质是数 在计算机的世界中 xff0c 所有的一切也确实是数 万物起源 xff1a 编码 1 万物皆可编码2 ASCII编码3 互不兼容4 Unicode编码 1 万物皆可编码 曾经有一位懵懂的少年 x
  • 【安全】如何关闭Windows系统的137, 139, 445端口?

    4月14日晚 xff0c 一个叫Shadow Brokers的黑客组织泄露了一大波Windows的远程漏洞利用工具 xff0c 事件细节可以参照运维派前面的文章 Windows血崩 xff0c 一波大规模 0day 攻击泄漏 恩威科技 am
  • Linux中断、系统调用处理流程与进程切换

    1 中断与系统调用的过程 1 程序控制流 正常程序的控制流只有next xff08 执行下一条指令 xff09 和goto xff08 跳转到另一条指令执行 xff09 除了正常控制流之外 xff0c 还有异常控制流 xff0c 广义上异常
  • 开篇叙事

    开篇叙事 我为什么会在这儿我的主题我的经历 我为什么会在这儿 作为我第一次踏足CSDN xff0c 当然 xff0c 我说的是在CSDN上写博客 xff0c 我在CSDN上阅读博客已经有很长一段时间了 xff0c 这里有非常多的非常棒的博主
  • Redhat(红帽) Linux软件包管理rpm概述

    1 软件包管理的内涵 习惯了Windows上安装软件的方式 下载安装包 xff0c 双击运行 xff0c 点击几次下一步后 xff0c 软件就安装完了 我也是常年使用Windows xff0c 习惯了Windows的方式 xff0c 却从来
  • FreeRTOS(一):裸机系统与多任务系统

    裸机系统与多任务系统 3 1裸机系统3 1 1轮询系统3 1 2前后台系统 3 2多任务系统总结 3 1裸机系统 裸机 xff1a 英文名是Bare machine Bare metal xff0c 指没有配置操作系统和其他软件的电子计算机
  • FreeRTOS(二):数据结构—列表与列表项

    数据结构 列表与列表项 4 列表与列表项4 1链表4 1 1单向链表4 1 2双向链表4 1 3链表与数组的对比 4 2FreeRTOS中链表的实现4 2 1实现链表节点1 定义链表节点数据结构2 链表节点初始化 4 2 2实现链表根节点1
  • Cordova技术初次学习

    文章目录 前言一 Cordova 是什么 xff1f 二 关于Cordova环境搭建前提要求 xff1a 1 利用npm 安装2 创建应用3 添加平台4 运行 三 结语 前言 这是一篇关于Cordova入门学习的记录文章 一 Cordova
  • 修改datax,Java获取mongo,Document转换成json,遇到的类型问题,用JsonWriterSettings解决

    java numberlong 解决方法 在修改datax插件的时候遇到了问题 问题 xff1a 我们存在mongo中带有数据类型 xff0c 如图 我们直接将Document转json会带上类型 且在mongo java driver的j
  • VirtualBox 主机ping不通虚拟机的解决办法

    visualBox的主机是ping不通虚拟机的 但是虚拟机能ping通主机 要先进行以下配置 第一个网卡为NAT Network 在网络配置中 xff0c 新建一个网卡2为桥接网卡 新建共享文件夹 国外一个老哥说的 xff0c 不新建共享文
  • 基于python实现相关模板匹配跟踪之SSDA算法

    基于python实现相关模板匹配跟踪之SSDA算法 1 单张图片匹配 1 1代码 1 2 效果 2 视频跟踪 2 1代码 2 2 效果 2 3 优化思路 3 参考链接 相关模板匹配跟踪和质心跟踪都是传统算法 相较于AI算法 具有极快的处理速
  • AGV小车经典算法设计及应用

    1 AGV小车的发展背景 在现代化工业的发展中 xff0c 提倡高效 xff0c 快速 xff0c 可靠 xff0c 提倡将人从简单的工作中解放出来 机器人逐渐替代了人出现在各个工作岗位上 机器人具有可编程 可协调作业和基于传感器控制等特点
  • 扒完社交网络关系才明白,《权力的游戏》凭什么是神作

    摘要 xff1a 凡人皆有一死 没错 xff0c 但那是 凡人 会数据的 xff0c 都不是凡人 DT君当你看冰火的时候 xff0c 你在看什么 xff1f 作为一个 冰与火之歌 的资深迷弟 xff0c 看到如今的冰火电视 Valar Mo
  • 数字IC设计入门(1)初识电路板和芯片

    本文为入门级同学和零电子基础同学准备 xff0c 有一定电子基础的请直接忽略 xff0c 芯片从本质上说还是电路 xff0c 因此有必要从电路板开始了解芯片工作过程 xff0c 下面将简单介绍一块电脑主机板 电路板已在我们生活中无处不在 x
  • 数电4_4——常见组合逻辑电路(3)数据选择器

    数据选择器 1 1 工作原理1 1 1 电路图1 1 2 写出逻辑表达式 1 1 3 对应真值表 1 2 应用1 2 1 用双四选一设计八选一1 2 2 用数据选择器设计组合逻辑电路1 2 2 1 用四选一实现1 2 2 2 用八选一实现1
  • 机器学习实战之科比数据集分析(随机森林寻最优值参数)

    文章目录 总体思路分为三部1 查看数据 xff0c 对数据进行清洗 xff0c 规约1 1 查看数据1 2 数据清洗 规约1 3 删除不相关的特征1 4 数据one hot处理 2 建立模型 xff0c 挑选出最优参数2 1 准备数据集 训