Python | 英雄联盟游戏数据分析

人工智能25

一、项目背景

EDG夺得2021英雄联盟全球总决赛冠军,这场比赛让所有观赛者热血沸腾,也唤起了我这个沉睡多年老玩家对MOBA游戏的兴趣,兴冲冲地下载了英雄联盟,却发现这并不是一个可以轻松上手的游戏。
对于时下最流行的MOBA类游戏——英雄联盟,作为一个新手可以从哪些方面切入,通过数据分析了解游戏机制并快速上手,降低新人过渡期的难度,是该项目的中心主题。

二、数据预处理

1.数据来源

数据源:League of Legends Ranked Matches

2.理解数据

数据集包含英雄联盟的18万场对局数据,数据表包括:
champs.csv :包含英雄名称和英雄id
matches.csv : 包含比赛信息
participants : 每场比赛的玩家信息
stats1.csv & stats2.csv : 对战数据
teambans : 队伍ban选数据
teamstats : 队伍总数据

3.数据清洗

1.导入数据
导入所有数据表

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

champs=pd.read_csv("champs.csv")
matches=pd.read_csv("matches.csv")
participants=pd.read_csv("participants.csv")
stats1=pd.read_csv("stats1.csv")
stats2=pd.read_csv("stats2.csv")
teambans=pd.read_csv("teambans.csv")
teamstats=pd.read_csv("teamstats.csv")

展示champs表:

champs.head()

Python | 英雄联盟游戏数据分析
展示matches表:

matches.head()

Python | 英雄联盟游戏数据分析
展示participants表:

participants.head()

Python | 英雄联盟游戏数据分析
展示stats1& stats2表,由于列数过多,仅能展示部分:

stats1_shape = stats1.shape
print(stats1_shape)

Python | 英雄联盟游戏数据分析
展示teambans表:

teambans.head()

Python | 英雄联盟游戏数据分析
展示teamstats表:

teamstats.head()

Python | 英雄联盟游戏数据分析

2.查找缺失值
计算各表缺失值总和,若缺失值过多再逐列处理

champs_null = sum(champs.isnull().sum())
print(champs_null)

各表缺失值均为0,说明数据集完整

3.合并数据表

stats = stats1.append(stats2)
df = pd.merge(participants, stats, how= 'left', on= ['id'])
df = pd.merge(df, champs, how= 'left', left_on= 'championid', right_on= 'id')
df = pd.merge(df, matches, how= 'left', left_on= 'matchid', right_on= 'id')
df.columns

4.添加必要字段

df['teamid']= df['player'].apply(lambda x: '1' if x<5 else '2')

def final_position(row):
    if row['role'] in ('DUO_SUPPORT','DUO_CARRY'):
        return row['role']
    else:
        return row['position']
df['adjposition']= df.apply(final_position, axis= 1)

df['team_role']= df['teamid']+ '-'+ df['adjposition']

三、探索性分析

1.英雄获胜率、KDA
英雄联盟中的英雄众多,新手往往会不知道该怎么选择英雄练手,因此分析哪些英雄更容易取胜,能得到更高得KDA((K击杀数+A助攻数)/ D死亡数),为新手选择英雄提供参考。

champs_stats= df.groupby('name').agg({'win':'sum', 'name':'count', 'kills':'mean', 'deaths':'mean', 'assists':'mean'})
champs_stats.columns= ['win', 'total matches', 'K', 'D', 'A']
champs_stats['win rate(%)']= champs_stats['win'] / champs_stats['total matches'] * 100
champs_stats['win rate-50%']= champs_stats['win rate(%)'] - 50
champs_stats['KDA']= (champs_stats['K'] + champs_stats['A']) / champs_stats['D']
champs_stats['KDA-mean']= champs_stats['KDA'] - champs_stats.KDA.mean()
champs_stats= champs_stats.round(2)
champs_stats.reset_index(inplace=True)
champs_stats= champs_stats.sort_values('win rate(%)',ascending= False)

