实战项目-python库分析科比生涯数据

python库分析科比生涯数据

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dC94xgQi-1644135351045)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\20实战项目\笔记图片\image-20220206160554907.png)]

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TCgg913O-1644135351046)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\20实战项目\笔记图片\image-20220206160709356.png)]

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sgIOTe3h-1644135351046)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\20实战项目\笔记图片\image-20220206160752656.png)]

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NVW2dkE5-1644135351047)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\20实战项目\笔记图片\image-20220206160930452.png)]

plt.figure(figsize=(5,5))

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6mTiW5E7-1644135351048)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\20实战项目\笔记图片\image-20220206161001016.png)]

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nBP1dzTN-1644135351049)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\20实战项目\笔记图片\image-20220206161040525.png)]

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]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KGmQqJhQ-1644135351050)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\20实战项目\笔记图片\image-20220206161118536.png)]

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 KFold

print('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])/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)


# 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])/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)

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nqenVfVG-1644135351052)(F:\Python学习\唐宇迪-python数据分析与机器学习实战\学习随笔\20实战项目\笔记图片\image-20220206161245749.png)]

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进行分析Python是一种被广泛应用于数据分析的编程语言,它可以帮助我们处理和展示科比的篮球数据。 首先,我们可以使用Python数据处理库(例如Pandas)来读取和清洗科比的比赛数据。这些数据通常是以CSV或Excel文件格式存储。我们可以使用Pandas将数据加载到数据帧(DataFrame)中,并进行一些基本的数据清洗,例如去除重复值或缺失值。 接下来,我们可以使用Python进行一些基本的数据分析,例如计算科比在不同比赛中的得分、助攻和篮板数据。我们可以使用Matplotlib这样的可视化库来绘制图表,从而更好地理解和展示这些数据。 另外,我们可以根据不同的条件进行数据筛选和分组。例如,我们可以根据不同的对手或赛季将数据分组,并计算科比在这些不同情况下的平均得分或胜率。这可以帮助我们更好地理解科比在不同场合的表现。 此外,我们还可以利用Python的统计分析库(例如SciPy或StatsModels)来进行更复杂的数据分析。这包括使用回归模型来分析科比与其他因素(例如比赛时间、得分、队友等)之间的关系。 最后,我们可以使用Python机器学习库(例如Scikit-learn)来构建预测模型,以预测科比在未来比赛中的表现。这可以通过训练监督学习模型,使用历史数据进行预测,然后根据模型的输出进行分析和讨论。 总而言之,使用Python进行科比数据生涯分析可以帮助我们更好地理解他在篮球比赛中的表现,并提供一些有趣的见解和洞察力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值