python库分析科比生涯数据

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
# import data
filename= "data.csv"
raw = pd.read_csv(filename)
print (raw.shape)
raw.head()

# 5000 for test
# 去掉缺失值
kobe =  raw[pd.notnull(raw['shot_made_flag'])]
print (kobe.shape)

(25697, 25)

#plt.subplot(211) first is raw second Column
# alpha表示点的透明程度
alpha = 0.02
# 指定画图区域
plt.figure(figsize=(10,10))# loc_x and loc_y
# 子图,12是一行两列,1是第一个位置
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')

# 极坐标计算
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())

kobe['season'].unique()

array([‘2000-01’, ‘2001-02’, ‘2002-03’, ‘2003-04’, ‘2004-05’, ‘2005-06’,
‘2006-07’, ‘2007-08’, ‘2008-09’, ‘2009-10’, ‘2010-11’, ‘2011-12’,
‘2012-13’, ‘2013-14’, ‘2014-15’, ‘2015-16’, ‘1996-97’, ‘1997-98’,
‘1998-99’, ‘1999-00’], dtype=object)

# 转换数值数据
raw['season'] = raw['season'].apply(lambda x: int(x.split('-')[1]) )
raw['season'].unique()

array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 97,
98, 99, 0], dtype=int64)

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

[1610612747]
[‘Los Angeles Lakers’]

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

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

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

Center© 11289
Right Side Center(RC) 3981
Right Side® 3859
Left Side Center(LC) 3364
Left Side(L) 3132
Back Court(BC) 72
Name: shot_zone_area, dtype: int64
6

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')

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)
print (raw['combined_shot_type'].value_counts())
pd.get_dummies(raw['combined_shot_type'], prefix='combined_shot_type')[0:2]

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)
# 指定训练集和测试集
train_kobe = raw[pd.notnull(raw['shot_made_flag'])]train_label = train_kobe['shot_made_flag']
train_kobe = train_kobe.drop('shot_made_flag', 1)test_kobe = raw[pd.isnull(raw['shot_made_flag'])]
test_kobe = test_kobe.drop('shot_made_flag', 1)
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

array([ 1, 3, 10, 31, 100])

# 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 = []
range_n = np.logspace(0,2,num=3).astype(int)
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(10, shuffle=True).split(train_kobe):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)# 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(10, shuffle=True).split(train_kobe):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)

Finding best n_estimators for RandomForestClassifier…
the number of trees : 1
Done processing 1 trees (0.973sec)
the number of trees : 10
Done processing 10 trees (5.755sec)
the number of trees : 100
Done processing 100 trees (51.947sec)
100 11.914000011353393
Finding best max_depth for RandomForestClassifier…
the max depth : 1
Done processing 1 trees (4.065sec)
the max depth : 10
Done processing 10 trees (16.296sec)
the max depth : 100
Done processing 100 trees (49.635sec)
10 11.040351953558947

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')

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

报错问题解决

for train_k, test_k in KFold(len(train_kobe), n_folds=10, shuffle=True):会报很多错
需要改为for train_k, test_k in KFold(10, shuffle=True).split(train_kobe):

