Use Python to analyze the data of 1982 games of League of Legends, and predict the outcome of the game before the start!

Nowadays, as long as you enter an Internet cafe casually, you will find that the most people play “League of Legends”. It can be said that “League of Legends” is already a well-deserved leader in end games. With such a base of players, “League of Legends” is not just an e-sports game, it also brings us countless joys.

Ask how much you can worry about, and assist you to grab the head with a flash; Asking how much you can worry about, the prince opens the gate to his teammates; it rains a lot during the Ching Ming Festival, and all kinds of teammates have various pitfalls. Others laugh at me for not buying eyes, and I laugh at others for wasting money; the lonely sail is far away, the blue sky is gone, and the grass is startled and it is easy to believe. When we met, it was hard to say goodbye, but when I met Zhao Xin with a broken chrysanthemum, I smiled to the sky with my sword, and I only need to use three swords to chop someone up. Train the blind monk hard thousands of times, and fight blindly N times; lose no less than fifty times in the battle, smashing the mouse to cause accidents; toast to invite the bright moon, and the grass to meet Galen.

A few days ago, I wrote an analysis on the game of eating chicken [Using Python to analyze the data of 1w games of eating chicken, it turns out that this is how to play chicken! Help Xiaopang increase the rate of eating chicken. In view of the fact that the chubby roommate of “Two Hundred Jin Soul” is not only obsessed with eating chicken games, but also likes LOL very much, so in order to help him get his first victory as soon as possible every day, he crawled and analyzed the data of more than 1982 LOL games. It is very amazing that before the start of the game, it can predict the outcome of the game with a high probability! Let you mentally prepare in advance.

image

Assumption

  • Assuming there is no king waiting for the big god to play the trumpet
  • Assuming no leveling
  • Assuming there is no hang-up because of being caught by the daughter-in-law halfway

image

Game battle data acquisition

National Server: Unofficial API of Tencent Game Platform — http://www.games-cube.com/

image

Foreign server: Riot Developer Platform API – https://developer.riotgames.com/

image

Connect to the database:

import numpy as npiimport pymysql, random, jsondef connect_db(database): try: conn = pymysql.connect(host='localhost', port=3306, user='root', password='zandaoguang ', db=database, charset='utf8') return conn except: print ('Exception: MySQL Connection') return None

image

Analyze and train data

Use neural network (neural_network), random forest (random_forest) and support vector machine (support_vector) and other intelligent algorithms for training and regression, and finally compare the results.

The following is part of the neural network code:

from __future__ import print_function import numpy as np#np.random.seed(1337) # for reproducibilityfrom keras.datasets import mnistfrom keras.models import Sequential, load_modelfrom keras.layers import Dense, Dropout, Activation, Flattenfrom keras.layers import Convolution2D , MaxPooling2Dfrom keras.utils import np_utilsfrom keras import backend as Kfrom keras.optimizers import SGD, Adam, RMSpropimport gzipimport sysfrom six.moves import cPicklefrom fetcher import *batch_size = 256nb_classes = 2nb_e poch = 100champion_dict = fetch_champion_dict("champion136.json")champion_num = len(champion_dict) X_train = X_train.astype('int8')X_test = X_test.astype('int8')print('X_train shape:', X_train.shape)print(X_train.shape[0 ], 'train samples')print(X_test.shape[0], 'test samples')Y_train = np_utils.to_categorical(y_train, nb_classes)Y_test = np_utils.to_categorical(y_test, nb_classes)model = Sequential() model.add(Dense(1500, input_dim = champion_num, init='uniform'))model.add(Activation('sigmoid'))model.add(Dense(2))model.add(Activation(\ 'softmax'))model.summary()model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy'])history = model.fit(X_train, Y_train, batch_size =batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(X_test, Y_test))score = model.evaluate(X_test, Y_test, verbose=0)print('Test score:', score[0])print( 'Test accuracy:', score[1])

Random forest code:

from sklearn.ensemble import RandomForestClassifierfrom sklearn.externals import joblibfrom fetcher import *champion_dict = fetch_champion_dict("champion136.json")champion_num = len(champion_dict)X_train, y_train, X_test, y_test = f etch_one_side_riot('12' , 'MATCHED_GAME', 'KING_PORO', 'KINGPORO', ('1492660800000', '1493740800000'), champion_dict)clf = RandomForestClassifier(n_estimators=500, n_jobs=2)clf.fit (X_train, y_train)train_score = clf.score(X_train, y_train)print ("Train Score = " + str(train_score))test_score = clf.score(X_test, y_test)print ("Test Score = " + str(test_score))

SVM code:

from sklearn.externals import joblibfrom sklearn import svmfrom fetcher import *champion_dict = fetch_champion_dict("champion136.json")champion_num = len(champion_dict)X_train, y_train, X_test, y_test = fetch_one_side_ri ot('12', \ 'MATCHED_GAME', 'ARAM_UNRANKED_5x5', 'ARAM', ('1492660800000', '1493740800000'), champion_dict)clf = svm.SVC()clf.fit(X_train, y_train)train_score = clf.score(X_train, y_train)print ("Train Score = " + str(train_score))test_score = clf.score(X_test, y_test)print ("Test Score = " + str(test_score))

image

Game battle prediction

According to the hero lineup of both sides, the accuracy rate of predicting the winner (%)

Author’s note: Since Aguang has not played League of Legends recently, the data analyzed is the game data of 2017.

image

The accuracy of predicting whether the team will win based on the team’s hero lineup only (%)

Image

image

Problems to be researched

  • Is the game victory in LOL related to gender?
  • Is the winning rate of LOL related to the time of day?
  • How much does LOL’s win rate drop when a girlfriend prevents me from playing the game? How to solve?

Note: Due to the small amount of data, more data can be collected in the future, hoping to conduct research on the above and more directions.

image

Conclusion

  • The three important factors for LOL’s final victory are: team lineup, team level, and tacit cooperation.
  • Reasonable allocation of BUFF is also a necessary factor for game victory.
  • The mentality of playing games is also an indispensable condition for winning games.

image

Write at the end

Although we can predict the winning or losing of this game through machine learning algorithms, this is not our final result after all. Playing League of Legends is similar to love. We clearly know that it is impossible for us, but we insist on pursuing it. This is the beauty of love. Maybe there is no result, but the beauty of the process itself is enough to taste in a lifetime.

I have a brother who has been addicted to this game for several years. He still hangs around Internet cafes in his twenties, and his family has turned against him. Of course, there is nothing wrong with the game itself, and I am not blaming the game. Its essence is entertainment. It has existed since ancient times, but the form has been changing and becoming more and more attractive. Knowing that every time you press the keyboard, you will fall into a deeper abyss, but you can’t stop your hands from twitching with excitement, sad person.

People who are extremely addicted to games, leave your limited life in the infinite game, then your soul will be full of achievements until the moment you leave. Even if later in the news reports there will be a coward who died suddenly in an Internet cafe and was laughed at as a joke!

Reader benefits: If you are interested in Python, this set of python learning materials must be useful to you

For beginners with 0 basics:

If you are a zero-based novice, you can consider getting started with Python quickly.
On the one hand, the learning time is relatively short, and the learning content is more comprehensive and concentrated.
The second aspect is that the study plan and direction can be planned according to these materials.

Friends, if you need a full set of Python introductory + advanced learning resource packages, you can click to get it for free (if you encounter problems with scanning codes, you can leave a message in the comment area to get it) ~

CSDN spree: “Python Introduction & amp; Advanced Learning Resource Pack” free sharing

Python learning spree

Python entry to proficiency memorization manual

Python installation package

Python crawler cheats

A complete set of resources for Python data analysis

Python implements a complete set of tutorials for office automation

Python interview highlights and resume template


Python sideline part-time job route

Data collection

The above-mentioned full version of the full set of learning materials for Python has been uploaded to the official CSDN. If you need it, you can scan the QR code of the CSDN official certification below on WeChat to receive it↓↓↓

CSDN spree: “python entry & amp; advanced learning resource package” free sharing