champs_stats.head(10).style.set_precision(2)

获胜率排名前10的英雄:
Python | 英雄联盟游戏数据分析
获胜率倒数的10名英雄:
Python | 英雄联盟游戏数据分析
最高获胜率为55.87%,最低获胜率为39.65%,差值并不算大,为了突出英雄之间获胜率的差异,以50%为基准值,观察所有英雄的获胜率情况:

f,ax= plt.subplots(figsize=(10,25))
sns.barplot(x='win rate-50%',y='name',data= champs_stats.sort_values(by='win rate(%)',ascending=False))
plt.title('Win Rate Based on 50%')
plt.show()

Python | 英雄联盟游戏数据分析
以KDA平均值为基准值,观察所有英雄的KDA情况:

f,ax= plt.subplots(figsize=(10,25))
sns.barplot(x='KDA-mean',y='name',data= champs_stats.sort_values(by='KDA',ascending=False))
plt.title('KDA Based on mean')
plt.show()

Python | 英雄联盟游戏数据分析
可以看到获胜率在50%以上和50%以下的英雄数量分布相对平衡。获胜率排名前10的英雄里超过一半是法师角色。
KDA最高值是3.81,最低值1.68。KDA排名前10的英雄里以战士/坦克、法师为主,而法师排在头部,考虑到法师在队伍中通常担任辅助角色,能拿到更多助攻;战士/坦克的生存能力、输出能力一般情况下都更强,击杀或助攻数值会比较高。
翠神这个英雄的获胜率和KDA都是所有英雄里最高的,该英雄的官方定位是打野、辅助。

2.英雄出场率
英雄胜率高并不意味着英雄对新手友好,这类英雄可能对玩家的游戏技能和熟练程度有很高的要求,所以就转向英雄出现率的分析,看看哪些英雄是玩家在游戏中最常使用的。

[En]

The high winning rate of the hero does not mean that the hero is friendly to the novice, this kind of hero may have high requirements for the player's game skills and proficiency, so turn to the analysis of hero appearance rate to see which heroes are most commonly used by players in the game.

f,ax= plt.subplots(figsize=(18,11))
pick_rate= df['name'].value_counts().sort_values(ascending= False)
ax= pd.concat((pick_rate.head(10),pick_rate.tail(10))).plot(kind= 'bar')
total_records= len(matches)
for x in ax.patches:
    height= x.get_height()
    ax.text(x.get_x() + x.get_width()/2.,
           height,
           '{:.2f}%'.format(height/total_records*100),
           ha= 'center')

plt.xticks(rotation= 45)
plt.yticks([1500,5000,10000,20000,30000,40000,50000,60000])
plt.title('Top 10 and Last 10 Pick Rate')
plt.show()

Python | 英雄联盟游戏数据分析
可以看到最热门的英雄分别是盲僧、皮城女警、圣枪游侠、魂锁典狱长、九尾妖狐、暗夜猎手、疾风剑豪、发条魔灵、逆羽、探险家,其中只有九尾妖狐在获胜率TOP10里。
出场率最低的10名英雄中,水晶先锋斯卡纳位列获胜率TOP10,可以看出斯卡纳不是绝大多数玩家的选择,但如果能驾驭好这个英雄,可以给团队带来巨大优势。

3.英雄出场次数与获胜率
基于英雄的出场次数和获胜率制作散点图。

def lable_point(x, y, val, ax):
    a= pd.concat({'x':x, 'y':y, 'val':val}, axis= 1)
    for i, point in a.iterrows():
        ax.text(point['x'],point['y'],str(point['val']))

champs_stats['color']= champs_stats['win rate(%)'].apply(lambda x: 'red' if x>50 else 'green')

ax= champs_stats.plot(kind= 'scatter', x= 'total matches', y= 'win rate(%)',
                      color= champs_stats['color'].tolist(),
                     figsize= (18,11),
                     title='Win Rate vs Pick')