实战项目-python库分析科比生涯数据相关推荐

  1. Hadoop实战系列之MapReduce 分析 Youtube视频数据

    Hadoop实战系列之MapReduce 分析 Youtube视频数据 一.实战介绍 MapReduce 是 Hadoop 的计算框架. 在运行一个 MR 程序时,任务过程被分为两个阶段:Map 阶段 ...

  2. python 播放本地音乐_实战项目—python实现本地音乐播放器

    随着网络的发展,我们已经很少将音乐下载到本地,而是直接在线听歌,方便而又直接.也许你用的音乐播放器是这个 也许是这个 这都不是重点,今天我们要用python自己打造一款音乐播放器. 具体思路 使用py ...

  3. 利用python简单分析抓包数据

    利用python简单分析抓包数据 wireshark的数据 先读一行看看长啥样 import json data_file = r'E:\download\data.json' with open(d ...

  4. 数据分析实战项目-用户行为分析(Python)

    数据分析步骤1:明确项目背景和需求 提出问题和应用模型 1.本次分析的目的是为了通过对某电商用户的行为进行分析,从而找到提升GMV方法. 思路:项目GMV的拆解公式为:GMV=UV(独立访客数)* 用 ...

  5. 实战项目 78 : 从 Web API 获取数据

    这篇文章分享我的 Android 开发(入门)课程 的第七个和第八个实战项目:书籍列表应用和新闻应用.这两个项目都托管在我的 GitHub 上,分别是 BookListing 和 NewsApp 这两 ...

  6. 新手python的100个实战项目,python练手经典100例项目

    Python 的练手项目有哪些值得推荐? 基础和爬虫.Python由荷兰数学和计算机科学研究学会的Guido van Rossum于1990 年代初设计,作为一门叫做ABC语言的替代品. Python ...

  7. 人工智能实战项目(python)+多领域实战练手项目

    人工智能实战项目 大家好,我是微学AI,本项目将围绕人工智能实战项目进行展开,紧密贴近生活,实战项目设计多个领域包括:金融.教育.医疗.地理.生物.人文.自然语言处理等:帮助各位读者结合机器学习与深度 ...

  8. 运用最小二乘法和sklearn库分析身高体重数据

    文章目录 一.使用Excel分析身高体重 二.用Jupyter Notebook编程使用最小二乘法分析身高体重 三.运用Sklearn库,导入数据模拟. 四.参考 一.使用Excel分析身高体重 (这 ...

  9. 大数据实战项目--中国移动运行分析

    1.项目背景 中国移动公司旗下拥有很多的子机构,基本可以按照省份划分. 而各省份旗下的充值机构也非常的多. 目前要想获取整个平台的充值情况,需要先以省为单元,进行省份旗下的机构统计,然后由下往上一层一 ...

  10. 大数据实战项目------中国移动运营分析实时监控平台 || 项目需求实现(文章最后有数据文件)

    1.业务概况(显示总订单量.订单成功量.总金额.花费时间) 2.业务详细概述(每小时的充值订单量.每小时的充值成功订单量) 3.业务质量(每个省份的充值成功订单量) 4.实时统计每分钟的充值金额和订单 ...

最新文章

  1. NeurIPS提前看 | 四篇论文,一窥元学习的最新研究进展
  2. java 处理 url_Java URL处理 - Java 教程 - 自强学堂
  3. Zend Framework 自动加载类的实现方法
  4. distance from ifm to Sidney Sussex College: acceptable
  5. boost::math::skew_normal用法的测试程序
  6. 关于 SAP 电商云 Spartacus UI 修改 div 层级结果是否算是 breaking change 的问题
  7. 动态规划训练12 [G - You Are the One HDU - 4283 ]
  8. 【CSS】常用特效字
  9. 欧科云链OKLink:以太坊网络难度达到5.74P的历史新高
  10. 如何下载HLS视频到本地(m3u8)
  11. Android改变图片颜色的自定义控件
  12. java中堆 栈的英文_Java中的栈和堆
  13. Jenkins持续集成环境, 如何自定义 maven 仓库
  14. 基于基因数据的神经网络模式分类研究
  15. 金蝶KIS15.1专业版注册流程和企业认证流程
  16. weka下载安装以及源码运行
  17. mysql rds 是什么_mysql.rds.aliyuncs.com
  18. 【信息学奥赛】1005:地球人口承载力估计(C++)
  19. C++实验5 游戏玩家类Player、两个道具类Helm和Armor
  20. 曾推出Anki Drive和Cozmo人工智能机器人的独角兽企业Anki谢幕

热门文章

  1. 基于Python+Opencv实现改变logo颜色
  2. 在计算机中怎么找到打字的文件,想在电脑上打字,然后把电脑上写的字,弄到纸上怎么做...
  3. 华为mate7 刷机出现android,华为Mate7怎么刷机 华为Mate7刷机教程【步骤详解】
  4. c语言网络病毒代码大全,C语言病毒 - 各类源码 - 中国红客联盟 - Powered by HUC
  5. 弹性波波长计算公式_固体中的弹性波
  6. 网页右下角弹出窗体实现代码
  7. 儿童车内滞留监测控制系统的设计
  8. matlab中平稳性检验,基于Matlab的信号平稳性检验系统
  9. 客户关系管理(CRM)基础篇
  10. JavaWeb——JavaScript精讲之DOM、BOM对象与案例实战(动态添加删除表格)