Python数据分析与机器学习-Python库分析科比生涯数据
源码下载:http://download.csdn.net/download/adam_zs/10222492
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np'''科比生涯数据'''
pd.set_option('display.height', 9999)
pd.set_option('display.max_rows', 9999)
pd.set_option('display.max_columns', 9999)
pd.set_option('display.width', 9999)raw = pd.read_csv("data.csv")
# print(raw.shape) #(30697, 25)
# print(raw.head())
'''action_type combined_shot_type game_event_id game_id lat loc_x loc_y lon minutes_remaining period playoffs season seconds_remaining shot_distance shot_made_flag shot_type shot_zone_area shot_zone_basic shot_zone_range team_id team_name game_date matchup opponent shot_id
0 Jump Shot Jump Shot 10 20000012 33.9723 167 72 -118.1028 10 1 0 2000-01 27 18 NaN 2PT Field Goal Right Side(R) Mid-Range 16-24 ft. 1610612747 Los Angeles Lakers 2000-10-31 LAL @ POR POR 1
1 Jump Shot Jump Shot 12 20000012 34.0443 -157 0 -118.4268 10 1 0 2000-01 22 15 0.0 2PT Field Goal Left Side(L) Mid-Range 8-16 ft. 1610612747 Los Angeles Lakers 2000-10-31 LAL @ POR POR 2
2 Jump Shot Jump Shot 35 20000012 33.9093 -101 135 -118.3708 7 1 0 2000-01 45 16 1.0 2PT Field Goal Left Side Center(LC) Mid-Range 16-24 ft. 1610612747 Los Angeles Lakers 2000-10-31 LAL @ POR POR 3
3 Jump Shot Jump Shot 43 20000012 33.8693 138 175 -118.1318 6 1 0 2000-01 52 22 0.0 2PT Field Goal Right Side Center(RC) Mid-Range 16-24 ft. 1610612747 Los Angeles Lakers 2000-10-31 LAL @ POR POR 4
4 Driving Dunk Shot Dunk 155 20000012 34.0443 0 0 -118.2698 6 2 0 2000-01 19 0 1.0 2PT Field Goal Center(C) Restricted Area Less Than 8 ft. 1610612747 Los Angeles Lakers 2000-10-31 LAL @ POR POR 5
'''
# shot_made_flag 是否进球
kobe = raw[pd.notnull(raw["shot_made_flag"])]
# print(kobe.shape) # (25697, 25)plt.figure(figsize=(10, 10))# alpha = 0.02 # 透明度
# plt.subplot(121)
# plt.scatter(kobe["loc_x"], kobe["loc_y"], color="R", alpha=alpha) # 球场中坐标
# plt.title("loc_x and loc_y")
# plt.subplot(122)
# plt.scatter(kobe["lon"], kobe["lat"], color="B", alpha=alpha) # 经纬度
# plt.title("lon and lat")
# plt.show()# 极坐标,到圆心的距离+与X轴的夹角
# raw['dist'] = np.sqrt(raw['loc_x'] ** 2 + raw['loc_y'] ** 2)
# loc_x_zero = raw['loc_x'] == 0
# 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 赛季
# print(kobe['season'].unique())
raw['season'] = raw['season'].apply(lambda x: int(x.split("-")[1]))
# print(raw['season'].unique())
#
# print(kobe['team_id'].unique())
# print(kobe['team_name'].unique())gs = kobe.groupby("shot_zone_area")
# print(kobe["shot_zone_area"].value_counts())
# print(len(gs))# print(kobe["shot_zone_area"].unique())
'''
['Left Side(L)' 'Left Side Center(LC)' 'Right Side Center(RC)' 'Center(C)''Right Side(R)' 'Back Court(BC)']
'''
# print(kobe["shot_zone_basic"].unique())
'''
['Mid-Range' 'Restricted Area' 'In The Paint (Non-RA)' 'Above the Break 3''Right Corner 3' 'Backcourt' 'Left Corner 3']
'''
# print(kobe["shot_zone_range"].unique())
'''['8-16 ft.' '16-24 ft.' 'Less Than 8 ft.' '24+ ft.' 'Back Court Shot']'''import matplotlib.cm as cmplt.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')
#
# plt.show()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.drop(drop, axis=1, inplace=True)
# print(raw.head())
'''action_type combined_shot_type period playoffs season shot_made_flag shot_type opponent
0 Jump Shot Jump Shot 1 0 1 NaN 2PT Field Goal POR
1 Jump Shot Jump Shot 1 0 1 0.0 2PT Field Goal POR
2 Jump Shot Jump Shot 1 0 1 1.0 2PT Field Goal POR
3 Jump Shot Jump Shot 1 0 1 0.0 2PT Field Goal POR
4 Driving Dunk Shot Dunk 2 0 1 1.0 2PT Field Goal POR
'''
# print(raw['combined_shot_type'].value_counts())
# dummies_cs_type = pd.get_dummies(raw['combined_shot_type'], prefix='cs_type')
# raw = pd.concat([raw, dummies_cs_type], axis=1)
# raw = raw.drop("combined_shot_type", axis=1)
# print(raw.head())
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)], axis=1)raw = raw.drop(var, 1)
print(raw.head())train_kobe = raw[pd.notnull(raw['shot_made_flag'])]
train_label = train_kobe['shot_made_flag']
train_kobe = train_kobe.drop('shot_made_flag', axis=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
# find the best n_estimators for RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation 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(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)# 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)
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')
plt.show()model = RandomForestClassifier(n_estimators=best_n, max_depth=best_m)
model.fit(train_kobe, train_label)
Python数据分析与机器学习-Python库分析科比生涯数据相关推荐
- 视频教程-Python数据分析与案例教程:分析人口普查数据-Python
Python数据分析与案例教程:分析人口普查数据 多年互联网从业经验: 有丰富的的企业网站.手游.APP开发经验: 曾担任上海益盟软件技术股份有限公司项目经理及产品经理: 参与项目有益盟私募工厂.睿妙 ...
- Python数据分析与案例教程:分析人口普查数据-欧阳桫-专题视频课程
Python数据分析与案例教程:分析人口普查数据-379人已学习 课程介绍 本课程将带你全程实现对全国第六次人口普查数据的获取.分析.及可视化图表的制作 课程收益 熟悉和掌握使 ...
- python数据分析方向的第三方库是_python数据分析方向的第三方库是什么
python数据分析方向的第三方库是:1.Numpy:2.Pandas:3.SciPy:4.Matplotlib:5.Scikit-Learn:6.Keras:7.Gensim:8.Scrapy. 本 ...
- python数据分析的钥匙——pandas库
目录 系列文章目录 一. 关于pandas库: 二. pandas库的安装 三. pandas的两种基本数据结构--Series 与 DataFrame(附代码) 四. pandas库的应用(附代码) ...
- Python数据分析与应用----财政收入预测分析、实训(企业所得税预测)
Python数据分析与应用----财政收入预测分析.实训(企业所得税预测) 本案例按照1994年我国财政体制改革后至2013年的数据进行分析并预测未来两年财政收入变化情况.主要按照财政收入分析预测模型 ...
- python数据分析和机器学习入门,我有一些书单来推荐
想要快速入门python数据分析与机器学习,书籍是一个很好的门路,可以帮助我们系统的快速入门! 下面是一些不错的书单,分享给大家,我也在拔草中,未来会把阅读笔记分享在我的公众号:python数据分析和 ...
- 23神经网络 :唐宇迪《python数据分析与机器学习实战》学习笔记
唐宇迪<python数据分析与机器学习实战>学习笔记 23神经网络 1.初识神经网络 百度深度学习研究院的图,当数据规模较小时差异较小,但当数据规模较大时深度学习算法的效率明显增加,目前大 ...
- 2020互联网数据分析师教程视频 统计学分析与数据实战 r语言数据分析实战 python数据分析实战 excel自动化报表分析实战 excel数据分析处理实战
2020互联网数据分析师教程视频 统计学分析与数据实战 r语言数据分析实战 python数据分析实战 excel自动化报表分析实战 excel数据分析处理实战
- 视频教程-Python数据分析与爬虫-Python
Python数据分析与爬虫 10年一线开发及项目管理经验,6年以上大数据项目架构.实施.开发与运维经验,骨灰级大数据玩家,对Hadoop.Storm.Spark.Flink.Kylin.Druid等大 ...
- 视频教程-Python数据分析与挖掘-Python
Python数据分析与挖掘 浙江工商大学统计学硕士,数据分析师,曾担任唯品会大数据部担任数据分析师一职,负责支付环节的数据分析业务.曾与联想.亨氏.网鱼网咖等企业合作多个企业级项目. 刘顺祥 ¥99. ...
最新文章
- CVPR 2021 | 基于稠密场景匹配的相机定位学习
- 【深度学习】自然场景中文汉字数据集下载
- php图片长宽处理,PHP重置JPG图片尺寸的函数
- python 折线图中文乱码_彻底解决 Python画图中文乱码问题--Pyplotz组件
- 字符流的抽象类 reader writter java
- 郁闷,IT厂商认证考试没有通过!
- 【POJ2888】Magic Bracelet Burnside引理+欧拉函数+矩阵乘法
- UNIX环境高级编程之第7章:进程环境
- 科学期刊中关于计算机视觉,计算机视觉相关专业JCR1区期刊
- 数学建模|预测方法:微分方程
- 软件设计——依赖倒置
- 计算机硬盘正常的使用步骤,500g的硬盘的电脑合理分区方法
- 百度、华为、京东、B站最新面试题汇集,含泪整理面经
- Android黑科技 自动点击
- 三、kylin读写分离集群部署
- Github每日精选(第48期):SQLite下的知识库memos
- .ipynb如何转为.py
- java志愿者活动招募申请报名系统springbootboot
- Win10怎么设置默认输入法为美式英文键盘
- Linux设备与驱动学习之----什么是设备
热门文章
- 如何清空c盘只剩系统_怎么清空c盘只保留系统文件,详情介绍
- Visual Studio2019出现“ 激活远程语言服务器 c#/Visual Basic 语言服务器客户端出错”请运行devenv/log...…“的解决办法
- 网上开店,网店系统选择的那些事
- 华胜天成以精益服务为中国联通构建电子渠道容灾系统
- 游戏十五大基本游戏类型介绍
- 三边定位算法在OMNet++上的简单实现
- 红帽子linux9百度云,linux安装--红帽子Linux REDHAT 9.0 ISO(3CD)
- html右下角固定广告,jQuery右下角悬浮广告
- 电机学他励直流发电机matlab,直流发电机综合实验指导书(全文5篇)
- 问诊把脉“实景三维业务发展瓶颈在哪里”和“御医良方”