lable_point(champs_stats['total matches'], champs_stats['win rate(%)'], champs_stats['name'], ax)

Python | 英雄联盟游戏数据分析
显然,盲僧虽然人气很高,但中签率并不高。相反,崔深胜率最高,但不是当红英雄。

[En]

It is obvious that although the blind monk is very popular, the winning rate is not high. On the contrary, Cui Shen has the highest winning rate but is not a popular hero.

新手玩家可以选择阿里、嘎纳、亚索等胜率极高的当红英雄进行练习。这类英雄更容易使用,可以增强新手玩家的体验感。

[En]

Novice players can choose popular heroes with excellent winning rates for practice, such as Ali, Gana, Yasso and so on. This kind of heroes are easier to use and can enhance the sense of experience of novice players.

4.取胜相关因素分析
分析获胜与击杀数(kills)、死亡数(deaths)、助攻数(assists)、推塔数(turretkills)、总治疗数(totheal)、补刀数(totminionskilled)、花费金币总数(goldspent)、总承伤(totdmgtaken)、推水晶数(inhibkills)、插眼数(wardsplaced)、游戏时长(duration)等因素间存在怎样的相关性。

df= df[['id', 'matchid', 'player', 'name', 'adjposition', 'team_role',
         'win', 'kills', 'deaths', 'assists', 'turretkills','totdmgtochamp',
         'totheal', 'totminionskilled', 'goldspent', 'totdmgtaken', 'inhibkills',
         'pinksbought', 'wardsplaced', 'duration', 'platformid',
         'seasonid']]

df_fac= df._get_numeric_data()
df_fac= df_fac.drop(['id','matchid','player','seasonid'],axis= 1)

mask= np.zeros_like(df_fac.corr(), dtype= np.bool)
mask[np.triu_indices_from(mask)]= True

plt.figure(figsize=(18,11))
sns.heatmap(df_fac.corr(), cmap= 'coolwarm', annot= True, fmt= '.2f', linewidths= .5, mask= mask)

plt.title('Win Factors')

Python | 英雄联盟游戏数据分析
如你所见,塔楼和水晶的数量是获胜的关键因素。毕竟,这场比赛是一场旨在摧毁对方水晶中枢的塔式推送游戏;助攻和安打的多少也与比赛的输赢息息相关;此外,金币消费总量也是一项重要指标,经济越好,球队的战斗力越高,在打法上就越有优势。

[En]

As you can see, the number of towers and crystals are the key factors to win. After all, this game is a tower push game aimed at destroying each other's crystal hub; the number of assists and hits are also closely related to the winning or losing of the game; in addition, the total number of gold coins spent is also an important indicator, the better the economy, the higher the combat effectiveness of the team, and the more advantageous it will be in the play.

四、分析总结

未完待续......

Original: https://blog.csdn.net/PbPbbb/article/details/121310947
Author: PbPbbb
Title: Python | 英雄联盟游戏数据分析



相关阅读

Title: ImportError: cannot import name LayerNormalization from tensorflow.python.keras.layers.normalization

问题:

导入库时出现错误:ImportError: cannot import name 'LayerNormalization' from 'tensorflow.python.keras.layers.normalization'

在自己笔记本上的深度学习环境中运行CycleGAN网络没有错误,但是显存不够,环境:

Python3.8

Tensorflow2.6.0

keras2.6.0

转到工作站运行,工作站当时下载了深度学习环境是:

Python3.8

Tensorflow2.3.0

keras2.4.3

问题描述:

在keras第一次导入时出现错误

Using TensorFlow backend.

