python 预测足球_利用 Python 预测英雄联盟胜负,分析了 5 万多场比赛才得出的数据!...
今天教大家用Python預測英雄聯盟比賽勝負。
Show me data,用數據說話
今天我們聊一聊 Python預測LOL勝負
目前,英雄聯盟S10全球總決賽正在火熱進行中,最終決賽于10月31日在浦東足球場舉行。作為當下最火熱的電競賽事,這點燃了全球無數玩家的關注,相信沒有哪個英雄聯盟玩家會錯過這場受眾超廣、影響力超大的國際電競賽事。LPL究竟能否在家門口拿下第三座世界賽獎杯也成了許多玩家關注的話題。
對于每場比賽,大家最關注的莫過于最后的勝負了,那么比賽的勝負能否可以預測呢?
今天,我們就分析了5萬多場英雄聯盟的排名比賽,教你如何用Python預測比賽勝負。
項目介紹
英雄聯盟(LOL)是美國游戲開發商Riot Games(2011年由騰訊收購)開發和發行的一款多人在線戰斗競技游戲。
在游戲中,玩家扮演一個"召喚師"角色,每個召喚師控制一個擁有獨特技能的"英雄",并與一組其他玩家或電腦控制的英雄戰斗。游戲的目標是摧毀對方的防御塔和基地。
召喚者峽谷是英雄聯盟中最受歡迎的地圖,在這種地圖類型中,兩隊五名玩家競爭摧毀一個被稱為基地的敵人建筑,這個建筑由敵人的隊伍和一些防御塔護衛。每個隊伍都希望保衛自己的建筑,同時摧毀對方的建筑。這些主要包括:Towers(防御塔):每支隊伍總共有11座防御塔
Inhibitor(水晶):每條道有一個水晶
Elemental Drakes/Elder Dragon(大龍/遠古龍)
Rift Herald(峽谷先鋒)
Baron Nasho(納什男爵)
Nexus(基地)
英雄聯盟最具爭議的元素之一,就是其嚴重的滾雪球效應。許多職業選手接受賽后采訪時都提到其輸贏都因為“滾雪球”,我們研究各方面各指標的數據,來看這些因素的發展是否真的影響了比賽的成敗。
在這個項目中,我們分析了5萬多場英雄聯盟的排名比賽,并嘗試使用決策樹算法來根據已有輸入屬性預測比賽勝負。
數據集概述
數據集收集了超過50000個從游戲英雄聯盟排位游戲的數據,字段主要包含以下數據:Game ID:游戲ID
Creation Time:創建時間
Game Duration (in seconds):游戲持續時間(秒)
Season ID:賽季ID
Winner (1=team1, 2=team2):獲勝隊伍
First Baron, dragon, tower, blood, inhibitor and Rift Herald (1 = team1, 2 = team2, 0 = none):第一條納什男爵,大龍,塔,一血,水晶,峽谷先鋒
Champions and summoner spells for each team (Stored as Riot's champion and summoner spell IDs):每只隊伍選擇的英雄和召喚術
The number of tower, inhibitor, Baron, dragon and Rift Herald kills each team has:塔,水晶,男爵,大龍和峽谷先鋒擊殺數
The 5 bans of each team (Again, champion IDs are used):每個隊伍的禁用英雄
數據讀入和預覽
首先導入所需包和讀入數據集。
# 數據整理import numpy as np import pandas as pd # 可視化import matplotlib.pyplot as plt import seaborn as sns import plotly as py import plotly.graph_objs as go # 建模from sklearn.tree import DecisionTreeClassifierfrom sklearn.model_selection import train_test_split, GridSearchCVfrom sklearn.metrics import confusion_matrix, classification_report
# 讀入數據df = pd.read_csv('./archive/games.csv')df.head()
ape(51490, 61)
數據可視化
我們將分別對影響比賽的相關因素進行如下探索:
1. 目標變量分布
數據集一共有51490條記錄,其中1隊獲勝的次數為26077次,占比50.6%,2隊獲勝的次數為25413次,占比49.4%。不存在樣本不平衡的情況。
代碼
# 餅圖trace0 = go.Pie(labels=df['winner'].value_counts().index, ? ? ? ? ? ? ? ? values=df['winner'].value_counts().values, ? ? ? ? ? ? ? ?hole=0.5, ? ? ? ? ? ? ? ?opacity=0.9, ? ? ? ? ? ? ? ?marker=dict(line=dict(color='white', width=1.3)) ? ? ? ? ? ? ? ) layout = go.Layout(title='目標變量winner分布')
data = [trace0]fig = go.Figure(data, layout)py.offline.plot(fig, filename='./html/整體獲勝情況分布.html')
2. 游戲時長分布
從直方圖可以看出,游戲時長大致服從正態分布,其中最短的游戲時長為3分鐘,3分鐘是游戲重開的時間點,最長的游戲時長是79分鐘。中間50%的時長在26~36分鐘之間。
代碼
df['game_duration'] = round(df['gameDuration'] / 60)
# 選擇數據x1 = df[df['winner'] == 1]['game_duration']x2 = df[df['winner'] == 2]['game_duration']
# 直方圖trace0 = go.Histogram(x=x1, bingroup=25, name='team1', opacity=0.9)trace1 = go.Histogram(x=x2, bingroup=25, name='team2', opacity=0.9)
layout = go.Layout(title='比賽游戲時長分布')
data = [trace0, trace1] fig = go.Figure(data, layout)py.offline.plot(fig, filename='./html/游戲時長分布.html')
3. 一血對獲勝的影響
獲得一血的隊伍勝率相對較高,在第一隊的比賽中,首先獲得一血時的勝率為59.48%,相較未獲得一血的比賽高18%。在第二隊的比賽中,獲得一血時的勝率為58.72%,相較未獲得一血的比賽高18%。
代碼
plot_bar_horizontal(input_col='firstBlood',?target_col='winner',?title_name='一血對獲勝的影響')
4. 一塔對獲勝的影響
從數據來看,第一個防御塔看起來是比較有說服力的指標。在第一隊的比賽中,首先摧毀一塔時隊伍的勝率高達70.84%,相較未獲得一塔的比賽高41.64%。在第二隊的比賽中,有相近的數據表現。
代碼
plot_bar_horizontal(input_col='firstTower', target_col='winner', title_name='一塔對獲勝的影響')
5. 摧毀第一個水晶對獲勝的影響
在比賽中拿到第一座水晶塔的隊伍91%的情況下可以獲勝,這一點在某種程度上是可以預見的,因為首先摧毀水晶塔代表隊伍已經積累的足夠的優勢,而且水晶塔力量很強大,并且更具有價值。
代碼
plot_bar_horizontal(input_col='firstInhibitor',?target_col='winner',?title_name='摧毀第一個水晶對獲勝的影響')
6. 擊殺第一條男爵對獲勝影響
統計數據顯示,在比賽中擊殺第一條男爵有80%的勝率。
plot_bar_horizontal(input_col='firstBaron', target_col='winner', title_name='擊殺第一條男爵對獲勝影響')
7. 擊殺第一條大龍對獲勝的影響
在第一個隊伍中,首先擊殺第一條大龍的隊伍勝率在68.6%,相較未取得優先的比賽勝率高36%。
plot_bar_horizontal(input_col='firstDragon',?target_col='winner',?title_name='擊殺第一條大龍對獲勝的影響')
8. 擊殺第一條峽谷先鋒對獲勝的影響
在第一個隊伍中,首先擊殺第一條峽谷先鋒的隊伍勝率在69.45%,相較未取得優先的比賽勝率高38.92%。
plot_bar_horizontal(input_col='firstRiftHerald', target_col='winner', ? ? ? ? ? ? ? ? ? ? title_name='擊殺第一條峽谷先鋒對獲勝的影響')
9. 摧毀防御塔數對獲勝影響
選擇第一個隊伍的摧毀防御塔數作為影響因素,可以看出,摧毀的防御塔數量越多,獲勝的概率越大。當數量大于8個時,勝率大于85%。11個防御塔全部摧毀時的勝率為99.16%,當然也有8.4‰的翻盤概率。
plot_bar_vertical(input_col='t1_towerKills', target_col='winner', title_name='摧毀防御塔數對獲勝影響')
10. 摧毀水晶數對獲勝影響
摧毀水晶的數目越多,獲勝的概率越大。沒有摧毀水晶的獲勝概率為12.55%,摧毀一個的獲勝概率為81.11%,兩個為92.38%。
plot_bar_vertical(input_col='t1_inhibitorKills', target_col='winner', title_name='摧毀水晶數對獲勝影響')
11. 擊殺男爵數對獲勝影響
擊殺男爵數越多,獲勝的概率越大,擊殺5條男爵的數據僅有一條,后續需要刪除。
plot_bar_vertical(input_col='t1_baronKills', target_col='winner', title_name='擊殺男爵數對獲勝影響')
12. 擊殺大龍數對獲勝影響
擊殺大龍數數越多,獲勝的概率越大
plot_bar_vertical(input_col='t1_dragonKills', target_col='winner', title_name='擊殺大龍數對獲勝影響')
數據建模
首先進行初步的清洗,并篩選建模所需變量。
# 刪除時間少于15分鐘和分類數較少的記錄df = df[(df['gameDuration'] >= 900) & (df['t1_baronKills'] != 5)]print(df.shape)
(50180,?62)# 篩選建模變量df_model = df[['winner', 'firstBlood', 'firstTower', 'firstInhibitor', 'firstBaron', ? ? ? ? ? ? ?'firstDragon', 'firstRiftHerald', 't1_towerKills', 't1_inhibitorKills','t1_baronKills', ? ? ? ? ? ? ?'t1_dragonKills', 't2_towerKills', 't2_inhibitorKills', 't2_baronKills', 't2_dragonKills' ? ? ? ? ? ? ?]] df_model.head()
然后劃分訓練集和測試集,采用分層抽樣方法劃分80%數據為訓練集,20%數據為測試集。
# 劃分訓練集和測試集x = df_model.drop('winner', axis=1)y = df_model['winner']
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, stratify=y, random_state=0)print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
(40144, 14) (10036, 14) (40144,) (10036,)
使用決策樹算法建模,使用GridSearchCV進行參數調優。
# 參數parameters = { ? ?'splitter': ('best', 'random'), ? ?'criterion':('gini', 'entropy'), ? ?'max_depth':[*range(1, 20, 2)],}
# 建立模型clf = DecisionTreeClassifier(random_state=0)GS = GridSearchCV(clf, parameters, cv=10)GS.fit(X_train, y_train)GridSearchCV(cv=10, estimator=DecisionTreeClassifier(random_state=0), ? ? ? ? ? ? param_grid={'criterion': ('gini', 'entropy'), ? ? ? ? ? ? ? ? ? ? ? ? 'max_depth': [1, 3, 5, 7, 9, 11, 13, 15, 17, 19], ? ? ? ? ? ? ? ? ? ? ? ? 'splitter': ('best', 'random')})# 輸出最佳得分 print("best score: ", GS.best_score_)print("best param: ", GS.best_params_)best?score:??0.9770077890521407best?param:??{'criterion':?'gini',?'max_depth':?7,?'splitter':?'best'}#?最佳模型best_clf?=?DecisionTreeClassifier(criterion="gini",?max_depth=7,?splitter="best")best_clf.fit(X_train,y_train)?print("score:",?best_clf.score(X_test,y_test))???score: 0.9799721004384216
使用最優的模型重新評估測試數據集效果:
# 輸出分類報告y_pred = best_clf.predict(X_test) cm = confusion_matrix(y_test, y_pred)cr = classification_report(y_test, y_pred)print('Classification?report?:?\n',?cr)
Classification report : ? ? ? ? ? ? ? ?precision ? ?recall ?f1-score ? support
1 ? ? ? 0.98 ? ? ?0.98 ? ? ?0.98 ? ? ?5077 ? ? ? ? ? 2 ? ? ? 0.98 ? ? ?0.98 ? ? ?0.98 ? ? ?4959
accuracy ? ? ? ? ? ? ? ? ? ? ? ? ? 0.98 ? ? 10036 ? macro avg ? ? ? 0.98 ? ? ?0.98 ? ? ?0.98 ? ? 10036weighted?avg???????0.98??????0.98??????0.98?????10036
# 熱力圖g1 = sns.heatmap(cm, annot=True, fmt=".1f", cmap="flag", linewidths=0.2, cbar=False)g1.set_ylabel('y_true', fontdict={'fontsize': 15})g1.set_xlabel('y_pred', fontdict={'fontsize': 15}) ?g1.set_title('confusion_matrix',?fontdict={'fontsize':?15})Text(0.5, 1, 'confusion_matrix')
# 輸出屬性重要性imp = pd.DataFrame(list(zip(X_train.columns, best_clf.feature_importances_))) imp.columns = ['columns', 'importances']imp = imp.sort_values('importances', ascending=False)imp
在屬性的重要性排序中,擊殺防御塔數量的重要性最高,其次是水晶摧毀數量、一塔、擊殺龍的數量。
以下代碼用于輸出這顆樹:
# 可視化import graphvizfrom sklearn import tree
dot_data = tree.export_graphviz(decision_tree=best_clf, max_depth=3, ? out_file=None, ? feature_names=X_train.columns, ?class_names=['1', '2'], ? filled=True, ?rounded=True ?)graph = graphviz.Source(dot_data)graph
模型預測
我們假設:
第一隊拿了第一血,第一塔,第一男爵,第一條大龍和第一峽谷先鋒,而第二隊只拿了第一個水晶。
第一隊的塔,水晶,男爵和龍殺死的數量分別是10,2,1,4和塔,水晶,男爵和龍的數量分別是7,2,1,1。
# 新數據new_data = [[1, 1, 2, 1, 1, 1, 10, 2, 1, 4, 7, 2, 1, 1]]c = best_clf.predict_proba(new_data).reshape(-1, 1) print("winner is :" , best_clf.predict(x1)) print("First team win probability is % ", list(c[0] * 100), ? ? ?"\nSecond team win probability is %:",list(c[1] * 100))
winner is : [1]First team win probability is % ?[89.87341772151899] Second team win probability is %: [10.126582278481013]
根據模型預測結果,第一隊將會獲勝,獲勝的概率為89.87%。
喜歡的記得三連哦,需要學習資料的可以私信UP主領取
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的python 预测足球_利用 Python 预测英雄联盟胜负,分析了 5 万多场比赛才得出的数据!...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在校期间如何确保部队安全
- 下一篇: 关键词提取_NLP 关键词 提取 实战