2021-05-15 20:43:16.281415: I tensorflow/stream_executor/platform/default/dso_loader.cc:53] Successfully opened dynamic library cudart64_110.dll
Traceback (most recent call last):
  File "E:/FACULTATE ANUL 3 SEMESTRUL 2/Procesarea Imaginilor/proiect/main.py", line 8, in <module>
    from keras.layers import Conv2D,Dropout, Flatten, Dense,MaxPooling2D, MaxPool2D
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\__init__.py", line 3, in <module>
    from . import utils
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\utils\__init__.py", line 6, in <module>
    from . import conv_utils
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\utils\conv_utils.py", line 9, in <module>
    from .. import backend as K
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\backend\__init__.py", line 1, in <module>
    from .load_backend import epsilon
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\backend\load_backend.py", line 90, in <module>
    from .tensorflow_backend import *
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\backend\tensorflow_backend.py", line 5, in <module>
    import tensorflow as tf
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\__init__.py", line 41, in <module>
    from tensorflow.python.tools import module_util as _module_util
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\__init__.py", line 48, in <module>
    from tensorflow.python import keras
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\__init__.py", line 25, in <module>
    from tensorflow.python.keras import models
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\models.py", line 20, in <module>
    from tensorflow.python.keras import metrics as metrics_module
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\metrics.py", line 37, in <module>
    from tensorflow.python.keras import activations
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\activations.py", line 18, in <module>
    from tensorflow.python.keras.layers import advanced_activations
  File "C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\layers\__init__.py", line 146, in <module>
    from tensorflow.python.keras.layers.normalization import LayerNormalization
ImportError: cannot import name 'LayerNormalization' from 'tensorflow.python.keras.layers.normalization' (C:\Users\My-Pc\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\layers\normalization\__init__.py)</module></module></module></module></module></module></module></module></module></module></module></module></module></module>

解决办法:参考以下网站:https://stackoverflow.com/questions/67549661/importerror-cannot-import-name-layernormalization-from-tensorflow-python-ker/67667525

错误原因:

以上链接中表明可能是Python/Tensorflow/keras的版本不匹配导致的

解决:

将工作站的三者的版本改为自己电脑的版本就可以了。

Python | 英雄联盟游戏数据分析

Python | 英雄联盟游戏数据分析

Python | 英雄联盟游戏数据分析

所以最后工作站的环境配成了:

CUDA11.2

cuDNN8.2.0

Tensorflow2.6.0 Tensorflow-gpu2.6.0

python3.8.0

keras2.6.0

部分Python/Tensorflow/Keras的版本对应关系

但是更新一点的Tensorflow和keras的对应关系还没有找到。

Original: https://blog.csdn.net/qq_43608192/article/details/122252588
Author: 张小懒君
Title: ImportError: cannot import name LayerNormalization from tensorflow.python.keras.layers.normalization

相关文章
YOLOv3学习——锚框和候选区域 人工智能

YOLOv3学习——锚框和候选区域

R-CNN系列算法需要先产生候选区域,再对候选区域做分类和位置坐标的预测,这类算法被称为两阶段目标检测算法。近几年,很多研究人员相继提出一系列单阶段的检测算法,只需要一个网络即可同时产生候选区域并预测...
Anaconda的使用 人工智能

Anaconda的使用

一、介绍 conda 是开源包(packages)和虚拟环境(environment)的管理系统。 packages 管理: 可以使用 conda 来安装、更新 、卸载工具包 ,并且它更关注于数据科学...
数据挖掘复习要点整理 人工智能

数据挖掘复习要点整理

复习要点: 回归课本 个人总结仅供参考 简答题: * 1. Apriori算法主要步骤: 2.数据挖掘流程 3.数据预处理 4.信息熵 5.K-Means 聚类算法 - 基本思想: 工作步骤: 计算题...
语音模块:pyttsx变声项目 人工智能

语音模块:pyttsx变声项目

一、说明 二、安装 三、基本用法 四、结论 程序员们好,我们将在本教程中看到如何使用 Python 中的 pyttsx3 将语音转换为文本。也可以将人的语音实现变音、变速等处理。 pyttsx3 库是...