<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alleria on Medium]]></title>
        <description><![CDATA[Stories by Alleria on Medium]]></description>
        <link>https://medium.com/@xiaoyigu?source=rss-57eb0aee8b95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oB-9SZOYTuMV6Q8YvrkLRA.jpeg</url>
            <title>Stories by Alleria on Medium</title>
            <link>https://medium.com/@xiaoyigu?source=rss-57eb0aee8b95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:01:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xiaoyigu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Query Spelling Correction Overview]]></title>
            <link>https://medium.com/@xiaoyigu/query-spelling-correction-overview-dd19cbb4d47a?source=rss-57eb0aee8b95------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd19cbb4d47a</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Alleria]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 04:25:26 GMT</pubDate>
            <atom:updated>2025-09-28T04:26:39.217Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Query Spelling Correction Evolution</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tXheGSs941_kMyBm" /><figcaption>A Summary Figure of This Article (ChatGPT generated)</figcaption></figure><h3><strong>TL;DR</strong></h3><p>Ever searched for a product online, only to be met with “no results found” because of a tiny typo? That’s the multi-billion dollar problem of query spelling correction. Spelling errors kill search results. This article reviews how query correction evolved from 🔡 edit distance | noisy channel → 📊 rankers → 🤖 transformers → 🌐 LLMs, and where the field is heading.</p><p>Query misspelling is a common challenge in information retrieval, detrimental to retrieval systems that rely heavily on string similarity metrics such as exact match or edit distance. In industrial applications such as e-commerce, a misspelled query may lead to “no results found” or irrelevant results, significantly degrading user experience. A robust spelling correction system can directly improve engagement and satisfaction.</p><p>Misspellings arise from several <a href="https://web.stanford.edu/~jurafsky/slp3/slides/6_Spell.pdf">sources</a>: <strong>non-word errors</strong> (e.g., <em>“compiter”</em> → <em>“computer”</em>), <strong>real-word errors</strong> (e.g., <em>“form”</em> instead of <em>“from”</em>), <strong>typographic errors</strong> (missing spaces or transpositions, e.g., <em>“hellp”</em> → <em>“hello”</em>), and <strong>phonetic/cognitive errors</strong> (e.g., <em>“too”</em> vs. <em>“two”</em>) (<a href="https://aclanthology.org/2023.acl-industry.66.pdf">reference</a>).</p><p>🔍 <strong>Traditional approaches</strong> include:</p><ul><li><strong>Edit-distance methods.</strong> Compute character-level distances between a query and a vocabulary, using thresholds for matches. These methods ignore semantics and intent — for example, <em>“noodle”</em> and <em>“doodle”</em> are close by distance but semantically unrelated. On large vocabularies, brute-force distance computation is expensive; efficient candidate generation (e.g., tries or FST) is used in practice.</li><li><strong>Noisy channel models.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*Sm2H2GhFjIuJI4VuSR9_Jg.png" /><figcaption>Noisy Channel Model (<a href="https://aclanthology.org/2022.ecnlp-1.9.pdf">image source</a>: <a href="https://aclanthology.org/2022.ecnlp-1.9.pdf">https://aclanthology.org/2022.ecnlp-1.9.pdf</a>)</figcaption></figure><p>Using Bayes’ rule, correction is framed as maximizing the product of a <strong>channel model</strong> P(Q∣C) — the probability the intended query C would be misspelled into Q — and a <strong>language model</strong> P(C) — the likelihood of the candidate query itself. Channel models typically assign probabilities to edit operations (insertions, deletions, substitutions, transpositions), often parameterized from edit-distance statistics such as Damerau-Levenshtein. Language models are trained from corpora or query logs to capture realistic word and phrase frequencies. While effective, these models require maintenance (updating vocabularies and probabilities), and multi-word queries demand n-gram or higher-order models beyond unigrams.</p><ul><li><strong>Ranker-based systems.</strong> These generate multiple candidate corrections (from edit distance, phonetic rules, logs, etc.) and use supervised models to rank them. Features may include query frequency, edit distances, or context signals. Such systems, pioneered at <a href="https://aclanthology.org/D07-1019.pdf">Microsoft/Bing</a> (<a href="https://www.microsoft.com/en-us/research/wp-content/uploads/2010/08/coling2010-speller-v5-name.pdf">reference</a>), are more scalable than naive methods, though they may struggle with natural language queries requiring deep semantic understanding. Modern hybrid <a href="https://arxiv.org/pdf/2305.01082">pipelines</a> explicitly fuse traditional candidate generation (fast, scalable) with neural reranking, balancing scalability and accuracy.</li></ul><p>⚡ <strong>Neural and transformer-based models.</strong> With BERT, T5, and related architectures, correction increasingly resembles <em>machine translation</em>: the misspelled query is input, and the model generates the corrected query. Unlike discriminative rankers, encoder-decoder models can handle complex, multi-error corrections and entire query contexts. Generative models (RNNs, LSTMs, Transformers) are data-hungry, so augmentation techniques like Easy Data Augmentation (<a href="https://arxiv.org/pdf/1901.11196">EDA</a>) can be used to synthesize noisy training data. <a href="https://arxiv.org/pdf/2010.11085">NeuSpell</a> is a BERT-based sequence labeling toolkit yielding strong results. However, production deployment must account for <a href="https://arxiv.org/pdf/2305.01082">latency</a>: even single-token queries (“apple”) must be corrected within strict service-level agreements. Domain-specific fine-tuning is essential for accuracy.</p><p>Industry has adapted a few methods: <a href="https://dl.acm.org/doi/pdf/10.1145/3637528.3671625">eBay</a> trained a distilled transformer on in-session edits to achieve production-grade performance. <a href="https://aclanthology.org/2022.ecnlp-1.9.pdf">Amazon AI</a> addressed phonetic and multilingual errors in e-commerce search using phonetic modeling that added no extra latency.</p><p>🤖 <strong>Large Language Models (LLMs).</strong> With cheaper computation, companies now explore LLMs for query correction. LLM-based search got popular in <a href="https://kdd2025.kdd.org/applied-data-science-ads-track-papers-2/">KDD 2025 Applied Data Science Track</a>. LLMs bring commonsense knowledge and flexibility, often paired with retrieval-augmented generation (RAG), which grounds corrections in product catalogs or context (an <a href="https://dl.acm.org/doi/pdf/10.1145/3711896.3737204">example</a>). While LLMs mitigate context limitations, latency and over-correction remain concerns; some <a href="https://doi.org/10.1145/3711896.3737230">companies</a> use fine-tuned lightweight models with high-quality constraints for more predictable performance.</p><p><strong>Summary.</strong> Query spelling correction has evolved from simple dictionary lookups to probabilistic noisy channel models, ranker-based systems, neural networks, transformers, and now LLMs. Each stage improved context-awareness and error coverage, but raised new challenges around latency and domain adaptation. Modern production systems typically combine efficient candidate generation (edit distance, FSTs, phonetic variants) with neural ranking or generation. With LLMs, query correction increasingly integrates into broader <em>semantic search and query understanding</em> pipelines, leveraging user history, in-session behavior, and metadata for richer search accuracy. Now AI-assisted search is almost everywhere.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd19cbb4d47a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer Architecture]]></title>
            <link>https://medium.com/@xiaoyigu/transformer-architecture-920c4e7f5dc7?source=rss-57eb0aee8b95------2</link>
            <guid isPermaLink="false">https://medium.com/p/920c4e7f5dc7</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alleria]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 01:55:27 GMT</pubDate>
            <atom:updated>2024-10-28T01:55:27.336Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a summary of transformer architecture with detailed component explanations.</p><h3>Table of Contents</h3><ul><li>Backgrounds</li><li>Transformer Architecture</li><li>Training and Inferencing</li><li>What’s Next</li><li>References</li></ul><h3>Backgrounds</h3><p>In the NLP field, traditional RNNs model the text sequences while suffering from the gradient vanishing and explosion issues. Like human memory, RNNs struggle to retain long-past information, focusing more on recent inputs. LSTM excels in long-term dependencies and alleviates gradient vanishing by its memory cell (forget/input/output gates).</p><p>In 2017, Google’s scientists proposed <strong>transformer</strong> with its famous attention mechanism in the “Attention is All You Need” paper <a href="https://user.phil.hhu.de/~cwurm/wp-content/uploads/2020/01/7181-attention-is-all-you-need.pdf">1</a> (cited by 138,640), which became the SOTA deep learning framework widely used in NLP.</p><h3>Transformer Architecture</h3><p>The transformer architecture explains its transformative performance in NLP tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*5kQ25paK8F-oRQiO.png" /><figcaption>Transformer from its paper</figcaption></figure><h4>Tokenization and Word Embedding</h4><p>Like other NLP models, the model can’t understand the texts, hence we need numerical inputs. An intuitive way to convert text into numbers is by breaking sentences into segments, assigning each a numerical representation, and then concatenating them.</p><h4>Tokenization</h4><p>The first part of breaking sentences into multiple sections is tokenization. Huggingface has a <a href="https://huggingface.co/docs/transformers/en/tokenizer_summary">tokenizer summary</a>.</p><p><strong>Word-based:</strong> In general, splitting by words is simple, but the major problem is it creates a huge corpus (a set of all unique words).</p><p><strong>Character-based:</strong> But if we only break the sentences into characters, every single character contains little contextual meaning, although it reduces the corpus size greatly. For example, learning the meaning of “h” alone provides little context compared to learning “hello.”</p><p><strong>Subword-based: </strong>Since <em>word-based</em> and <em>character-based</em> have limitations, the transformer model uses <em>subword</em> tokenization, which is the hybrid between <em>word-based</em> and <em>character-based</em>. The principle is, the rarely used words should be split into smaller and meaningful subwords while the frequent words should be better kept. For example, “surprisingly” is used less frequently than “surprising” and “ly”. It will be decomposed into “surprising” and “ly” and we can use “surprising” and “ly” to create “surprisingly” again.</p><p>Subword-based tokenizers include:</p><ul><li><em>Byte-Pair Encoding (BPE)</em> <a href="https://arxiv.org/pdf/1508.07909">2</a>, used in GPT-2, RoBERTa, etc.</li><li><em>WordPiece</em> <a href="https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/37842.pdf">3</a>, used in BERT, DistilBERT, Electra, etc.</li><li><em>Unigram</em> <a href="https://arxiv.org/pdf/1804.10959">4</a>, initialize a large vocabulary and then narrow it down.</li></ul><p>Note that these methods are based on a pre-tokenizer, which is to first separate words by spaces, and then apply a subword tokenizer. However, some languages such as Chinese and Japanese, do not use spaces to separate words within sentences.</p><ul><li>Therefore, SentencePiece <a href="https://arxiv.org/pdf/1808.06226">5</a>, a language-independent subword tokenizer was proposed, making it easier for multilingual tasks.</li></ul><p>You can use the <a href="https://github.com/openai/tiktoken">tiktoken</a> package to check the tokenization of OpenAI’s models.</p><h4>Word Embedding</h4><p>After separating the long text sequences into tokens (to sync with the generally used term “word embedding”, in the following sections we will also use “word”), the next process to vectorize these text tokens is word embedding. There are many word embedding techniques.</p><p><strong>One-Hot:</strong> One-hot embedding is straightforward. If the vocabulary has 10k different words, each word will become a 10k-dimension vector. All other elements are “0” except for a single element which is a “1”. The dimension of the embedded vectors highly depends on the vocab size and each vector is sparse and huge.</p><p><strong>Bag of Words:</strong> Bag of words is to model texts by counting the word frequency. It indeed makes the vectors denser. But the shortcoming is losing semantic meanings if only counting the number of words.</p><p><strong>Word Embeddings:</strong> To create dense and smaller word representations, while maintaining the semantic meanings, methods like Word2Vec <a href="https://arxiv.org/pdf/1301.3781">6</a> and GloVe <a href="https://aclanthology.org/D14-1162.pdf">7</a> are often used. Word2Vec trains embeddings with CBOW (continuous bag of words) and Skip-gram. To put it simply, the embeddings are trained by predicting a token with its surrounding tokens, and by predicting its surrounding tokens with a specific token.</p><h4>Positional Encoding</h4><p>With word embedding, each word now has its own numerical representation.</p><p>In natural language, words’ relative orders carry information. For example, in the sentence “My cat eats fish” and “My fish eats cat”, the positions of “<em>cat</em>” and “<em>fish</em>” determine the sentence meanings.</p><p>In traditional RNN, as the model processes the input word vectors sequentially, using the same word embedding for the same word works. E.g. in both of the 2 sentences, cat: [0.1, 0.2, -0.1], fish: [-0.1, -0.2, 0.1], regardless of the positions.</p><p>But in transformer, as the model processes each word in parallel for efficiency, using word embeddings alone fails to capture relative orders. Therefore, the authors proposed positional encoding with 2 options: One is to learn the embeddings, which means trainable parameters are required; Another one is to directly use some heuristics like sinusoidal. They found similar performances of these options. Finally, they chose a set of sinusoidal functions to encode positions without adding additional parameters, reducing computational cost.</p><h4>Encoders and Decoders</h4><p>With word embedding and positional encoding, the transformer model can understand each word and its relative order now. Before diving into self-attention, it is worth mentioning that the transformer architecture has 2 main sections, the encoders and the decoders. On the high level, the encoders are to understand the context and the decoders are to generate predictions. Moreover, stacking only encoders yields models like BERT (Bidirectional encoder representations from transformers <a href="https://arxiv.org/pdf/1810.04805">8</a>), focused on understanding context while stacking decoders creates autoregressive models like GPT (Generative Pre-trained Transformer) for text generation.</p><p>Let’s start with the architecture of Encoders, aka. encoder layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*OWiXLVHvozM_jq_s.png" /><figcaption>Transformer Encoder Layers. Reference: <a href="https://glassboxmedicine.com/2019/08/15/the-transformer-attention-is-all-you-need/">https://glassboxmedicine.com/2019/08/15/the-transformer-attention-is-all-you-need/</a></figcaption></figure><h4>Self-Attention</h4><p>After the input text is vectorized and attached positional information, how does the model understand the relation of words? This is where the self-attention mechanism works. In the sentence “My name is Ana.” The word “<em>name</em>” is more relevant to “<em>Ana</em>” than to “<em>is</em>”. Failing to capture the information causes information loss. The transformer architecture leverages the attention mechanism to solve this problem. In encoders, it is self-attention, in decoders, it is masked self-attention and between encoders and decoders, it is encoder-decoder attention. You will see the word “<em>multi-head</em>” a lot. We will discuss it later.</p><p><strong>Query, Key, Value</strong></p><p>For each token (word embedding + positional encoding now), the architecture will generate query, key and value (Q, K, V) with linear transformations using 3 sets of matrixes. Note, here, the query, key and value are generated vectors using the encoded inputs and the mentioned matrixes. Suppose we have an English-to-Chinese machine translation task and the English Sequence is “I love apples.”, in the self-attention mechanism, we will have 3 query vectors for “I”, “love”, and “apples” respectively and 3 key vectors for these 3 words too. Then to get the similarity/relevance between “I” and every other word, including itself, we need to calculate the <a href="https://en.wikipedia.org/wiki/Dot_product">Dot Product</a> of the query of “I” and the key of “I”, “love” and “apples” respectively. Then a softmax will be applied to these 3 values and generate 3 new softmax outputs. We then multiply the value vector with the softmax output and create a new vector, which is the <em>self-attention value for “I”</em>.</p><p>As we pointed out, transformer processes words in parallel, which means the <em>key, query, and values of “I”, “love” and “apples” will be created at the same time regardless of the word orders</em>. To enable this, the weights used for <em>query</em> are the same across words, and so do key and value.</p><p><strong>Scaled Dot Product</strong></p><p>We simply mentioned Dot Product above. But the paper is actually using scaled dot products. When the input dimension gets larger, the value created from query * key will be large too. So after <a href="https://en.wikipedia.org/wiki/Softmax_function">softmax</a>, some self-attention values are large, while some are close to 0. If we don’t scale the Q*K output, we might have gradient vanishing/exploding issues and the training will not be stable. The scaling stabilizes the training and avoids saturating the softmax output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*iWk_sTNgr_3mX4sE.png" /><figcaption>Scaled Dot Product from paper</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*Mq-6H06Y4KIBp4tV.png" /><figcaption>Attention Calculation from paper</figcaption></figure><p><strong>Multi-Head Attention</strong></p><p>In the transformer model, the authors proposed a stack of self-attention cells (8 heads at first). Each cell uses its own sets of weights for query, key and value separately. The reason behind it is to capture complex paragraph and context meanings. This means, each independent head focuses on a different aspect or subspace of the input information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*9O1ZnWT2_OlDAJb6.png" /><figcaption>Multi-head Attention from paper</figcaption></figure><p>To control the computational cost of multiple attention calculations, Multi-Head Attention reduces dimensions in each head. If head = 8, and the original model dimension is 512, the authors use dk = dv = d_model/h = 64 in each head. Then the MHA outputs are concatenated, so that the output dimension will be the same as the original input. For example, if the input vector is [1, 2, 3, 4, 5, 6, 7, 8], head = 2, then in the first head we have v1=[1, 2, 3, 4] and in the second head, we have v2=[5, 6, 7, 8]. We apply distinct sets of w1 to v1 and w2 to v2(w1 and w2 are unique to their head), then concatenate the outputs, which ultimately match the original input dimensions.</p><h4>Residual Connection</h4><p>Let’s get back to the encoder layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*yqu05kxB-p8vQP8g.png" /><figcaption>Transformer Encoder Layers. Reference: <a href="https://glassboxmedicine.com/2019/08/15/the-transformer-attention-is-all-you-need/">https://glassboxmedicine.com/2019/08/15/the-transformer-attention-is-all-you-need/</a></figcaption></figure><p>Now we have the multi-head attention. The next components are the residual connections and normalization. To mitigate the vanishing gradient problem and make it more efficient to train deeper networks, the transformer architecture allows self-attention layers to connect to the word’s embedding and position encoding input. This is residual connections, aka, skip connections, which were first popularized by ResNet <a href="https://arxiv.org/pdf/1512.03385">9</a>.</p><h4>Layer Normalization</h4><p>In deep learning models, to reduce overfitting, normalization is a commonly used technique. Normalizing the input of activation functions ensures the values are centered around zero, also leading to more stable and faster training.</p><p>Computer vision tasks use batch normalization a lot, because the inputs are images with the same shape(dims). However, each input text in NLP tasks can have a different number of tokens or sizes. Also the tokens differ a lot in different sentences. Simply using batch normalization on each dimension is impossible. Therefore, layer normalizations are preferred. It is to normalize across all features(dimensions) in a training example, instead of normalizing across all the examples for a dimension.</p><h4>PreLN vs. PostLN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*We9_Sym-bOBYnqE7.png" /><figcaption>PreLN vs. PostLN, source: <a href="https://benjaminwarner.dev/2023/07/28/rest-of-the-transformer">https://benjaminwarner.dev/2023/07/28/rest-of-the-transformer</a></figcaption></figure><p>In practice, there are 2 ways to add layer normalization(LN).</p><ul><li><strong>PostLN(left): </strong>place the LN after the residual block. It normalized the feedforward network residual as well, which is more robust.</li><li><strong>PreLN(right): </strong>place the LN inside the residual block. It normalizes fewer parameters, which actually helps prevent gradient explosion/vanishing. If the network is very deep, then pre-norm can be better. If the model has fewer layers, then post-norm will be robust.</li></ul><h4>Feedforward Network</h4><p>The last part of an encoder layer is the feedforward network. It is some linear layers with activation functions like ReLu.</p><p>Now we have covered the basic structures in the encoder. Next we will discuss decoders. Encoders and decoders have similar normalization and feedforward networks. Here we only include the different components.</p><h4>Masked Multi-head Attention</h4><p>Looking at the architecture again, the attention mechanism in the right tower (decoders) is different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*uiG9yVrww_0sp1kz.png" /><figcaption>Transformer architecture in the paper</figcaption></figure><p>We have defined Multi-head, but what is masked? Masked Self-Attention (MSA) is to calculate the relevance/similarity between each word, including itself and all the words preceding that word. We have MSA here instead of Self-attention because the decoder is supposed to translate (in the English to Chinese translation task) the content. So when predicting the next token, it is unable to access anything after it, hence preventing data leakage during training and helping generate sequences autoregressively. Here is a reference to some <a href="https://huggingface.co/blog/how-to-generate">text generation strategies</a> used to predict the next token.</p><h4>Encoder-decoder Attention</h4><p>As we mentioned, the encoders are to learn the context and the decoders are to create new tokens, the Encoder-decoder Attention is to connect encoders and decoders, allowing the decoder to selectively focus on the significant words in the input. For example, in the sentence “I love apples”, when translating to Chinese “我爱苹果“, we create the query for “我”, then use it to calculate the dot product with each key in the encoded “I love apples” and get the encoder-decoder attention values. Note that this layer applies a distinct set of weight matrixes from self-attention to focus selectively on significant words from the encoder output.</p><h3>Training and Inferencing</h3><p>During training, each token’s output from a layer computation can be processed in parallel in the subsequent layer. Meanwhile, as we already have the target sequence (just like we already have the label to predict), so in the decoder, masked self-attention is calculated in parallel too.</p><p>During inferencing, the decoder has to predict based on the previous tokens, which means it can’t be fully parallelized, resulting in slower processing times.</p><h3>What’s Next</h3><p>This is a summary of the transformer architecture. In the next posts, we will discuss more about BERT, knowledge distillation and various multi-modal models.</p><h3>References</h3><p>Self-Attention Video: <a href="https://www.youtube.com/watch?v=zxQyTK8quyY&amp;t=3s">https://www.youtube.com/watch?v=zxQyTK8quyY&amp;t=3s</a></p><p>Thanks for reading it! Feel free to reach out if you have any questions.</p><p>GitHub:</p><p><a href="https://github.com/Alleria1809/ML-LLM-Posts/blob/main/transformer/Transformer.md">https://github.com/Alleria1809/ML-LLM-Posts/blob/main/transformer/Transformer.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=920c4e7f5dc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Text Chunking for LLMs]]></title>
            <link>https://blog.gopenai.com/implementing-text-chunking-for-llms-98b669606f3f?source=rss-57eb0aee8b95------2</link>
            <guid isPermaLink="false">https://medium.com/p/98b669606f3f</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Alleria]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 05:14:42 GMT</pubDate>
            <atom:updated>2024-06-28T11:18:35.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1byOYWUi082wQJWidnoHwQ.png" /><figcaption>A Simple Illustration</figcaption></figure><h3><strong>TL; DR</strong></h3><p>This article focuses on practical text-splitting strategies for Large Language Models (LLMs). It contains:</p><ul><li>Background of Text Chunking</li><li>Chunking Approaches</li><li><a href="https://github.com/openai/tiktoken?tab=readme-ov-file">tiktoken</a> and Its Considerations</li></ul><h3><strong>Background</strong></h3><p>Modern LLMs like GPT-4 Turbo can process up to <a href="https://platform.openai.com/docs/models">128k tokens</a> in a single context window but may experience issues such as hallucinations. A popular strategy to enhance LLM performance is the Retrieval-Augmented Generation (RAG) system. This method involves retrieving and providing relevant context before the LLM processes a query, thereby reducing noise and enhancing accuracy. For effective implementation, essential texts are chunked into smaller, manageable segments and then embedded for efficient retrieval, as observed in existing LLM infrastructure libraries.</p><h3>Chunking Approaches</h3><p>The principle of text chunking involves dividing long texts into smaller units and then merging them into shorter segments with specific <strong><em>chunk sizes and overlaps</em></strong>. Including overlap helps prevent abrupt shifts in meaning, which is crucial for tasks like sentiment analysis where context continuity is key.</p><h4>Text Split</h4><p>For straightforward texts, we can use Python’s built-in string-splitting functions. For instance, medical papers can be split at sentence boundaries (using <strong>text.split(“.”)</strong>) to preserve the integrity of each sentence. This approach allows control over the number of sentences per chunk, maintaining context relevance.</p><h4>Tokenization</h4><p>For less context-sensitive data, splitting by words may be adequate. However, when integrating text into an LLM, which processes input as tokens rather than words, <strong>tokenizers</strong> become essential. They ensure the chunked text conforms to the LLM’s context window limitations, optimizing both relevance and processing efficiency.</p><h3>tiktoken</h3><p>OpenAI highlights the importance of tokenization:</p><ol><li>Determine if the text exceeds the processing capabilities of a model.</li><li>Inform the cost of an API call, as pricing is based on token count.</li></ol><h4>How tiktoken works</h4><p>To facilitate efficient tokenization, OpenAI introduced <a href="https://github.com/openai/tiktoken?tab=readme-ov-file">tiktoken</a>, which employs <a href="https://en.wikipedia.org/wiki/Byte_pair_encoding">Byte Pair Encoding (BPE)</a>. Unlike traditional tokenizers that may struggle with unseen words, resulting in out-of-content (&lt;OOC&gt;) or unknown (&lt;UNK&gt;) tokens, BPE can handle arbitrary text, including data not present in the training set. This flexibility is crucial for processing diverse text inputs efficiently.</p><p>tiktoken allows developers to choose encoding methods that best fit their model’s needs, accommodating variations in word splitting, space grouping, and the handling of non-English characters. More details can be found in OpenAI’s guide on token counting: <a href="https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb">How to Count Tokens with tiktoken</a>.</p><p>The tool operates through distinct encoding and decoding phases and supports a vocabulary size of 100,256 unique tokens as noted by <a href="https://en.wikipedia.org/wiki/Byte_pair_encoding">Wikipedia</a> for models like GPT-3.5 and GPT-4. Developers can also integrate custom special tokens into this system, enhancing flexibility in token management.</p><p>Using tiktoken, one word can sometimes get encoded to multiple token ids. For example:</p><pre>import tiktoken<br><br># load encoding tokenizer<br># use cl100k_base here<br>tokenizer = tiktoken.get_encoding(&quot;cl100k_base&quot;)<br>input = &quot;tiktoken.&quot;<br><br>encoded = tokenizer.encode(input)<br>print(f&quot;encoded: {encoded}&quot;)<br><br>for token in encoded:<br>    decoded_token = tokenizer.decode([token])<br>    print(f&quot;decoded_token: {decoded_token}&quot;)<br><br># encoded: [83, 1609, 5963, 13]<br># decoded_token: t<br># decoded_token: ik<br># decoded_token: token<br># decoded_token: .</pre><p>tiktoken also treats the <em>punctuations</em> as tokens.</p><h4>Examples</h4><p>Now let’s go back to our original task — text chunking.</p><p>Using basic text splitting to create text chunks:</p><pre>from more_itertools import windowed<br>chunk_size = 3<br>chunk_overlap = 1<br>split_by = &quot; &quot;<br>input = &quot;What is Retrieval-Augmented Generation?&quot;<br><br>splits = input.split(split_by)<br>print(f&quot;splits: {splits}&quot;)<br><br># Calculate the step size from the chunk size and overlap<br>step_size = chunk_size - chunk_overlap<br><br># Use more_itertools.windowed to create overlapping chunks<br>chunks = [split_by.join(list(chunk)) for chunk in windowed(splits, n=chunk_size, step=step_size) if chunk is not None and None not in chunk]<br><br>print(f&quot;chunks: {chunks}&quot;)<br># splits: [&#39;What&#39;, &#39;is&#39;, &#39;Retrieval-Augmented&#39;, &#39;Generation?&#39;]<br># chunks: [&#39;What is Retrieval-Augmented&#39;]</pre><p>When employing a tokenizer:</p><pre>from more_itertools import windowed<br>chunk_size = 3<br>chunk_overlap = 1<br>input = &quot;What is Retrieval-Augmented Generation?&quot;<br><br>encoded = tokenizer.encode(input)<br>print(f&quot;encoded: {encoded}&quot;)<br>decoded = []<br>for token in encoded:<br>    decoded_token = tokenizer.decode([token])<br>    decoded.append(decoded_token)<br>print(f&quot;decoded: {decoded}&quot;)<br><br># Calculate the step size from the chunk size and overlap<br>step_size = chunk_size - chunk_overlap<br><br># Use more_itertools.windowed to create overlapping chunks<br>chunks = [&quot;&quot;.join(list(chunk)) for chunk in windowed(decoded, n=chunk_size, step=step_size) if chunk is not None and None not in chunk]<br><br>print(f&quot;chunks: {chunks}&quot;)<br><br># encoded: [3923, 374, 20035, 838, 62735, 28078, 24367, 30]<br># decoded: [&#39;What&#39;, &#39; is&#39;, &#39; Retrie&#39;, &#39;val&#39;, &#39;-Aug&#39;, &#39;mented&#39;, &#39; Generation&#39;, &#39;?&#39;]<br># chunks: [&#39;What is Retrie&#39;, &#39; Retrieval-Aug&#39;, &#39;-Augmented Generation&#39;]</pre><p>You will find that the tokenizer is longer than the text splitter. If we check the OpenAI token count <a href="https://platform.openai.com/tokenizer">platform</a>, we will see tiktoken decoded output is consistent with its official website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLpR_kN0IOIjKmiZ6I-m5A.png" /><figcaption>OpenAI Tokenizer Count</figcaption></figure><p>Now we have covered how we can split text into small units by Python function and tokenizer, and then merge the units into chunks based on chunk size and overlap.</p><h4><strong>Challenge</strong></h4><p>Despite the tokenizer’s ability to process unseen tokens, decoding tokens individually may lead to the appearance of the ‘�’ character, indicating decoding errors. For example:</p><pre>from more_itertools import windowed<br>chunk_size = 3<br>chunk_overlap = 1<br>input = &quot;What is ≈∇∆∟?😊&quot;<br><br><br>encoded = tokenizer.encode(input)<br>print(f&quot;encoded: {encoded}&quot;)<br>decoded = []<br>for token in encoded:<br>    decoded_token = tokenizer.decode([token])<br>    decoded.append(decoded_token)<br>print(f&quot;decoded: {decoded}&quot;)<br><br># Calculate the step size from the chunk size and overlap<br>step_size = chunk_size - chunk_overlap<br><br># Use more_itertools.windowed to create overlapping chunks<br>chunks = [&quot;&quot;.join(list(chunk)) for chunk in windowed(decoded, n=chunk_size, step=step_size) if chunk is not None and None not in chunk]<br><br>print(f&quot;chunks: {chunks}&quot;)<br><br># encoded: [3923, 374, 21784, 230, 22447, 229, 22447, 228, 22447, 253, 30, 76460, 232]<br># decoded: [&#39;What&#39;, &#39; is&#39;, &#39; �&#39;, &#39;�&#39;, &#39;�&#39;, &#39;�&#39;, &#39;�&#39;, &#39;�&#39;, &#39;�&#39;, &#39;�&#39;, &#39;?&#39;, &#39;�&#39;, &#39;�&#39;]<br># chunks: [&#39;What is �&#39;, &#39; ���&#39;, &#39;���&#39;, &#39;���&#39;, &#39;��?&#39;, &#39;?��&#39;]</pre><p>So if we tokenize an emoji 😊 into 2 token ids, and decode individually, it creates �s.</p><h4>Potential Solution</h4><p>One way to minimize this problem is to decode the chunked list after merging.</p><pre>from more_itertools import windowed<br>chunk_size = 3<br>chunk_overlap = 1<br>input = &quot;What is ≈∇∆∟?😊&quot;<br><br><br>encoded = tokenizer.encode(input)<br>print(f&quot;encoded: {encoded}&quot;)<br># decoded = []<br># for token in encoded:<br>#     decoded_token = tokenizer.decode([token])<br>#     decoded.append(decoded_token)<br># print(f&quot;decoded: {decoded}&quot;)<br><br># Calculate the step size from the chunk size and overlap<br>step_size = chunk_size - chunk_overlap<br><br># Use more_itertools.windowed to create overlapping chunks<br>chunks = [list(chunk) for chunk in windowed(encoded, n=chunk_size, step=step_size) if chunk is not None and None not in chunk]<br>decoded_chunks = [tokenizer.decode(chunk) for chunk in chunks]<br>print(f&quot;chunks: {chunks}&quot;)<br>print(f&quot;decoded_chunks: {decoded_chunks}&quot;)<br><br># encoded: [3923, 374, 21784, 230, 22447, 229, 22447, 228, 22447, 253, 30, 76460, 232]<br># chunks: [[3923, 374, 21784], [21784, 230, 22447], [22447, 229, 22447], [22447, 228, 22447], [22447, 253, 30], [30, 76460, 232]]<br># decoded_chunks: [&#39;What is �&#39;, &#39; ≈�&#39;, &#39;∇�&#39;, &#39;∆�&#39;, &#39;∟?&#39;, &#39;?😊&#39;]</pre><p>By decoding the merged chunks, we can recover more input works and keep them as the LLM input.</p><h3>Future Directions</h3><p>I’m still exploring how we can manage the tokenization step better, both controlling the number of tokens to input and keeping the raw input after decoding. Please feel free to share any suggestions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98b669606f3f" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/implementing-text-chunking-for-llms-98b669606f3f">Implementing Text Chunking for LLMs</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a GraphQL-based data pipeline using Python]]></title>
            <link>https://medium.com/@xiaoyigu/building-a-graphql-based-data-pipeline-using-python-7c35cb898a25?source=rss-57eb0aee8b95------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c35cb898a25</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Alleria]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 03:25:38 GMT</pubDate>
            <atom:updated>2024-04-09T22:28:10.625Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Keywords: GraphQL, Python, SQL</strong></p><p>GraphQL is a great tool for building real-time mobile applications. But it is abstract to understand and implement. I have experienced the difficulty of acquiring resources and build an application from scratch.</p><p>Therefore I will present GraphQL to you based on my understanding and practice. The article starts with what GraphQL is, why we can use it, and how it works. Then I will show you a simple tutorial on implementing GraphQL in a web application. <strong>This application is very simple and hard to demonstrate the advantages of GraphQL since <em>it does not use GraphQL in common sense. It is directly leveraging the power of the resolvers. I will update it gradually in future versions</em>.</strong> But I hope it will be a good start for you to understand how to build a GraphQL based application.</p><p>You can find the code of the project <a href="https://github.com/Alleria1809/GraphQL-Python">here</a>.</p><p><strong><em>What is GraphQL?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kWF40nHa8JfrhnS6" /><figcaption>source: <a href="https://medium.com/@vinciabhinav7/what-is-graphql-an-overview-of-concepts-e8a8e3c92a7c">https://medium.com/@vinciabhinav7/what-is-graphql-an-overview-of-concepts-e8a8e3c92a7c</a></figcaption></figure><p>GraphQL is developed by Meta. The engineers mentioned :</p><blockquote>“When we built Facebook’s <strong>mobile applications</strong>, we needed a data-fetching API powerful enough to describe all of Facebook, yet simple enough to be easy to learn and use by our product developers.”</blockquote><p><a href="https://engineering.fb.com/2015/09/14/core-infra/graphql-a-data-query-language/">https://engineering.fb.com/2015/09/14/core-infra/graphql-a-data-query-language/</a></p><p>Sometimes it is described as GraphQL API and it is confusing since the <a href="https://graphql.org/">official doc</a> defined it as a query language for APIs:</p><blockquote>GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data — meaning that it excels at fetching data from a variety of data sources, bundling it all together, and handing it back to us.</blockquote><p><a href="https://graphql.com/learn/what-is-graphql/">What is GraphQL?</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zsdm-saDx-e9WsHI" /><figcaption>Official Document</figcaption></figure><p>This means that GraphQL as a query language is actually helping us get data precisely from multiple sources just with a single request.)</p><p><strong><em>Why use GraphQL?</em></strong></p><p>The advantages of using GraphQL include:</p><ol><li>API technologies like REST would require multiple HTTP calls to access data from multiple sources but GraphQL simplifies the task of aggregating data from multiple sources or APIs and then resolving the data to the client in <strong>a single endpoint</strong>. E.g. <strong><em>REST: </em></strong><em>Suppose you’re building a social media app and need to display a user’s profile, including their basic info and the last 10 posts. With REST, you might need to make two HTTP requests: one to /api/user/{userId} to get the user’s basic info and another to /api/user/{userId}/posts to get their posts.GraphQL: With</em><strong><em> GraphQL</em></strong><em>, you can fetch both the user’s information and their last 10 posts in a single query. This reduces the number of network requests, making your application more efficient, especially in mobile environments or places with slow internet connections.</em></li><li>GraphQL is <strong>strongly typed</strong>; you can validate a query within the GraphQL type system before execution.</li><li>Since GraphQL query can <strong>precisely fetch the data the users request</strong> (not over-fetching — we don’t have to get data from multiple sources and filter them, not under-fetching), the data exchange will be more efficient.</li></ol><p>Therefore, GraphQL is a powerful tool for mobile apps, especially user-facing applications.</p><p>More advantages:</p><p><a href="https://engineering.fb.com/2015/09/14/core-infra/graphql-a-data-query-language/">https://engineering.fb.com/2015/09/14/core-infra/graphql-a-data-query-language/</a></p><p><strong><em>How does it work?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o-e7AjlyRHZPWyqF" /><figcaption>source: <a href="https://scandiweb.com/blog/what-is-graphql-api-how-does-it-work/">https://scandiweb.com/blog/what-is-graphql-api-how-does-it-work/</a></figcaption></figure><p>You need to define the <strong>schema</strong>, which include the data and types you are able to query on the service. It sounds like a contract between user and the service.</p><p>Then the operations users can perform are <strong>Query</strong> and <strong>Mutation</strong>. Query means reading or fetching values. Mutation refers to inserting or deleting values.</p><p>When query and mutation come in, we need <strong>resolvers</strong> to validate the operations and process the operations.</p><p>The clients(users) can request data, the request will be validated through the schema(check if we are able to offer the data to the clients). If the request is validated, then the resolver will fetch the requested data from the storage and send it back to the clients(users) side.</p><p>This article is a good reference:</p><p><a href="https://scandiweb.com/blog/what-is-graphql-api-how-does-it-work/">https://scandiweb.com/blog/what-is-graphql-api-how-does-it-work/</a></p><h3>Build an app based on GraphQL</h3><p>In the next part, I will show you how to build a GraphQL based Daily Planning Application.</p><p><strong>Use Case:</strong></p><p>Let’s build an app that the users can input in the daily plans(content) and then fetch back the plans they have done on a specific day.</p><p><strong>Features:</strong></p><ol><li>Store the data the user inputs in real time</li><li>Fetch that data back to the users</li></ol><p><strong>Tech Stack:</strong></p><p><strong>Enviroment: VScode</strong></p><ul><li><strong>Python + streamlit</strong> for demo, streamlit integrates frontend and backend easily</li><li><strong>Sqlalchemy</strong> for integration with python(ORM instead of raw sql)</li><li><strong>Postgresql</strong> for data storage</li><li><strong>Graphql</strong> instead of sql/rest api because:</li></ul><p>— Single endpoint instead of multiple sources</p><p>— Flexible data selection, no over fetching and under fetching</p><p>— Strict type</p><p><strong>Steps:</strong></p><ol><li>create a database — in the postgres server</li><li>define the schema.graphql</li><li>create the backend(define models, resolvers)</li><li>create the app frontend</li></ol><p>I’m using streamlit, so the frontend and the backend will be closely integrated.</p><p><strong>File Structure</strong></p><p>app_dir/</p><p>— schema.graphql</p><p>— backend.py(resolvers, models)</p><p>— app_streamlit.py(a dummy frontend)</p><p><strong>Create a Database</strong></p><p>In the terminal, open postgres and create a database.</p><pre>CREATE DATABASE daily_planning;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*8yy8hwsGrJXvuH5j" /><figcaption>create database</figcaption></figure><p>There are many instructions to connect to the postgresql database through VScode. E.g. <a href="https://ryanhutzley.medium.com/getting-started-with-the-postgresql-extension-for-vscode-d666c281ec72">https://ryanhutzley.medium.com/getting-started-with-the-postgresql-extension-for-vscode-d666c281ec72</a></p><p><strong>Create the tables for the app</strong></p><p>Since this is a very simple application, the main entity is the users and the plans. Meanwhile we will need the logging activity of the user.</p><p>So We will have 2 dimension tables here for <strong>users</strong> and <strong>plans</strong> separately. And also a table to store the <strong>activities</strong> of users.</p><p>I will add very simple attributes to these 3 tables.</p><pre>DIM_user<br>Id (Primary Key)<br>User_name<br>created_at<br><br>DIM_Plans<br>Id (Primary Key)<br>created_at<br><br>Activity<br>Session_id (Primary Key)<br>User_id<br>Plan_id<br>Event_type -- suppose the app only supports add new task &quot;Add new task&quot;<br>task_content<br>created_at</pre><p>When you connect to the database correctly, run the following code to create the database</p><pre>-- Creating the DIM_user table<br>CREATE TABLE dim_users (<br>   id INT PRIMARY KEY,<br>   user_name VARCHAR(255),<br>   created_at TIMESTAMP NOT NULL DEFAULT NOW()<br>);<br><br><br>-- Creating the DIM_Plans table<br>CREATE TABLE dim_plans (<br>   id SERIAL PRIMARY KEY,<br>   created_at TIMESTAMP NOT NULL DEFAULT NOW()<br>);<br><br><br>-- Creating the Activity table<br>CREATE TABLE activity (<br>   session_id SERIAL PRIMARY KEY,<br>   user_id INT,<br>   plan_id INT,<br>   Event_type VARCHAR(255) CHECK (Event_type = &#39;add new task&#39;), -- Assuming only &#39;add new task&#39; is supported<br>   task_content TEXT,<br>   created_at TIMESTAMP NOT NULL DEFAULT NOW(),<br>   FOREIGN KEY (user_id) REFERENCES dim_users(id),<br>   FOREIGN KEY (plan_id) REFERENCES dim_plans(id)</pre><p>Then the tables will be added to the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ltY0qRAsN3SOis1E" /></figure><p><strong>Define the schema.graphql</strong></p><p>Schema.graphql, this file refers to the GraphQL schema, we can install this GraphQL extension for file highlighting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*M8UMNl-f2gpGcCQ8" /><figcaption>GraphQL extension in VSCode</figcaption></figure><p>There are two operations, one is <strong>Query</strong>, the other is <strong>Mutation</strong>. And we will need to define these operations.</p><p>Before we define them, think about <strong>what we are going to query</strong> and <strong>what we are going to insert</strong>.</p><pre>type User {<br> id: ID!<br> userName: String!<br> createdAt: String!<br> activities: [Activity]<br>}<br><br><br>type Plan {<br> id: ID!<br> createdAt: String!<br> activities: [Activity]<br>}<br><br><br>type Activity {<br> sessionId: ID!<br> user: User!<br> plan: Plan!<br> eventType: String!<br> taskContent: String!<br> createdAt: String!<br>}<br><br><br># Queries and Mutations<br><br><br>type Query {<br> # Find plans on a specific day. Returns all plans created on that day.<br> findPlanOnSpecificDay(day: String!, userId: ID!): [Plan]<br>}<br><br><br>type Mutation {<br> # Inserts a new plan and links it to a user. The mutation also assumes<br> # the creation of an initial activity (e.g., &#39;add new task&#39;) for the plan.<br> insertNewPlan(<br>   userId: ID!,<br>   createdAt: String!,<br>   eventType: String!,<br>   taskContent: String!<br> ): Plan<br>}</pre><p><strong>Backend</strong></p><p>Now we can move on to the backend construction. What we need to do is to create <strong>data models</strong> and define <strong>resolvers</strong> for the operations.</p><p>We create data models using SQLAlchemy to facilitate the operation in Python.</p><pre>from sqlalchemy import create_engine, Column, Text, Boolean, Integer, String, DateTime, func,ForeignKey, TIMESTAMP<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import sessionmaker<br>from sqlalchemy.exc import SQLAlchemyError<br>import datetime<br>from sqlalchemy import func<br>from datetime import datetime, timedelta<br>from ariadne import gql, QueryType, MutationType, make_executable_schema, load_schema_from_path, graphql_sync<br>from ariadne import load_schema_from_path, make_executable_schema<br>from ariadne.asgi import GraphQL<br><br><br><br><br>Base = declarative_base()<br><br><br>class DIMUser(Base):<br>   __tablename__ = &#39;dim_users&#39;  # Use lowercase to match PostgreSQL&#39;s default behavior<br>  <br>   id = Column(Integer, primary_key=True)<br>   user_name = Column(String(255))<br>   created_at = Column(TIMESTAMP, nullable=False)<br>  <br>class DIMPlans(Base):<br>   __tablename__ = &#39;dim_plans&#39;<br>  <br>   id = Column(Integer, primary_key=True, autoincrement=True)<br>   created_at = Column(TIMESTAMP, nullable=False)<br><br><br>class Activity(Base):<br>   __tablename__ = &#39;activity&#39;  # Table name in lowercase<br>  <br>   session_id = Column(Integer, primary_key=True, autoincrement=True)<br>   user_id = Column(Integer, ForeignKey(&#39;dim_users.id&#39;))  # Correct FK reference to &#39;dim_users.id&#39;<br>   plan_id = Column(Integer, ForeignKey(&#39;dim_plans.id&#39;))  # Correct FK reference to &#39;dim_plans.id&#39;<br>   event_type = Column(String(255), nullable=False)<br>   task_content = Column(Text)<br>   created_at = Column(TIMESTAMP, nullable=False)<br><br><br># Connect to your PostgreSQL database<br>DATABASE_URL = &quot;postgresql://postgres:password@localhost:5432/daily_planning&quot;<br>engine = create_engine(DATABASE_URL)<br># Base.metadata.drop_all(bind=engine)<br>Session = sessionmaker(bind=engine)</pre><p>When defining the GraphQL resolver, remember that the @query/mutation.field should be exactly the same as what you defined in the GraphQL schema. For example, @query.field(“findPlanOnSpecificDay”)</p><pre># define resolvers<br># Create QueryType and MutationType instances<br>query = QueryType()<br>mutation = MutationType()<br><br><br><br><br>@query.field(&quot;findPlanOnSpecificDay&quot;)<br>def resolve_find_plan(_, info, userId, day):<br>   &quot;&quot;&quot;<br>   Finds activities for a specific user on a specific day.<br>  <br>   :param _: Unused parameter, convention for GraphQL resolvers.<br>   :param info: Provides context for the GraphQL query (unused here).<br>   :param userId: The ID of the user to find activities for.<br>   :param day: The day to find activities on, provided as &#39;YYYY-MM-DD&#39;.<br>   :return: A list of Activity objects for the user on the specified day.<br>   &quot;&quot;&quot;<br>   # Convert the input day string to a datetime object representing the start and end of the day<br>   day_start = datetime.strptime(day, &quot;%Y-%m-%d&quot;)<br>   day_end = day_start + timedelta(days=1)<br><br><br>   # Create a new database session<br>   session = Session()<br><br><br>   try:<br>       # Query for activities by a specific user within the specified day<br>       activities = session.query(Activity)\<br>                           .filter(Activity.user_id == userId)\<br>                           .filter(Activity.created_at &gt;= day_start)\<br>                           .filter(Activity.created_at &lt; day_end)\<br>                           .all()<br>   finally:<br>       # Ensure the session is closed after the operation<br>       session.close()<br><br><br>   return activities<br>  <br>  <br>@mutation.field(&quot;insertNewPlan&quot;)<br>def resolve_insert_new_plan(_, info, userId, createdAt, eventType, taskContent):<br>   &quot;&quot;&quot;<br>   Inserts a new plan linked to a user and creates an initial activity for the plan.<br><br><br>   Parameters:<br>   - userId (ID!): The ID of the user the new plan is associated with.<br>   - createdAt (String!): The creation time for the plan and activity, provided as a string.<br>   - eventType (String!): The type of the initial activity.<br>   - taskContent (String!): The content of the task for the initial activity.<br><br><br>   Returns:<br>   - A dictionary with &#39;plan_id&#39; of the newly created Plan.<br>   &quot;&quot;&quot;<br>   created_at_datetime = datetime.strptime(createdAt, &quot;%Y-%m-%d %H:%M:%S&quot;)<br>  <br>   session = Session()<br>   try:<br>       # Create and add a new Plan to the session<br>       new_plan = DIMPlans(created_at=created_at_datetime)<br>       session.add(new_plan)<br>       session.flush()  # Ensures the new plan gets an ID assigned<br><br><br>       # Create and add a new Activity linked to the new plan<br>       new_activity = Activity(<br>           user_id=userId,<br>           plan_id=new_plan.id,  # Correctly access new_plan&#39;s id attribute<br>           event_type=eventType,<br>           task_content=taskContent,<br>           created_at=created_at_datetime<br>       )<br>       session.add(new_activity)<br><br><br>       session.commit()<br>       # Correctly returning the ID of the new plan using dot notation<br>       return {&quot;plan_id&quot;: new_plan.id} <br>   except Exception as e:<br>       session.rollback()<br>       print(f&quot;An error occurred: {e}&quot;)  # It&#39;s better to log errors<br>       return {&quot;error&quot;: &quot;Failed to insert new plan.&quot;}<br>   finally:<br>       session.close()<br><br><br><br><br># Load schema from .graphql file<br>type_defs = load_schema_from_path(&quot;schema.graphql&quot;)<br># Make the executable schema<br>schema = make_executable_schema(type_defs, query, mutation)<br>graphql_app = GraphQL(schema, debug=True)</pre><p><strong>Application</strong></p><p>You can separate the data models and the resolvers in different scripts.</p><p>Finally, we need an application to enable the task creation and retrieval.</p><p>Here I use streamlit as it’s easy. We need to insert a user id into the database first to ensure that the current user exists. I will use my favorite number 2009. You can include more operations to insert the user information automatically. I’m just inserting for convenience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X0fT9X7bhevaVDNH" /><figcaption>Insert the user data</figcaption></figure><p>I will design a simple application UI with streamlit. And we need to import the resolvers defined.</p><pre>import streamlit as st<br>from backend import resolve_find_plan, resolve_insert_new_plan   # Import the resolver<br>from uuid import UUID<br>from datetime import datetime<br>from dateutil import parser<br><br><br># Streamlit UI<br>st.title(&quot;Add Plans to My Schedule Today&quot;)<br><br><br># Streamlit UI for Adding New Plans<br>st.header(&quot;Add a New Plan&quot;)<br><br><br># Form for new plan data<br>with st.form(key=&#39;new_plan_form&#39;):<br>   user_id = st.number_input(&quot;User ID&quot;, min_value=1, value=2009, format=&quot;%d&quot;)<br>   created_at = st.text_input(&quot;Creation Date and Time (YYYY-MM-DD HH:MM:SS)&quot;, value=datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;))<br>   event_type = st.text_input(&quot;Event Type&quot;, value=&quot;add new task&quot;)<br>   task_content = st.text_area(&quot;Task Content&quot;)<br>  <br>   # Submit button for the form<br>   submit_button = st.form_submit_button(label=&#39;Insert New Plan&#39;)<br><br><br>if submit_button:<br>   try:<br>       # Inserting the new plan using the resolver<br>       new_plan = resolve_insert_new_plan(None, None, int(user_id), created_at, event_type, task_content)<br>      <br>       # Displaying a success message<br>       st.success(f&quot;Successfully added new plan with ID: {new_plan[&#39;plan_id&#39;]}&quot;)<br>   except Exception as e:<br>       st.error(f&quot;Error adding new plan: {e}&quot;)<br><br><br><br><br><br><br># Streamlit UI for Querying Historical Plans<br>st.header(&quot;Query Historical Plans&quot;)<br><br><br># User input for user ID<br>user_id_query = 2009<br><br><br># User input for date<br>date_query = st.text_input(&quot;Enter date (YYYY-MM-DD) to query plans:&quot;, value=datetime.now().strftime(&quot;%Y-%m-%d&quot;))<br><br><br># Button to trigger the query<br>if st.button(&#39;Query Plans&#39;):<br>   try:<br>       # Parsing the user input to date<br>       date = parser.parse(date_query).strftime(&quot;%Y-%m-%d&quot;)<br>      <br>       # Using the resolver to query plans based on user ID and date<br>       activities = resolve_find_plan(None, None, user_id_query, date)<br>      <br>       # Display the activities<br>       if activities:<br>           for activity in activities:<br>               st.write(f&quot;Activity Session ID: {activity.session_id}, Created At: {activity.created_at.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)}, Task Content: {activity.task_content}&quot;)<br>       else:<br>           st.write(&quot;No activities found for this user on the specified date.&quot;)<br>   except Exception as e:<br>       st.error(f&quot;Error querying activities: {e}&quot;)</pre><p>Run streamlit run app.py under this project directory. And you will be able to see the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LTIvt3867nd2UW-J" /><figcaption>insert data to the application</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AiWEO8fAjmKnNizz" /><figcaption>fetch the historical records</figcaption></figure><p>Thank you for reading! Please do let me know if you have any questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/1*96PlOfZ9qWEQ9GwTCcJjPw.jpeg" /><figcaption>jiayoua</figcaption></figure><p>codebase: <a href="https://github.com/Alleria1809/GraphQL-Python">https://github.com/Alleria1809/GraphQL-Python</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c35cb898a25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science for DOTA2(PART 2 — Winning Camp Prediction based on Draft)]]></title>
            <link>https://medium.com/@xiaoyigu/data-science-for-dota2-part-2-winning-camp-prediction-based-on-draft-bf1e56346cca?source=rss-57eb0aee8b95------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf1e56346cca</guid>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Alleria]]></dc:creator>
            <pubDate>Tue, 23 May 2023 04:07:34 GMT</pubDate>
            <atom:updated>2023-05-23T04:07:34.444Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Science for DOTA2(PART 2 — Winning Camp Prediction based on Draft)</h3><p><strong>Keywords:</strong> EDA, Graph Embedding, Feature Engineering, Prediction Models(Logistic Regression, Decision Tree, Random Forest, XGBoosting)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AH4qaXVuayaA-hevdXiU-Q.jpeg" /><figcaption>One draft PSG.LGD selected inTI10</figcaption></figure><p>After analyzing the heroes, next, I would like to apply EDA to the matches and build the prediction model. To gather as much data as possible, I used the method described in <a href="https://medium.com/@xiaoyigu/data-science-for-dota2-part-1-data-collection-55d7d7cb07c1">PART 1</a> to collect more games with the Opendota API. This time altogether I have 25927 records and these data will be uploaded once I compile everything.</p><blockquote>EDA</blockquote><p>First of all, I have a file for the team metadata and a file for the detailed player data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFR5GXarp74cVYVJNK1CZw.png" /><figcaption>Team Metadata</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oAcFVvhM0MitNk2H6WE-Q.png" /><figcaption>Player Data</figcaption></figure><p>Here we can combine the team metadata and the information of each player together using <em>the pandas merge method(below)</em> and the player data will also have the metadata.</p><pre>player_df = player_df.merge(team_df, on=&#39;match_id&#39;)<br>player_df.head()</pre><p>Information of team metadata:</p><pre>team_df.info()<br>&quot;&quot;&quot;<br>RangeIndex: 25927 entries, 0 to 25926<br>Data columns (total 9 columns):<br> #   Column         Non-Null Count  Dtype <br>---  ------         --------------  ----- <br> 0   match_id       25927 non-null  int64 <br> 1   start_time     25927 non-null  object<br> 2   duration       25927 non-null  int64 <br> 3   game_mode      25927 non-null  int64 <br> 4   win_camp       25927 non-null  object<br> 5   radiant_hero   25927 non-null  object<br> 6   dire_hero      25927 non-null  object<br> 7   radiant_score  25927 non-null  int64 <br> 8   dire_score     25927 non-null  int64 <br>dtypes: int64(5), object(4)<br>memory usage: 1.8+ MB<br>&quot;&quot;&quot;</pre><p>We have the match_id, start_time, duration of the game, game_mode, win_camp, radiant hero set, dire hero set, and the final radiant/dire scores. We can look at the game mode first. The game mode dictionary is — -</p><p>22: ALL DRAFT, 23: TURBO, 3: RANDOM DRAFT, 13: LIMITED HEROES, 4: SINGLE DRAFT, 18: ABILITY DRAFT, 1: ALL PICK, 2: CAPTAINS MODE, 21: SOLO. ALL DRAFT means the players can pick any hero. TURBO is an accelerated version of the normal game, which means you will get resources faster than usual. RANDOM DRAFT(RD) means the players can only choose heroes in a randomly selected hero pool(limited number of heroes). LIMITED HEROES: this also means choosing a hero in a limited hero pool. SINGLE DRAFT: Players pick from a pool of one Strength attribute symbol Strength hero, one Agility attribute symbol Agility hero, one Intelligence attribute symbol Intelligence hero, and one Universal attribute symbol Universal hero. Each player gets different randomly assigned heroes. ABILITY DRAFT: Play a hero with four abilities selected from a random pool of abilities. ALL PICK(AP): Choose from the full hero pool. Players can choose any hero, random a hero, or swap heroes with teammates. CAPTAINS MODE: Each team’s captain bans and chooses heroes for the team. Captains mode is the standard format for tournament games. The captains ban certain heroes, up to seven per team, preventing either team from picking the hero. SOLO: two players battle on the mid lane.</p><p>Generally, ALL DRAFT/AP/CAPTAINS MODE will be more informative because all the heroes will be included. So I use the data of these modes next for the models. Let’s have a look at the distribution of the modes.</p><pre>team_df.game_mode.value_counts()<br>&quot;&quot;&quot;<br>22    16573<br>23     5686<br>3      1113<br>13      928<br>4       909<br>1       368<br>18      343<br>2         4<br>21        3<br>Name: game_mode, dtype: int64<br>&quot;&quot;&quot;</pre><pre>mode_map = {22:&quot;ALL DRAFT&quot;, 23:&quot;TURBO&quot;, 3:&quot;RANDOM DRAFT&quot;, 13:&quot;LIMITED HEROES&quot;, 4:&quot;SINGLE DRAFT&quot;, 18:&quot;ABILITY DRAFT&quot;, 1:&quot;ALL PICK&quot;, 2:&quot;CAPTAINS MODE&quot;, 21:&quot;SOLO&quot;}<br>mode_list = []<br># mode_color_map = dict(zip(range(8), list(mode_map.values())))<br>for mode in team_df.game_mode.value_counts().keys():<br>    mode_list.append(mode_map[mode])<br>fig, ax = plt.subplots(figsize=(8, 4))<br>mode_count_df = pd.DataFrame({<br>    &#39;game_mode&#39;: team_df.game_mode.value_counts().keys(),<br>    &#39;count&#39;: team_df.game_mode.value_counts().values<br>})<br># set the mode id as string<br>mode_count_df[&#39;game_mode&#39;] = mode_count_df[&#39;game_mode&#39;].astype(str)<br>sns.barplot(data=mode_count_df, x=&quot;game_mode&quot;, y=&quot;count&quot;, ax=ax)<br>plt.xticks(rotation=90, fontsize=10)<br>plt.title(&#39;Count of Different Game Mode&#39;)<br>handles = []<br>for idx, value in enumerate(mode_list):<br>    patch = mpatches.Patch(color=color_list[idx], label=value)<br>    handles.append(patch)<br>plt.legend(handles=handles)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*wUUcIgMkIGIpsiE6UQ_fZQ.png" /><figcaption>Count of Different Game Modes</figcaption></figure><p>ALL DRAFT accounts for the largest number of games while SOLO accounts for the smallest. I select the captain mode, all pick and all draft only for the analysis.</p><pre># keep captain mode, all pick  and all draft<br># # GAMEMODE: 22:ALL DRAFT, 23:TURBO, 3:RANDOM DRAFT, 13:LIMITED HEROES, 4:SINGLE DRAFT, 18:ABILITY DRAFT, 1:ALL PICK, 2:CAPTAINS MODE<br>team_df = team_df[(team_df.game_mode==22) | (team_df.game_mode==2) | (team_df.game_mode==1)].reset_index(drop=True)<br>filtered_player_df = player_df.loc[(player_df[&#39;game_mode&#39;]==22) | (player_df[&#39;game_mode&#39;]==2) | (player_df[&#39;game_mode&#39;]==1)]</pre><p>After filtering the game mode, we have 16945 games. Then I want to look at the rank tiers of the players.</p><pre>fig, ax = plt.subplots(figsize=(8, 4))<br>sns.countplot(x = filtered_player_df[&#39;rank_tier&#39;], ax=ax)<br>plt.xticks(rotation=90, fontsize=10)<br>plt.title(&#39;Count of Different Rank Tier&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*7ziPQ3GguY0m4swPNzcxgQ.png" /><figcaption>Count of Different Rank Tier</figcaption></figure><p>As you can see, in these games, the rank tier of the players almost has a normal distribution, but there are a lot of players with a rank tier of 80+.</p><p>For the game start time, all of these data are from 2023/05/13. The latest major version of DOTA2 is updated in April, so the games I collected are up-to-date. And I believe that the players in the data have a better understanding of the strategies and the heroes. So the future prediction based on these data will be more reliable. Next, we can check the duration of the games.</p><pre>fig, ax = plt.subplots(figsize=(8, 4))<br>sns.histplot(data=team_df, x=&quot;duration&quot;)<br>plt.xticks(rotation=90, fontsize=10)<br>plt.title(&#39;Duration Distribution of the Matches(minutes)&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*bfB3jBroXAlPwMYdRcwaTQ.png" /><figcaption>Duration Distribution of the Matches(minutes)</figcaption></figure><p>Most of the games are around 30–50 minutes. Sometimes, the game only lasts 0 minutes. Probably because some players leave the game at the beginning. Sometimes the game is quite long, e.g. over 80 minutes, which means that the game is tough and maybe the performances of the two camps are very close. Then, I want to see the distribution of different winning camps.</p><pre>fig, ax = plt.subplots(figsize=(8, 4))<br>sns.countplot(x = team_df[&#39;win_camp&#39;], ax=ax)<br>plt.xticks(rotation=90, fontsize=10)<br>plt.title(&#39;Count of Different Rank Tier&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*zY4GhZCdKDJERAe5EMxp0A.png" /><figcaption>Count of Different Winning Camps</figcaption></figure><p>The number of victories in the radiant camp is a little bit larger than in the dire. And we may also look at the winning rate of each hero.</p><pre># select the first 5 hero and win rate<br>hero_win_rate_df = filtered_player_df.groupby([&#39;hero_id&#39;])[&#39;win&#39;].mean().reset_index()<br>hero_win_rate_df = hero_win_rate_df.sort_values(by=&#39;win&#39;, ascending=False)<br># hero_win_rate_df.head()<br><br>heroes_df = pd.read_csv(&#39;all_heroes.csv&#39;)<br>hero_id_to_name = dict(zip(heroes_df[&#39;hero_id&#39;].values, heroes_df[&#39;official_name&#39;].values))<br>hero_win_rate_df[&#39;hero_name&#39;] = hero_win_rate_df[&#39;hero_id&#39;].apply(lambda x:hero_id_to_name[x])<br>hero_win_rate_df.hero_id = hero_win_rate_df.hero_id.astype(str)<br>&quot;&quot;&quot;<br>hero_id win hero_name<br>92 94 0.580744 Medusa<br>80 82 0.560825 Meepo<br>102 104 0.558762 Legion Commander<br>106 108 0.558590 Underlord<br>73 75 0.556023 Silencer<br>&quot;&quot;&quot;</pre><p>In our 16,000+ matches, Medusa is the hero with the highest winning rate.</p><pre>fig, ax = plt.subplots(figsize=(8, 4))<br>sns.barplot(data=hero_win_rate_df, x=&quot;hero_id&quot;, y=&quot;win&quot;, ax=ax)<br>plt.xticks(fontsize=5, rotation = 90)<br>plt.title(&#39;Win Rate Distribution for Each Hero&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*WUJQDmN00EIBLy42wE5F7Q.png" /><figcaption>Win Rate Distribution for Each Hero</figcaption></figure><p>I also want to see the winning rate of some heroes in different camps.</p><pre>hero_df_by_camp = filtered_player_df.groupby([&#39;hero_id&#39;, &#39;camp&#39;])[&#39;win&#39;].mean().reset_index()<br>hero_df_by_camp[&#39;hero_name&#39;] = hero_df_by_camp[&#39;hero_id&#39;].apply(lambda x:hero_id_to_name[x])<br># hero_df_by_camp = hero_df_by_camp.sort_values(by=&#39;win&#39;, ascending=False)<br>sns.barplot(data=hero_df_by_camp.head(20), x=&quot;hero_name&quot;, y=&quot;win&quot;, hue=&#39;camp&#39;)<br>plt.xticks(fontsize=10, rotation = 90)<br>plt.ylabel(&#39;win_rate&#39;)<br>plt.title(&#39;Heroes and Their Win Rate in Different Camps(20 samples)&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*7f9nhK3bMrG7kN624Xnkjg.png" /><figcaption>Heroes and Their Win Rate in Different Camps(20 samples)</figcaption></figure><p>In these 20 examples, generally, the heroes will have a higher winning rate in the radiant. But sometimes the radiant camp wins more. Then, I want to generate different hero pairs and look into the winning rate of each pair of heroes.</p><pre>def get_hero_pair_win(team_df):<br>    hero_pairs = []<br>    for _, row in team_df.iterrows():<br>        # prevent some nan ids that cause errors<br>        r_heroes = row.radiant_hero<br>        rd_split = str(r_heroes).split(&#39;, &#39;)<br>        for i, item in enumerate(rd_split):<br>            if &#39;nan]&#39; in item:<br>                rd_split[i] = rd_split[i].replace(&#39;nan&#39;, &#39;0&#39;)<br>        r_heroes = &#39;,&#39;.join(rd_split)<br>        <br>        d_heroes = row.dire_hero<br>        dd_split = str(d_heroes).split(&#39;, &#39;)<br>        for i, item in enumerate(dd_split):<br>            if &#39;nan]&#39; in item:<br>                dd_split[i] = dd_split[i].replace(&#39;nan&#39;, &#39;0&#39;)<br>        d_heroes = &#39;,&#39;.join(dd_split)<br>    <br>        # generate the list of heroes in radiant<br>        r_heroes = list(ast.literal_eval(r_heroes).keys())<br>        # generate the pair combinations<br>        r_hero_pairs = list(combinations(r_heroes,2))<br>        for pair in r_hero_pairs:<br>            hero_pair = {}<br>            # get the number of victory<br>            if row[&#39;win_camp&#39;] == &#39;radiant&#39;:<br>                hero_pair[pair] = 1<br>            else:<br>                hero_pair[pair] = 0<br>            hero_pairs.append(hero_pair)<br><br>        # generate the list of heroes in dire<br>        d_heroes = list(ast.literal_eval(d_heroes).keys())<br>        # generate the pair combinations<br>        d_hero_pairs = list(combinations(d_heroes,2))<br>        for pair in d_hero_pairs:<br>            hero_pair = {}<br>            # get the number of victory<br>            if row[&#39;win_camp&#39;] == &#39;radiant&#39;:<br>                hero_pair[pair] = 0<br>            else:<br>                hero_pair[pair] = 1<br>            hero_pairs.append(hero_pair)<br><br>    hero1, hero2, is_win = [], [], []<br>    for item in hero_pairs:<br>        # print(item) # {(&#39;Earthshaker&#39;, &#39;Bloodseeker&#39;): 1}<br>        hero_pair = list(item.keys())[0]<br>        <br>        win = list(item.values())[0]<br>        <br>        hero1.append(hero_name_to_id[hero_pair[0]])<br>        hero2.append(hero_name_to_id[hero_pair[1]])<br>        is_win.append(win)<br><br>        # print(hero_pair)<br>        <br>    hero_win_df = pd.DataFrame({<br>    &#39;hero1&#39;: hero1,<br>    &#39;hero2&#39;: hero2,<br>    &#39;is_win&#39;: is_win<br>    })<br>    return hero_win_df<br>hero_name_to_id = dict(zip(heroes_df[&#39;official_name&#39;].values, heroes_df[&#39;hero_id&#39;].values))<br><br># generate the paired winning rate<br>hero_pair_win_df = get_hero_pair_win(team_df)<br><br># we need to group by the two heroes ignoring the order of hero1 and hero2<br>hero_pair_win_df[[&#39;hero1&#39;, &#39;hero2&#39;]] = np.sort(hero_pair_win_df[[&#39;hero1&#39;, &#39;hero2&#39;]], axis=1)<br>hero_pair_win_df_grouped = hero_pair_win_df.groupby([&#39;hero1&#39;, &#39;hero2&#39;]).mean().reset_index()<br># hero_pair_win_df_grouped = hero_pair_win_df.groupby([&#39;hero1&#39;, &#39;hero2&#39;]).mean().reset_index()<br>hero_pair_win_pivot = hero_pair_win_df_grouped.pivot(index=&#39;hero1&#39;, columns=&#39;hero2&#39;, values=&#39;is_win&#39;)<br><br>sns.heatmap(hero_pair_win_pivot, cmap=&quot;flare&quot;)<br>plt.title(&#39;Win Rate Heatmap Across the Hero Pairs&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*vBeMfH-maNxe8CEZZuUeKg.png" /><figcaption>Win Rate Heatmap Across the Hero Pairs</figcaption></figure><p>As we can see, pair (94, 137) has a winning rate of 0.613, which means that Medusa and Primal Beast together will have a 61.3% win rate. But it’s better to look at the number of games when these two heroes are selected in the same camp. I have already removed the order of hero1 and hero2 so we only need to check hero1=94 and hero2=137.</p><pre>hero_pair_win_df[(hero_pair_win_df.hero1==94) &amp; (hero_pair_win_df.hero2==137)]<br><br>&quot;&quot;&quot;<br>an subset of the result<br>hero1 hero2 is_win<br>200 94 137 1<br>6361 94 137 0<br>20393 94 137 1<br>24475 94 137 0<br>31014 94 137 1<br>35147 94 137 1<br>44935 94 137 0&quot;&quot;&quot;<br><br>count = len(hero_pair_win_df[(hero_pair_win_df.hero1==94) &amp; (hero_pair_win_df.hero2==137)])<br>print(f&#39;Total number of games with Medusa and Primal Beast in the same camp = {count}&#39;)<br># Total number of games with Medusa and Primal Beast in the same camp = 31<br><br>win_sum = hero_pair_win_df[(hero_pair_win_df.hero1==94) &amp; (hero_pair_win_df.hero2==137)].is_win.sum()<br>print(f&#39;Total winning games with Medusa and Primal Beast in the same camp = {win_sum}&#39;)<br># Total winning games with Medusa and Primal Beast in the same camp = 19</pre><p>So we have 31 games when Medusa and Primal Beast are in the same camp and in the 31 games, we have around 19 victories.</p><blockquote>Prediction Model</blockquote><p>For the prediction model, actually, Valve has an inbuilt model in DOTA2. It takes a lot of aspects into consideration such as the draft, the current score of each camp, the accumulated gold, the accumulated experience point, and so on. My idea is simpler: I want to build an immediate prediction during the draft session, completely depending on what we can know before the game starts. Unlike DOTA1, DOTA2 relies more and more on the draft. And my objective is to help the players/coaches pick the better draft.</p><p>Feature Engineering</p><p>To select the features, I searched some papers. <a href="https://cs229.stanford.edu/proj2013/PerryConley-HowDoesHeSawMeARecommendationEngineForPickingHeroesInDota2.pdf"><em>How Does He Saw Me? A Recommendation Engine for Picking Heroes in Dota 2</em></a>, and <a href="https://cseweb.ucsd.edu/classes/wi15/cse255-a/reports/wi15/Kaushik_Kalyanaraman.pdf"><em>To Win or Not to Win? A prediction model to determine the outcome of a DotA2 match</em></a><em>, the authors mainly used a large vector to represent each game</em>. For example, the first paper(Stanford) used 100+ dimensions for hero ids in the radiant and the other 100+ dimensions for hero ids in the dire. Each match will have over 200 dimensions. If the hero appears, its hero id will be 1, else 0. The samples will finally contain 10 “1”s and become very sparse. Besides, they develop a metric for the overall probability: 1. get the radiant victory prob; 2. reverse the draft and get the dire victory prob; 3. res = avg(radiant_prob + (1-dire_prob)). However, in DOTA2, the map is asymmetric. Especially before the latest version(7.33), the control of ROSHAN(a boss dropping specific items when killed in the game) and other resources are different for the radiant and the dire. Therefore, I still convert the problem into a binary classification task. If the radiant wins, then the target variable is 1, else 0. I decided not to use the features in these two papers because as mentioned, the data will be sparse for the model. Besides, these methods don’t exploit the detailed information of the heroes actually.</p><p>Then, in<a href="https://dl.acm.org/doi/10.1145/3208788.3208800"><em> Outcome prediction of DOTA2 using machine learning methods</em></a>, the authors used the hero attributes to predict the winning camp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_EG7whTDbxcRVZNAaG_zQ.png" /><figcaption>The heroes’ features</figcaption></figure><p>Their features take the hero attributes into consideration and I will keep these features. But I won’t use the GPM as mentioned in the paper because my model is not real-time forecasting. It’s only to forecast after the draft. In the future, I will try to add these features based on each player and the previous performance when playing this hero. e.g. player features: rank tier. Later, other features such as items can also be considered.</p><p>After the literature review, I will build the following features:</p><p>1. attributes: including initial strength/agility/intelligence and gained strength/agility/intelligence.</p><p>2. hero features: role, attack type, primary attributes.</p><p>And I will follow the method of arranging features in this paper: to align the heroes with the same role in each camp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*If6eRw2oCt9RtJ-H2JYIbQ.png" /><figcaption>The method of representing the heroes’ draft</figcaption></figure><p>Training Data Preprocessing</p><pre>data_df = team_df<br>print(f&quot;Total number of matches = {len(data_df)}.&quot;)<br># Total number of matches = 16945.</pre><p>I build the hero vectors — — the hero attributes.</p><pre>hero_map = {}<br>for hero in heroes_df.official_name:<br>    # hero_map[hero] = []<br>    row = heroes_df[heroes_df[&#39;official_name&#39;]==hero]<br>    hero_map[hero] = [row.attribute.values[0], row.attack_type.values[0], row.base_strength.values[0], \<br>        row.add_strength.values[0], row.lvl30_strength.values[0],row.base_agility.values[0], row.add_agility.values[0], \<br>            row.lvl30_agility.values[0], row.base_intelligence.values[0], row.add_intelligence.values[0], row.lvl30_intelligence.values[0]]<br>hero_map[&#39;Ogre Magi&#39;]<br># [&#39;Strength&#39;, &#39;Melee&#39;, 23.0, 4.2, 144.8, 14.0, 1.5, 57.5, 0.0, 0.0, 0.0]</pre><p>Then I record the heroes and their roles correspondingly.</p><pre># record heroes and their roles<br>radiant_roles = []<br>dire_roles = []<br>win_camp = data_df.win_camp<br>match_ids = data_df.match_id<br><br>for idx, row in data_df.iterrows():<br>    <br>    # prevent some nan ids that cause errors<br>    radiant_dict = row.radiant_hero<br>    rd_split = str(radiant_dict).split(&#39;, &#39;)<br>    for i, item in enumerate(rd_split):<br>        if &#39;nan]&#39; in item:<br>            rd_split[i] = rd_split[i].replace(&#39;nan&#39;, &#39;0&#39;)<br>    radiant_dict = &#39;,&#39;.join(rd_split)<br>    <br>    dire_dict = row.dire_hero<br>    dd_split = str(dire_dict).split(&#39;, &#39;)<br>    for i, item in enumerate(dd_split):<br>        if &#39;nan]&#39; in item:<br>            dd_split[i] = dd_split[i].replace(&#39;nan&#39;, &#39;0&#39;)<br>    dire_dict = &#39;,&#39;.join(dd_split)<br>    <br>    radiant_dict = ast.literal_eval(radiant_dict)<br>    dire_dict = ast.literal_eval(dire_dict)<br>    <br>    rrole_dict = {}<br>    drole_dict = {}<br>    <br>    for hero in radiant_dict:<br>        rrole_dict[hero] = radiant_dict[hero][0]<br>    for hero in radiant_dict:<br>        drole_dict[hero] = radiant_dict[hero][0]<br>    <br>    radiant_roles.append(rrole_dict)<br>    dire_roles.append(drole_dict)</pre><p>I will ignore the matches with incomplete roles. Only the games with 5 full roles in each camp will be kept.</p><pre>def cmp(full_roles, roles):<br>    # find the role between current roles and the full roles in a team<br>    diff = []<br>    for role in full_roles:<br>        if role not in roles:<br>            diff.append(role)<br>    return diff<br><br>def append_attr(hero, row, hero_map):<br>    # add attributes for each hero<br>    attributes = hero_map[hero]<br>    for att in attributes:<br>        row.append(att)<br>    return row<br><br>r_carry = []<br>r_mid = []<br>r_off = []<br>r_ss = []<br>r_hs = []<br><br>d_carry = []<br>d_mid = []<br>d_off = []<br>d_ss = []<br>d_hs = []<br><br>res = []<br>matches = []<br># count = 0<br>full_roles = [&#39;carry&#39;, &#39;hard_support&#39;, &#39;mid&#39;, &#39;offlane&#39;, &#39;soft_support&#39;]<br><br>for i, radiant_role in enumerate(radiant_roles):<br>    <br>    rroles = list(radiant_role.values())<br>    rdiff = cmp(full_roles, rroles)<br>    <br>    dire_role = dire_roles[i]<br>    droles = list(dire_role.values())<br>    ddiff = cmp(full_roles, droles)<br>    <br>    if not rdiff and not ddiff:<br>    # print(sorted(list(radiant_role.values())))<br>    # break<br>        matches.append(match_ids[i])<br>        res.append(win_camp[i])<br>        for hero, rrole in radiant_role.items():<br>            # role_list = radiant_roles.values<br>            if rrole==&#39;carry&#39;:<br>                r_carry.append(hero)<br>            elif rrole==&#39;mid&#39;:<br>                r_mid.append(hero)<br>            elif rrole==&#39;offlane&#39;:<br>                r_off.append(hero)<br>            elif rrole==&#39;soft_support&#39;:<br>                r_ss.append(hero)<br>            elif rrole==&#39;hard_support&#39;:<br>                r_hs.append(hero)<br>                <br>        for hero, drole in dire_role.items():<br>            if drole==&#39;carry&#39;:<br>                d_carry.append(hero)<br>            elif drole==&#39;mid&#39;:<br>                d_mid.append(hero)<br>            elif drole==&#39;offlane&#39;:<br>                d_off.append(hero)<br>            elif drole==&#39;soft_support&#39;:<br>                d_ss.append(hero)<br>            elif drole==&#39;hard_support&#39;:<br>                d_hs.append(hero)<br>    else:<br>        continue<br><br>rows = []<br>for i in range(len(r_carry)):<br>    row = [matches[i], res[i], r_carry[i]]<br>    row = append_attr(r_carry[i], row, hero_map)<br>    <br>    row.append(r_mid[i])<br>    row = append_attr(r_mid[i], row, hero_map)<br>    <br>    row.append(r_off[i])<br>    row = append_attr(r_off[i], row, hero_map)<br>    <br>    row.append(r_ss[i])<br>    row = append_attr(r_ss[i], row, hero_map)<br>    <br>    row.append(r_hs[i])<br>    row = append_attr(r_hs[i], row, hero_map)<br>    <br>    row.append(d_carry[i])<br>    row = append_attr(d_carry[i], row, hero_map)<br>    <br>    row.append(d_mid[i])<br>    row = append_attr(d_mid[i], row, hero_map)<br>    <br>    row.append(d_off[i])<br>    row = append_attr(d_off[i], row, hero_map)<br>    <br>    row.append(d_ss[i])<br>    row = append_attr(d_ss[i], row, hero_map)<br>    <br>    row.append(d_hs[i])<br>    row = append_attr(d_hs[i], row, hero_map)<br>    <br>    rows.append(row)<br><br>columns = [&#39;match_id&#39;, &#39;res&#39;]<br>for hero_role in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]:<br>    <br>    columns.append(f&quot;{hero_role}_id&quot;)<br>    columns.append(f&quot;{hero_role}_attribute&quot;)<br>    columns.append(f&quot;{hero_role}_attack_type&quot;)<br>    columns.append(f&quot;{hero_role}_str&quot;)<br>    columns.append(f&quot;{hero_role}_str_gain&quot;)<br>    columns.append(f&quot;{hero_role}_str_lvl30&quot;)<br>    columns.append(f&quot;{hero_role}_agi&quot;)<br>    columns.append(f&quot;{hero_role}_agi_gain&quot;)<br>    columns.append(f&quot;{hero_role}_agi_lvl30&quot;)<br>    columns.append(f&quot;{hero_role}_int&quot;)<br>    columns.append(f&quot;{hero_role}_int_gain&quot;)<br>    columns.append(f&quot;{hero_role}_int_lvl30&quot;)<br><br>combine_df = pd.DataFrame(<br>    columns=columns,<br>    data=rows<br>)<br><br>match_time_map = dict(zip(data_df.match_id, data_df.start_time))<br>combine_df[&#39;start_time&#39;] = combine_df[&#39;match_id&#39;].apply(lambda x:match_time_map[x])</pre><p>Let’s select the id, primary attribute, attack type, base attribute and attribute gain then.</p><pre>sub_columns = [&#39;match_id&#39;, &#39;res&#39;, &#39;start_time&#39;]<br>for hero_role in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]:<br>    <br>    sub_columns.append(f&quot;{hero_role}_id&quot;)<br>    sub_columns.append(f&quot;{hero_role}_attribute&quot;)<br>    sub_columns.append(f&quot;{hero_role}_attack_type&quot;)<br>    sub_columns.append(f&quot;{hero_role}_str&quot;)<br>    sub_columns.append(f&quot;{hero_role}_str_gain&quot;)<br>    # sub_columns.append(f&quot;{hero_role}_str_lvl30&quot;)<br>    sub_columns.append(f&quot;{hero_role}_agi&quot;)<br>    sub_columns.append(f&quot;{hero_role}_agi_gain&quot;)<br>    # sub_columns.append(f&quot;{hero_role}_agi_lvl30&quot;)<br>    sub_columns.append(f&quot;{hero_role}_int&quot;)<br>    sub_columns.append(f&quot;{hero_role}_int_gain&quot;)<br>    # sub_columns.append(f&quot;{hero_role}_int_lvl30&quot;)<br>len(sub_columns) # 93</pre><p>This is the compiled data:</p><pre>data = combine_df[sub_columns]<br>data<br><br>&quot;&quot;&quot;<br>match_id res start_time r_carry_id r_carry_attribute r_carry_attack_type r_carry_str r_carry_str_gain r_carry_agi r_carry_agi_gain r_carry_int r_carry_int_gain r_mid_id r_mid_attribute r_mid_attack_type r_mid_str r_mid_str_gain r_mid_agi r_mid_agi_gain r_mid_int r_mid_int_gain r_off_id r_off_attribute r_off_attack_type r_off_str r_off_str_gain r_off_agi r_off_agi_gain r_off_int r_off_int_gain r_ss_id r_ss_attribute r_ss_attack_type r_ss_str r_ss_str_gain r_ss_agi r_ss_agi_gain r_ss_int r_ss_int_gain r_hs_id r_hs_attribute r_hs_attack_type r_hs_str r_hs_str_gain r_hs_agi r_hs_agi_gain r_hs_int r_hs_int_gain d_carry_id d_carry_attribute d_carry_attack_type d_carry_str d_carry_str_gain d_carry_agi d_carry_agi_gain d_carry_int d_carry_int_gain d_mid_id d_mid_attribute d_mid_attack_type d_mid_str d_mid_str_gain d_mid_agi d_mid_agi_gain d_mid_int d_mid_int_gain d_off_id d_off_attribute d_off_attack_type d_off_str d_off_str_gain d_off_agi d_off_agi_gain d_off_int d_off_int_gain d_ss_id d_ss_attribute d_ss_attack_type d_ss_str d_ss_str_gain d_ss_agi d_ss_agi_gain d_ss_int d_ss_int_gain d_hs_id d_hs_attribute d_hs_attack_type d_hs_str d_hs_str_gain d_hs_agi d_hs_agi_gain d_hs_int d_hs_int_gain<br>0 7152113589 radiant 23-05-13 Medusa Agility Ranged 0.0 0.0 22.0 3.4 27.0 3.7 Bloodseeker Agility Melee 24.0 2.7 22.0 3.1 17.0 2.0 Necrophos Intelligence Ranged 18.0 2.3 12.0 1.3 21.0 2.7 Earthshaker Strength Melee 22.0 3.7 12.0 1.4 18.0 2.1 Oracle Intelligence Ranged 20.0 2.4 15.0 1.7 26.0 3.8 Medusa Agility Ranged 0.0 0.0 22.0 3.4 27.0 3.7 Bloodseeker Agility Melee 24.0 2.7 22.0 3.1 17.0 2.0 Necrophos Intelligence Ranged 18.0 2.3 12.0 1.3 21.0 2.7 Earthshaker Strength Melee 22.0 3.7 12.0 1.4 18.0 2.1 Oracle Intelligence Ranged 20.0 2.4 15.0 1.7 26.0 3.8<br>1 7152113590 dire 23-05-13 Sand King Universal Melee 22.0 2.7 19.0 1.8 19.0 1.8 Zeus Intelligence Ranged 19.0 2.1 11.0 1.2 22.0 3.3 Void Spirit Universal Melee 22.0 2.6 19.0 2.2 24.0 3.1 Bounty Hunter Agility Melee 20.0 2.5 21.0 2.6 22.0 1.9 Slark Agility Melee 20.0 1.9 21.0 1.5 16.0 1.7 Sand King Universal Melee 22.0 2.7 19.0 1.8 19.0 1.8 Zeus Intelligence Ranged 19.0 2.1 11.0 1.2 22.0 3.3 Void Spirit Universal Melee 22.0 2.6 19.0 2.2 24.0 3.1 Bounty Hunter Agility Melee 20.0 2.5 21.0 2.6 22.0 1.9 Slark Agility Melee 20.0 1.9 21.0 1.5 16.0 1.7<br>2 7152113591 radiant 23-05-13 Bristleback Strength Melee 22.0 2.5 17.0 1.8 14.0 2.8 Zeus Intelligence Ranged 19.0 2.1 11.0 1.2 22.0 3.3 Slark Agility Melee 20.0 1.9 21.0 1.5 16.0 1.7 Phoenix Universal Ranged 23.0 3.3 12.0 1.5 16.0 1.8 Sand King Universal Melee 22.0 2.7 19.0 1.8 19.0 1.8 Bristleback Strength Melee 22.0 2.5 17.0 1.8 14.0 2.8 Zeus Intelligence Ranged 19.0 2.1 11.0 1.2 22.0 3.3 Slark Agility Melee 20.0 1.9 21.0 1.5 16.0 1.7 Phoenix Universal Ranged 23.0 3.3 12.0 1.5 16.0 1.8 Sand King Universal Melee 22.0 2.7 19.0 1.8 19.0 1.8<br>3 7152113592 radiant 23-05-13 Windranger Universal Ranged 18.0 2.4 17.0 1.4 18.0 2.4 Ember Spirit Agility Melee 22.0 2.6 22.0 3.2 20.0 2.2 Rubick Intelligence Ranged 21.0 2.0 23.0 2.5 25.0 3.1 Medusa Agility Ranged 0.0 0.0 22.0 3.4 27.0 3.7 Mars Strength Melee 23.0 3.7 20.0 1.7 21.0 2.2 Windranger Universal Ranged 18.0 2.4 17.0 1.4 18.0 2.4 Ember Spirit Agility Melee 22.0 2.6 22.0 3.2 20.0 2.2 Rubick Intelligence Ranged 21.0 2.0 23.0 2.5 25.0 3.1 Medusa Agility Ranged 0.0 0.0 22.0 3.4 27.0 3.7 Mars Strength Melee 23.0 3.7 20.0 1.7 21.0 2.2<br>&quot;&quot;&quot;</pre><p>Let’s do a simple EDA here.</p><pre># simple EDA<br>data.res.value_counts()<br><br># radiant    8743 dire       8172</pre><p>The radiant and dire have a similar number of victories.</p><p>Which kind of carry will have a higher winning rate? Here I plot the carry attributes and the winning rate.</p><pre># total carry attribute distribution<br>from collections import Counter<br>dict(Counter(data.r_carry_attribute.tolist()+ data.d_carry_attribute.tolist()))<br><br>r_win_dict = data[data[&#39;res&#39;]==&#39;radiant&#39;].r_carry_attribute.value_counts()<br>d_win_dict = data[data[&#39;res&#39;]==&#39;dire&#39;].d_carry_attribute.value_counts()<br># r_win_dict,d_win_dict<br><br>r_attr_win_proportion = {}<br>d_attr_win_proportion = {}<br>total_dict = Counter(data.r_carry_attribute.tolist()+ data.d_carry_attribute.tolist())<br>r_win_dict = data[data[&#39;res&#39;]==&#39;radiant&#39;].r_carry_attribute.value_counts()<br>d_win_dict = data[data[&#39;res&#39;]==&#39;dire&#39;].d_carry_attribute.value_counts()<br><br>for attr, cnt in total_dict.items():<br>    r_pro = r_win_dict[attr] / cnt<br>    r_attr_win_proportion[attr] = r_pro<br>    <br>    d_pro = d_win_dict[attr] / cnt<br>    d_attr_win_proportion[attr] = d_pro<br>  <br># r_attr_win_proportion  <br>tmp_df = pd.DataFrame({&#39;attr&#39;:list(r_attr_win_proportion.keys()) + list(d_attr_win_proportion.keys()), \<br>    &#39;proportion&#39;:list(r_attr_win_proportion.values()) + list(d_attr_win_proportion.values()), \<br>    &#39;win&#39;: [&#39;radiant&#39;]*4 + [&#39;dire&#39;]*4})<br><br>sns.barplot(data=tmp_df,\<br>    x=&#39;attr&#39;, y=&#39;proportion&#39;, units=True, hue=&#39;win&#39;)<br>plt.title(&#39;Winning Rate for Different Attributes&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*TbrZZtQ12RcmeKQ_jcoe5A.png" /><figcaption>Winning Rate for Different Carry Attributes</figcaption></figure><p>As you can see, in the radiant, agility heroes and strength heroes have a higher proportion of victories while in the dire, that will be universal heroes and intelligence heroes. Then I encoded the categorical variables into numerical ones.</p><pre>win_map = {&#39;radiant&#39;:1, &#39;dire&#39;:0}<br>attribute_map = {&#39;Strength&#39;:0, &#39;Agility&#39;:1, &#39;Intelligence&#39;:2, &#39;Universal&#39;:3}<br>attack_map = {&#39;Melee&#39;:0, &#39;Ranged&#39;:1}<br><br>heroes_to_map = [f&quot;{x}_id&quot; for x in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]]<br>attr_to_map = [f&quot;{x}_attribute&quot; for x in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]]<br>attack_to_map = [f&quot;{x}_attack_type&quot; for x in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]]<br><br>for column in heroes_to_map:<br>    data[column] = data[column].apply(lambda x:hero_name_to_id[x])<br>for column in attr_to_map:<br>    data[column] = data[column].apply(lambda x:attribute_map[x])<br>for column in attack_to_map:<br>    data[column] = data[column].apply(lambda x:attack_map[x])<br><br>data[&#39;res&#39;] = data[&#39;res&#39;].map(win_map)<br><br>&quot;&quot;&quot;<br>match_id res start_time r_carry_id r_carry_attribute r_carry_attack_type r_carry_str r_carry_str_gain r_carry_agi r_carry_agi_gain r_carry_int r_carry_int_gain r_mid_id r_mid_attribute r_mid_attack_type r_mid_str r_mid_str_gain r_mid_agi r_mid_agi_gain r_mid_int r_mid_int_gain r_off_id r_off_attribute r_off_attack_type r_off_str r_off_str_gain r_off_agi r_off_agi_gain r_off_int r_off_int_gain r_ss_id r_ss_attribute r_ss_attack_type r_ss_str r_ss_str_gain r_ss_agi r_ss_agi_gain r_ss_int r_ss_int_gain r_hs_id r_hs_attribute r_hs_attack_type r_hs_str r_hs_str_gain r_hs_agi r_hs_agi_gain r_hs_int r_hs_int_gain d_carry_id d_carry_attribute d_carry_attack_type d_carry_str d_carry_str_gain d_carry_agi d_carry_agi_gain d_carry_int d_carry_int_gain d_mid_id d_mid_attribute d_mid_attack_type d_mid_str d_mid_str_gain d_mid_agi d_mid_agi_gain d_mid_int d_mid_int_gain d_off_id d_off_attribute d_off_attack_type d_off_str d_off_str_gain d_off_agi d_off_agi_gain d_off_int d_off_int_gain d_ss_id d_ss_attribute d_ss_attack_type d_ss_str d_ss_str_gain d_ss_agi d_ss_agi_gain d_ss_int d_ss_int_gain d_hs_id d_hs_attribute d_hs_attack_type d_hs_str d_hs_str_gain d_hs_agi d_hs_agi_gain d_hs_int d_hs_int_gain<br>0 7152113589 1 23-05-13 94 1 1 0.0 0.0 22.0 3.4 27.0 3.7 4 1 0 24.0 2.7 22.0 3.1 17.0 2.0 36 2 1 18.0 2.3 12.0 1.3 21.0 2.7 7 0 0 22.0 3.7 12.0 1.4 18.0 2.1 111 2 1 20.0 2.4 15.0 1.7 26.0 3.8 94 1 1 0.0 0.0 22.0 3.4 27.0 3.7 4 1 0 24.0 2.7 22.0 3.1 17.0 2.0 36 2 1 18.0 2.3 12.0 1.3 21.0 2.7 7 0 0 22.0 3.7 12.0 1.4 18.0 2.1 111 2 1 20.0 2.4 15.0 1.7 26.0 3.8<br>1 7152113590 0 23-05-13 16 3 0 22.0 2.7 19.0 1.8 19.0 1.8 22 2 1 19.0 2.1 11.0 1.2 22.0 3.3 126 3 0 22.0 2.6 19.0 2.2 24.0 3.1 62 1 0 20.0 2.5 21.0 2.6 22.0 1.9 93 1 0 20.0 1.9 21.0 1.5 16.0 1.7 16 3 0 22.0 2.7 19.0 1.8 19.0 1.8 22 2 1 19.0 2.1 11.0 1.2 22.0 3.3 126 3 0 22.0 2.6 19.0 2.2 24.0 3.1 62 1 0 20.0 2.5 21.0 2.6 22.0 1.9 93 1 0 20.0 1.9 21.0 1.5 16.0 1.7<br>2 7152113591 1 23-05-13 99 0 0 22.0 2.5 17.0 1.8 14.0 2.8 22 2 1 19.0 2.1 11.0 1.2 22.0 3.3 93 1 0 20.0 1.9 21.0 1.5 16.0 1.7 110 3 1 23.0 3.3 12.0 1.5 16.0 1.8 16 3 0 22.0 2.7 19.0 1.8 19.0 1.8 99 0 0 22.0 2.5 17.0 1.8 14.0 2.8 22 2 1 19.0 2.1 11.0 1.2 22.0 3.3 93 1 0 20.0 1.9 21.0 1.5 16.0 1.7 110 3 1 23.0 3.3 12.0 1.5 16.0 1.8 16 3 0 22.0 2.7 19.0 1.8 19.0 1.8<br>3 7152113592 1 23-05-13 21 3 1 18.0 2.4 17.0 1.4 18.0 2.4 106 1 0 22.0 2.6 22.0 3.2 20.0 2.2 86 2 1 21.0 2.0 23.0 2.5 25.0 3.1 94 1 1 0.0 0.0 22.0 3.4 27.0 3.7 129 0 0 23.0 3.7 20.0 1.7 21.0 2.2 21 3 1 18.0 2.4 17.0 1.4 18.0 2.4 106 1 0 22.0 2.6 22.0 3.2 20.0 2.2 86 2 1 21.0 2.0 23.0 2.5 25.0 3.1 94 1 1 0.0 0.0 22.0 3.4 27.0 3.7 129 0 0 23.0 3.7 20.0 1.7 21.0 2.2<br>&quot;&quot;&quot;</pre><p>For the attributes, we have 4 categories: strength, agility, intelligence, and universal. These 4 categories represent meanings at the same level. So I will use one-hot encoding for the attributes. For the attack types, we have 2 categories: melee and ranged. These 2 categories represent meanings at the same level just like males and females. So I will also use one-hot encoding. Actually, the hero ids also represent meanings at the same level, but if we use one-hot encoding, it will be very sparse and contain huge dimensions. So I will use one-hot encoding for the attributes.</p><pre>attr_columns = []<br>for hero_role in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]:<br>    attr_columns.append(f&quot;{hero_role}_attribute&quot;)<br>for col in attr_columns:<br>    tmp_df = pd.get_dummies(data[col], prefix=col)<br>    data = pd.concat([data, tmp_df], axis=1)<br>    data.drop([col], axis=1, inplace=True)<br><br>attack_type_columns = []<br>for hero_role in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]:<br>    <br>    attack_type_columns.append(f&quot;{hero_role}_attack_type&quot;)<br>for col in attack_type_columns:<br>    tmp_df = pd.get_dummies(data[col], prefix=col)<br>    data = pd.concat([data, tmp_df], axis=1)<br>    data.drop([col], axis=1, inplace=True)<br><br>data<br>&quot;&quot;&quot;<br>match_id res start_time r_carry_id r_carry_str r_carry_str_gain r_carry_agi r_carry_agi_gain r_carry_int r_carry_int_gain r_mid_id r_mid_str r_mid_str_gain r_mid_agi r_mid_agi_gain r_mid_int r_mid_int_gain r_off_id r_off_str r_off_str_gain r_off_agi r_off_agi_gain r_off_int r_off_int_gain r_ss_id r_ss_str r_ss_str_gain r_ss_agi r_ss_agi_gain r_ss_int r_ss_int_gain r_hs_id r_hs_str r_hs_str_gain r_hs_agi r_hs_agi_gain r_hs_int r_hs_int_gain d_carry_id d_carry_str d_carry_str_gain d_carry_agi d_carry_agi_gain d_carry_int d_carry_int_gain d_mid_id d_mid_str d_mid_str_gain d_mid_agi d_mid_agi_gain d_mid_int d_mid_int_gain d_off_id d_off_str d_off_str_gain d_off_agi d_off_agi_gain d_off_int d_off_int_gain d_ss_id d_ss_str d_ss_str_gain d_ss_agi d_ss_agi_gain d_ss_int d_ss_int_gain d_hs_id d_hs_str d_hs_str_gain d_hs_agi d_hs_agi_gain d_hs_int d_hs_int_gain r_carry_attribute_0 r_carry_attribute_1 r_carry_attribute_2 r_carry_attribute_3 r_mid_attribute_0 r_mid_attribute_1 r_mid_attribute_2 r_mid_attribute_3 r_off_attribute_0 r_off_attribute_1 r_off_attribute_2 r_off_attribute_3 r_ss_attribute_0 r_ss_attribute_1 r_ss_attribute_2 r_ss_attribute_3 r_hs_attribute_0 r_hs_attribute_1 r_hs_attribute_2 r_hs_attribute_3 d_carry_attribute_0 d_carry_attribute_1 d_carry_attribute_2 d_carry_attribute_3 d_mid_attribute_0 d_mid_attribute_1 d_mid_attribute_2 d_mid_attribute_3 d_off_attribute_0 d_off_attribute_1 d_off_attribute_2 d_off_attribute_3 d_ss_attribute_0 d_ss_attribute_1 d_ss_attribute_2 d_ss_attribute_3 d_hs_attribute_0 d_hs_attribute_1 d_hs_attribute_2 d_hs_attribute_3 r_carry_attack_type_0 r_carry_attack_type_1 r_mid_attack_type_0 r_mid_attack_type_1 r_off_attack_type_0 r_off_attack_type_1 r_ss_attack_type_0 r_ss_attack_type_1 r_hs_attack_type_0 r_hs_attack_type_1 d_carry_attack_type_0 d_carry_attack_type_1 d_mid_attack_type_0 d_mid_attack_type_1 d_off_attack_type_0 d_off_attack_type_1 d_ss_attack_type_0 d_ss_attack_type_1 d_hs_attack_type_0 d_hs_attack_type_1<br>0 7152113589 1 23-05-13 94 0.0 0.0 22.0 3.4 27.0 3.7 4 24.0 2.7 22.0 3.1 17.0 2.0 36 18.0 2.3 12.0 1.3 21.0 2.7 7 22.0 3.7 12.0 1.4 18.0 2.1 111 20.0 2.4 15.0 1.7 26.0 3.8 94 0.0 0.0 22.0 3.4 27.0 3.7 4 24.0 2.7 22.0 3.1 17.0 2.0 36 18.0 2.3 12.0 1.3 21.0 2.7 7 22.0 3.7 12.0 1.4 18.0 2.1 111 20.0 2.4 15.0 1.7 26.0 3.8 0 1 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 1 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 0 1<br>1 7152113590 0 23-05-13 16 22.0 2.7 19.0 1.8 19.0 1.8 22 19.0 2.1 11.0 1.2 22.0 3.3 126 22.0 2.6 19.0 2.2 24.0 3.1 62 20.0 2.5 21.0 2.6 22.0 1.9 93 20.0 1.9 21.0 1.5 16.0 1.7 16 22.0 2.7 19.0 1.8 19.0 1.8 22 19.0 2.1 11.0 1.2 22.0 3.3 126 22.0 2.6 19.0 2.2 24.0 3.1 62 20.0 2.5 21.0 2.6 22.0 1.9 93 20.0 1.9 21.0 1.5 16.0 1.7 0 0 0 1 0 0 1 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 1 0 0 0 1 0 0 1 0 0 1 1 0 1 0 1 0 1 0 0 1 1 0 1 0 1 0<br>2 7152113591 1 23-05-13 99 22.0 2.5 17.0 1.8 14.0 2.8 22 19.0 2.1 11.0 1.2 22.0 3.3 93 20.0 1.9 21.0 1.5 16.0 1.7 110 23.0 3.3 12.0 1.5 16.0 1.8 16 22.0 2.7 19.0 1.8 19.0 1.8 99 22.0 2.5 17.0 1.8 14.0 2.8 22 19.0 2.1 11.0 1.2 22.0 3.3 93 20.0 1.9 21.0 1.5 16.0 1.7 110 23.0 3.3 12.0 1.5 16.0 1.8 16 22.0 2.7 19.0 1.8 19.0 1.8 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 1 0<br>3 7152113592 1 23-05-13 21 18.0 2.4 17.0 1.4 18.0 2.4 106 22.0 2.6 22.0 3.2 20.0 2.2 86 21.0 2.0 23.0 2.5 25.0 3.1 94 0.0 0.0 22.0 3.4 27.0 3.7 129 23.0 3.7 20.0 1.7 21.0 2.2 21 18.0 2.4 17.0 1.4 18.0 2.4 106 22.0 2.6 22.0 3.2 20.0 2.2 86 21.0 2.0 23.0 2.5 25.0 3.1 94 0.0 0.0 22.0 3.4 27.0 3.7 129 23.0 3.7 20.0 1.7 21.0 2.2 0 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 0 1 0 1 1 0 <br>&quot;&quot;&quot;</pre><p>Next, we split the data. Since the target variable(winning camp) is kind of balanced, I won’t use resampling methods.</p><pre>from sklearn.model_selection import train_test_split<br><br>hero_id_columns = [&#39;match_id&#39;,<br> &#39;res&#39;,<br> &#39;start_time&#39;,<br> &#39;r_carry_id&#39;,<br> &#39;r_mid_id&#39;,<br> &#39;r_off_id&#39;,<br> &#39;r_ss_id&#39;,<br> &#39;r_hs_id&#39;,<br> &#39;d_carry_id&#39;,<br> &#39;d_mid_id&#39;,<br> &#39;d_off_id&#39;,<br> &#39;d_ss_id&#39;,<br> &#39;d_hs_id&#39;]<br>X = data.drop(hero_id_columns, axis=1)<br>y = data[&#39;res&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2009)<br># X_train, X_test, y_train, y_test = X[:1092], X[1092:], y[:1092], y[1092:]<br><br>print(f&quot;shape of training set: {X_train.shape}&quot;)<br>print(f&quot;shape of training label: {y_train.shape}&quot;)<br>print(f&quot;shape of test set: {X_test.shape}&quot;)<br>print(f&quot;shape of test label: {y_test.shape}&quot;)<br><br>&quot;&quot;&quot;<br>shape of training set: (13532, 120)<br>shape of training label: (13532,)<br>shape of test set: (3383, 120)<br>shape of test label: (3383,)<br>&quot;&quot;&quot;</pre><p>So the final input training data contains the features I mentioned above with the corresponding heroes and roles aligned together. The attribute features are numerical and attribute type/attack type are encoded categories.</p><p>Since the base attribute value and attribute gain are not at the same scale, I would like to rescale these numerical data.</p><pre>from sklearn.metrics import accuracy_score<br>from sklearn.metrics import confusion_matrix<br>from sklearn.metrics import f1_score<br>from sklearn import metrics<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import MinMaxScaler<br><br>rescale_cols = []<br>for hero_role in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]:<br>    <br>    # rescale_cols.append(f&quot;{hero_role}_id&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_attribute&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_attack_type&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_str&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_str_gain&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_str_lvl30&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_agi&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_agi_gain&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_agi_lvl30&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_int&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_int_gain&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_int_lvl30&quot;)<br> <br>   <br>scaler = StandardScaler()<br># scaler = MinMaxScaler()<br># scaler.fit_transform(X_train[rescale_cols])<br>train_scale_df = pd.DataFrame(data=scaler.fit_transform(X_train[rescale_cols]),columns=rescale_cols)<br>test_scale_df = pd.DataFrame(data=scaler.transform(X_test[rescale_cols]),columns=rescale_cols)<br>X_train.reset_index(inplace=True,drop=True)<br>X_test.reset_index(inplace=True,drop=True)<br>for column in rescale_cols:<br>    X_train[column] = train_scale_df[column]<br>    X_test[column] = test_scale_df[column]<br>X_train<br>&quot;&quot;&quot;<br>r_carry_str r_carry_str_gain r_carry_agi r_carry_agi_gain r_carry_int r_carry_int_gain r_mid_str r_mid_str_gain r_mid_agi r_mid_agi_gain r_mid_int r_mid_int_gain r_off_str r_off_str_gain r_off_agi r_off_agi_gain r_off_int r_off_int_gain r_ss_str r_ss_str_gain r_ss_agi r_ss_agi_gain r_ss_int r_ss_int_gain r_hs_str r_hs_str_gain r_hs_agi r_hs_agi_gain r_hs_int r_hs_int_gain d_carry_str d_carry_str_gain d_carry_agi d_carry_agi_gain d_carry_int d_carry_int_gain d_mid_str d_mid_str_gain d_mid_agi d_mid_agi_gain d_mid_int d_mid_int_gain d_off_str d_off_str_gain d_off_agi d_off_agi_gain d_off_int d_off_int_gain d_ss_str d_ss_str_gain d_ss_agi d_ss_agi_gain d_ss_int d_ss_int_gain d_hs_str d_hs_str_gain d_hs_agi d_hs_agi_gain d_hs_int d_hs_int_gain<br>0 -0.628194 -0.436137 0.238392 1.973559 0.000945 -0.682583 0.133648 -0.168354 0.303581 0.585685 -0.389951 -0.272647 2.308560 2.012501 -4.088817 -2.925184 -0.395140 -0.037030 1.294056 0.802616 -0.819670 -0.736939 -0.838009 -0.734500 0.173782 -0.815631 1.416303 1.177800 0.923437 0.431324 -0.628194 -0.436137 0.238392 1.973559 0.000945 -0.682583 0.133648 -0.168354 0.303581 0.585685 -0.389951 -0.272647 2.308560 2.012501 -4.088817 -2.925184 -0.395140 -0.037030 1.294056 0.802616 -0.819670 -0.736939 -0.838009 -0.734500 0.173782 -0.815631 1.416303 1.177800 0.923437 0.431324<br>1 1.006107 0.844860 -1.511852 -1.387061 -0.608033 -0.442462 0.365898 -0.168354 -2.048032 -1.396413 1.723226 0.644444 -0.082010 -1.006279 0.839430 0.836813 0.856165 1.948198 -0.515323 -0.484385 0.965906 0.816058 0.921030 0.387796 -1.199625 -0.446410 -0.285625 -0.331178 -1.037258 0.646568 1.006107 0.844860 -1.511852 -1.387061 -0.608033 -0.442462 0.365898 -0.168354 -2.048032 -1.396413 1.723226 0.644444 -0.082010 -1.006279 0.839430 0.836813 0.856165 1.948198 -0.515323 -0.484385 0.965906 0.816058 0.921030 0.387796 -1.199625 -0.446410 -0.285625 -0.331178 -1.037258 0.646568<br>2 0.098162 -0.564237 0.019611 -1.257807 -0.608033 -0.562523 -0.563101 -0.168354 -1.192900 -0.471434 -0.812586 2.707899 0.183609 -0.251584 -0.280627 -0.320724 -1.020793 0.663639 -0.515323 -0.484385 0.965906 0.816058 0.921030 0.387796 0.173782 -0.815631 1.416303 1.177800 0.923437 0.431324 0.098162 -0.564237 0.019611 -1.257807 -0.608033 -0.562523 -0.563101 -0.168354 -1.192900 -0.471434 -0.812586 2.707899 0.183609 -0.251584 -0.280627 -0.320724 -1.020793 0.663639 -0.515323 -0.484385 0.965906 0.816058 0.921030 0.387796 0.173782 -0.815631 1.416303 1.177800 0.923437 0.431324<br>&quot;&quot;&quot;</pre><p>Modeling</p><p>For the models, I choose Logistic Regression as the baseline because it is more basic. And I will compare the performance of the Decision Tree, Random Forest, and XGBoosting with Logistic Regression.</p><ol><li>Logistic Regression</li></ol><pre># from sklearn.linear_model import LogisticRegression<br>from sklearn.linear_model import LogisticRegressionCV<br>baseline_clf = LogisticRegressionCV(cv=5, random_state=2009, max_iter=10000).fit(X_train, y_train)<br>lr_preds = baseline_clf.predict(X_test)<br>lr_accuracy = accuracy_score(y_test, lr_preds)<br>lr_f1 = f1_score(y_test, lr_preds)<br>print(f&quot;Logistic Regression accuracy = {lr_accuracy}, f1_score = {lr_f1}&quot;)<br># Logistic Regression accuracy = 0.5566065622228791, f1_score = 0.6027542372881355<br>confusion_matrix(y_test, lr_preds)<br>&quot;&quot;&quot;<br>array([[ 742,  913],<br>       [ 587, 1141]])<br>&quot;&quot;&quot;<br>#define metrics<br>y_pred_proba = baseline_clf.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.plot([0,1],[0,1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.title(&#39;ROC AUC curve for LR&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*4jTdle_zSVbkO-CKClGVaw.png" /><figcaption>ROC AUC curve for LR</figcaption></figure><p>2. Decision Tree</p><p>Decision Tree can learn to split on different features and can generate non-linear boundaries.</p><pre>from sklearn.tree import DecisionTreeClassifier<br>dt_clf = DecisionTreeClassifier(random_state=2009, max_depth=5, min_samples_leaf=9)<br>dt_clf = dt_clf.fit(X_train, y_train)<br>dt_preds = dt_clf.predict(X_test)<br><br>dt_accuracy = accuracy_score(y_test, dt_preds)<br>dt_f1 = f1_score(y_test, dt_preds)<br>print(f&quot;Decision Tree accuracy = {dt_accuracy}, f1_score = {dt_f1}&quot;)<br># Decision Tree accuracy = 0.561336092225835, f1_score = 0.6391050583657587<br>confusion_matrix(y_test, dt_preds)<br>&quot;&quot;&quot;<br>array([[ 585,  985],<br>       [ 499, 1314]])<br>&quot;&quot;&quot;<br>#define metrics<br>y_pred_proba = dt_clf.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.plot([0,1],[0,1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.title(&#39;ROC AUC curve for DT&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*7mDP0f6hVGDvM-bEJFBhMQ.png" /><figcaption>ROC AUC curve for DT</figcaption></figure><p>3. Random Forest</p><p>RF is an ensemble method. It applies majority voting for the final prediction, which combines the results of many estimators(decision trees).</p><pre>from sklearn.ensemble import RandomForestClassifier<br>rf_clf = RandomForestClassifier(n_estimators=200, max_depth=9, max_features=9, min_samples_split=4, random_state=2009)<br>rf_clf.fit(X_train, y_train)<br>rf_preds = rf_clf.predict(X_test)<br><br>rf_accuracy = accuracy_score(y_test, rf_preds)<br>rf_f1 = f1_score(y_test, rf_preds)<br>print(f&quot;Random Forest accuracy = {rf_accuracy}, f1_score = {rf_f1}&quot;)<br># Random Forest accuracy = 0.5690215784806385, f1_score = 0.6419449901768172<br>confusion_matrix(y_test, rf_preds)<br>&quot;&quot;&quot;<br>array([[ 618,  952],<br>       [ 506, 1307]])<br>&quot;&quot;&quot;<br>from sklearn.metrics import precision_recall_fscore_support as score<br>precision, recall, fscore, support = score(y_test, rf_preds)<br>print(&#39;precision: {}&#39;.format(precision))<br>print(&#39;recall: {}&#39;.format(recall))<br>print(&#39;fscore: {}&#39;.format(fscore))<br>print(&#39;support: {}&#39;.format(support))<br>&quot;&quot;&quot;<br>precision: [0.54982206 0.57857459]<br>recall: [0.39363057 0.72090458]<br>fscore: [0.45879733 0.64194499]<br>support: [1570 1813]<br>&quot;&quot;&quot;<br>#define metrics<br>y_pred_proba = rf_clf.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.plot([0,1],[0,1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.title(&#39;ROC AUC curve for RF&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*fh7jJxvsdeMqURRior2h6Q.png" /><figcaption>ROC AUC curve for RF</figcaption></figure><p>4. XGBoosting</p><p>Boosting is also an ensemble method. But it is quite different from Random Forest as the trees in Boosting are in a sequence. It assigns weights to the output of individual trees. Then it gives incorrect classifications from the first decision tree a higher weight and input to the next tree. After numerous cycles, the boosting method combines these weak rules into a single powerful prediction rule(<a href="https://aws.amazon.com/what-is/boosting/#:~:text=Boosting%20is%20a%20method%20used,make%20guesses%20about%20unlabeled%20data.">reference</a>).</p><pre>import xgboost as xgb<br><br>parameters = {&#39;n_estimators&#39;: 200,<br>        &#39;learning_rate&#39;: 0.05,<br>        &#39;max_depth&#39;: 6,<br>        &#39;subsample_size&#39;: 0.8,<br>        &#39;random_state&#39;: 2009,<br>        &#39;reg_alpha&#39;: 0.2,<br>        &#39;colsample_bytree&#39;: 0.5,<br>        &#39;reg_lambda&#39;: 4,<br>        &#39;min_child_weight&#39;: 66,<br>        # &#39;eval_metric&#39;: &#39;logloss&#39;<br>        }<br>model = xgb.XGBClassifier(**parameters)<br>model.fit(X_train, y_train)<br># Predict<br>xgb_preds = model.predict(X_test)<br>xgb_accuracy = accuracy_score(y_test, xgb_preds)<br>xgb_f1 = f1_score(y_test, xgb_preds)<br>print(f&quot;XGBoosting accuracy = {xgb_accuracy}, f1_score = {xgb_f1}&quot;)<br># XGBoosting accuracy = 0.5731599172332249, f1_score = 0.617989417989418<br>confusion_matrix(y_test, xgb_preds)<br>&quot;&quot;&quot;<br>array([[ 771,  799],<br>       [ 645, 1168]])<br>&quot;&quot;&quot;<br>precision, recall, fscore, support = score(y_test, xgb_preds)<br>print(&#39;precision: {}&#39;.format(precision))<br>print(&#39;recall: {}&#39;.format(recall))<br>print(&#39;fscore: {}&#39;.format(fscore))<br>print(&#39;support: {}&#39;.format(support))<br>&quot;&quot;&quot;<br>precision: [0.54449153 0.59379766]<br>recall: [0.4910828  0.64423607]<br>fscore: [0.51640991 0.61798942]<br>support: [1570 1813]<br>&quot;&quot;&quot;<br><br>#define metrics<br>y_pred_proba = model.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.plot([0,1],[0,1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.title(&#39;ROC AUC curve for XGB&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*Ns4zTa_5F9vQJbV8APqXPw.png" /><figcaption>ROC AUC curve for XGB</figcaption></figure><p>Now let’s compare the final results of these models:</p><pre>model_list = [&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;Random Forest&#39;, &#39;XGBoosting&#39;]<br>accuracy_list = [lr_accuracy, dt_accuracy, rf_accuracy, xgb_accuracy]<br>f1_list = [lr_f1, dt_f1, rf_f1, xgb_f1]<br>res1_df = pd.DataFrame({<br>    &#39;model&#39;: model_list,<br>    &#39;accuracy_score&#39;: accuracy_list,<br>    &#39;f1_score&#39;: f1_list<br>})<br>res1_df</pre><pre>&quot;&quot;&quot;<br>model accuracy_score f1_score<br>0 Logistic Regression 0.556607 0.602754<br>1 Decision Tree 0.561336 0.639105<br>2 Random Forest 0.569022 0.641945<br>3 XGBoosting 0.573160 0.617989<br>&quot;&quot;&quot;</pre><p>As you can see, XGBoosting has the best accuracy based on these features. RF has a relatively high accuracy and a high f1_score.</p><pre>from sklearn.metrics import classification_report<br>target_names = [&#39;class 0&#39;, &#39;class 1&#39;]<br>print(&#39;Random Forest Classification Report&#39;)<br>print(classification_report(y_test, rf_preds, target_names=target_names))<br><br>print(&#39;XGBoosting Classification Report&#39;)<br>print(classification_report(y_test, xgb_preds, target_names=target_names))<br>&quot;&quot;&quot;<br>Random Forest Classification Report<br>              precision    recall  f1-score   support<br>     class 0       0.55      0.39      0.46      1570<br>     class 1       0.58      0.72      0.64      1813<br>    accuracy                           0.57      3383<br>   macro avg       0.56      0.56      0.55      3383<br>weighted avg       0.57      0.57      0.56      3383<br>XGBoosting Classification Report<br>              precision    recall  f1-score   support<br>     class 0       0.54      0.49      0.52      1570<br>     class 1       0.59      0.64      0.62      1813<br>    accuracy                           0.57      3383<br>   macro avg       0.57      0.57      0.57      3383<br>weighted avg       0.57      0.57      0.57      3383<br>&quot;&quot;&quot;</pre><p>If we compare the precision and recall of XGB and RF, we will find that XGB has a higher precision for class label 1, and RF has a higher recall for class label 1. Although RF has a better f1-score than XGB for class label 1, actually, XGB has a balanced f1-score on both class 0 and 1. So XGB is the best model in general.</p><p>Graph Embedding</p><p>Next, I tried to use graphs to embed the counter-relationship between heroes. My teammate helped me with this. He is a cool Immortal player good at Carry and Mid. We referred to this paper: <a href="https://dl.acm.org/doi/10.1145/3132847.3132953.">https://dl.acm.org/doi/10.1145/3132847.3132953.</a> The author proposed HIN2Vec, a heterogeneous information networks model to capture the rich semantics by exploiting different types of relationships among nodes. I set the heroes as the nodes and the relationships as the edges. To train the model based on my own data, I referred to the code on <a href="https://github.com/e-yi/hin2vec_pytorch.">https://github.com/e-yi/hin2vec_pytorch.</a> In this repository, the Heterogeneous Information Network is considered an undirected weighted simple graph with multiple node types and multiple edge types. There is at most one type of edge for each pair of node types. So I will only embed the edge as good against, which means: If hero1 is good against hero2, the edge should be hero1 — hero2. If hero1 is bad against hero2, the edge should be hero2 — hero1. Finally, I embedded each hero in an 18-dimension vector(<a href="https://colab.research.google.com/drive/1JW4zZofyTLvkU8TzTlbtIde_FFWTq6Pi?usp=sharing">code</a>).</p><p>This time I also dropped the hero ids. Now we have more input features:</p><pre>temp_df<br>&quot;&quot;&quot;<br>match_id res start_time r_carry_id r_carry_str r_carry_str_gain r_carry_agi r_carry_agi_gain r_carry_int r_carry_int_gain r_mid_id r_mid_str r_mid_str_gain r_mid_agi r_mid_agi_gain r_mid_int r_mid_int_gain r_off_id r_off_str r_off_str_gain r_off_agi r_off_agi_gain r_off_int r_off_int_gain r_ss_id r_ss_str r_ss_str_gain r_ss_agi r_ss_agi_gain r_ss_int r_ss_int_gain r_hs_id r_hs_str r_hs_str_gain r_hs_agi r_hs_agi_gain r_hs_int r_hs_int_gain d_carry_id d_carry_str d_carry_str_gain d_carry_agi d_carry_agi_gain d_carry_int d_carry_int_gain d_mid_id d_mid_str d_mid_str_gain d_mid_agi d_mid_agi_gain d_mid_int d_mid_int_gain d_off_id d_off_str d_off_str_gain d_off_agi d_off_agi_gain d_off_int d_off_int_gain d_ss_id d_ss_str d_ss_str_gain d_ss_agi d_ss_agi_gain d_ss_int d_ss_int_gain d_hs_id d_hs_str d_hs_str_gain d_hs_agi d_hs_agi_gain d_hs_int d_hs_int_gain r_carry_attribute_0 r_carry_attribute_1 r_carry_attribute_2 r_carry_attribute_3 r_mid_attribute_0 r_mid_attribute_1 r_mid_attribute_2 r_mid_attribute_3 r_off_attribute_0 r_off_attribute_1 r_off_attribute_2 r_off_attribute_3 r_ss_attribute_0 r_ss_attribute_1 r_ss_attribute_2 r_ss_attribute_3 r_hs_attribute_0 r_hs_attribute_1 r_hs_attribute_2 r_hs_attribute_3 d_carry_attribute_0 d_carry_attribute_1 d_carry_attribute_2 d_carry_attribute_3 d_mid_attribute_0 d_mid_attribute_1 d_mid_attribute_2 d_mid_attribute_3 d_off_attribute_0 d_off_attribute_1 d_off_attribute_2 d_off_attribute_3 d_ss_attribute_0 d_ss_attribute_1 d_ss_attribute_2 d_ss_attribute_3 d_hs_attribute_0 d_hs_attribute_1 d_hs_attribute_2 d_hs_attribute_3 r_carry_attack_type_0 r_carry_attack_type_1 r_mid_attack_type_0 r_mid_attack_type_1 r_off_attack_type_0 r_off_attack_type_1 r_ss_attack_type_0 r_ss_attack_type_1 r_hs_attack_type_0 r_hs_attack_type_1 d_carry_attack_type_0 d_carry_attack_type_1 d_mid_attack_type_0 d_mid_attack_type_1 d_off_attack_type_0 d_off_attack_type_1 d_ss_attack_type_0 d_ss_attack_type_1 d_hs_attack_type_0 d_hs_attack_type_1 r_carry_id_emb_0 r_carry_id_emb_1 r_carry_id_emb_2 r_carry_id_emb_3 r_carry_id_emb_4 r_carry_id_emb_5 r_carry_id_emb_6 r_carry_id_emb_7 r_carry_id_emb_8 r_carry_id_emb_9 r_carry_id_emb_10 r_carry_id_emb_11 r_carry_id_emb_12 r_carry_id_emb_13 r_carry_id_emb_14 r_carry_id_emb_15 r_carry_id_emb_16 r_carry_id_emb_17 r_mid_id_emb_0 r_mid_id_emb_1 r_mid_id_emb_2 r_mid_id_emb_3 r_mid_id_emb_4 r_mid_id_emb_5 r_mid_id_emb_6 r_mid_id_emb_7 r_mid_id_emb_8 r_mid_id_emb_9 r_mid_id_emb_10 r_mid_id_emb_11 r_mid_id_emb_12 r_mid_id_emb_13 r_mid_id_emb_14 r_mid_id_emb_15 r_mid_id_emb_16 r_mid_id_emb_17 r_off_id_emb_0 r_off_id_emb_1 r_off_id_emb_2 r_off_id_emb_3 r_off_id_emb_4 r_off_id_emb_5 r_off_id_emb_6 r_off_id_emb_7 r_off_id_emb_8 r_off_id_emb_9 r_off_id_emb_10 r_off_id_emb_11 r_off_id_emb_12 r_off_id_emb_13 r_off_id_emb_14 r_off_id_emb_15 r_off_id_emb_16 r_off_id_emb_17 r_ss_id_emb_0 r_ss_id_emb_1 r_ss_id_emb_2 r_ss_id_emb_3 r_ss_id_emb_4 r_ss_id_emb_5 r_ss_id_emb_6 r_ss_id_emb_7 r_ss_id_emb_8 r_ss_id_emb_9 r_ss_id_emb_10 r_ss_id_emb_11 r_ss_id_emb_12 r_ss_id_emb_13 r_ss_id_emb_14 r_ss_id_emb_15 r_ss_id_emb_16 r_ss_id_emb_17 r_hs_id_emb_0 r_hs_id_emb_1 r_hs_id_emb_2 r_hs_id_emb_3 r_hs_id_emb_4 r_hs_id_emb_5 r_hs_id_emb_6 r_hs_id_emb_7 r_hs_id_emb_8 r_hs_id_emb_9 r_hs_id_emb_10 r_hs_id_emb_11 r_hs_id_emb_12 r_hs_id_emb_13 r_hs_id_emb_14 r_hs_id_emb_15 r_hs_id_emb_16 r_hs_id_emb_17 d_carry_id_emb_0 d_carry_id_emb_1 d_carry_id_emb_2 d_carry_id_emb_3 d_carry_id_emb_4 d_carry_id_emb_5 d_carry_id_emb_6 d_carry_id_emb_7 d_carry_id_emb_8 d_carry_id_emb_9 d_carry_id_emb_10 d_carry_id_emb_11 d_carry_id_emb_12 d_carry_id_emb_13 d_carry_id_emb_14 d_carry_id_emb_15 d_carry_id_emb_16 d_carry_id_emb_17 d_mid_id_emb_0 d_mid_id_emb_1 d_mid_id_emb_2 d_mid_id_emb_3 d_mid_id_emb_4 d_mid_id_emb_5 d_mid_id_emb_6 d_mid_id_emb_7 d_mid_id_emb_8 d_mid_id_emb_9 d_mid_id_emb_10 d_mid_id_emb_11 d_mid_id_emb_12 d_mid_id_emb_13 d_mid_id_emb_14 d_mid_id_emb_15 d_mid_id_emb_16 d_mid_id_emb_17 d_off_id_emb_0 d_off_id_emb_1 d_off_id_emb_2 d_off_id_emb_3 d_off_id_emb_4 d_off_id_emb_5 d_off_id_emb_6 d_off_id_emb_7 d_off_id_emb_8 d_off_id_emb_9 d_off_id_emb_10 d_off_id_emb_11 d_off_id_emb_12 d_off_id_emb_13 d_off_id_emb_14 d_off_id_emb_15 d_off_id_emb_16 d_off_id_emb_17 d_ss_id_emb_0 d_ss_id_emb_1 d_ss_id_emb_2 d_ss_id_emb_3 d_ss_id_emb_4 d_ss_id_emb_5 d_ss_id_emb_6 d_ss_id_emb_7 d_ss_id_emb_8 d_ss_id_emb_9 d_ss_id_emb_10 d_ss_id_emb_11 d_ss_id_emb_12 d_ss_id_emb_13 d_ss_id_emb_14 d_ss_id_emb_15 d_ss_id_emb_16 d_ss_id_emb_17 d_hs_id_emb_0 d_hs_id_emb_1 d_hs_id_emb_2 d_hs_id_emb_3 d_hs_id_emb_4 d_hs_id_emb_5 d_hs_id_emb_6 d_hs_id_emb_7 d_hs_id_emb_8 d_hs_id_emb_9 d_hs_id_emb_10 d_hs_id_emb_11 d_hs_id_emb_12 d_hs_id_emb_13 d_hs_id_emb_14 d_hs_id_emb_15 d_hs_id_emb_16 d_hs_id_emb_17<br>0 7152113589 1 23-05-13 94 0.0 0.0 22.0 3.4 27.0 3.7 4 24.0 2.7 22.0 3.1 17.0 2.0 36 18.0 2.3 12.0 1.3 21.0 2.7 7 22.0 3.7 12.0 1.4 18.0 2.1 111 20.0 2.4 15.0 1.7 26.0 3.8 94 0.0 0.0 22.0 3.4 27.0 3.7 4 24.0 2.7 22.0 3.1 17.0 2.0 36 18.0 2.3 12.0 1.3 21.0 2.7 7 22.0 3.7 12.0 1.4 18.0 2.1 111 20.0 2.4 15.0 1.7 26.0 3.8 0 1 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 1 1 0 0 1 1 0 0 1 0 1 1 0 0 1 1 0 0 1 0.518879 -0.066986 -0.440968 -0.325357 0.193166 -0.134934 -0.123168 0.596094 -0.605550 -0.532283 -0.070714 0.251996 0.448694 0.181602 -0.033602 0.260929 3.245669 0.065991 0.249611 -0.157333 -0.220043 -0.313190 -0.303614 -0.247384 -0.001114 0.209326 0.353159 -0.035542 -0.045212 0.156129 -0.003114 0.083318 -0.492035 0.165493 2.327394 0.149819 -0.009061 0.342790 0.026497 0.084790 0.151178 -0.261406 0.075487 -0.084987 -0.160529 0.578501 0.195970 -0.180328 -0.358564 0.412537 -0.180494 0.054389 2.176422 -0.033751 0.375128 -0.092188 -0.138763 -0.049273 -0.208746 -0.186143 -0.488855 -0.086250 -0.075446 -0.034505 -0.052678 -0.075578 0.206584 0.249883 -0.188644 -0.018512 3.141398 -0.062451 0.083078 0.018342 -0.490710 0.082603 -0.229644 -0.203048 -0.211574 0.492516 0.162593 -0.310779 0.153814 0.169410 0.057991 -0.582990 -0.188224 -0.199357 2.518085 0.197811 0.518879 -0.066986 -0.440968 -0.325357 0.193166 -0.134934 -0.123168 0.596094 -0.605550 -0.532283 -0.070714 0.251996 0.448694 0.181602 -0.033602 0.260929 3.245669 0.065991 0.249611 -0.157333 -0.220043 -0.313190 -0.303614 -0.247384 -0.001114 0.209326 0.353159 -0.035542 -0.045212 0.156129 -0.003114 0.083318 -0.492035 0.165493 2.327394 0.149819 -0.009061 0.342790 0.026497 0.084790 0.151178 -0.261406 0.075487 -0.084987 -0.160529 0.578501 0.195970 -0.180328 -0.358564 0.412537 -0.180494 0.054389 2.176422 -0.033751 0.375128 -0.092188 -0.138763 -0.049273 -0.208746 -0.186143 -0.488855 -0.086250 -0.075446 -0.034505 -0.052678 -0.075578 0.206584 0.249883 -0.188644 -0.018512 3.141398 -0.062451 0.083078 0.018342 -0.490710 0.082603 -0.229644 -0.203048 -0.211574 0.492516 0.162593 -0.310779 0.153814 0.169410 0.057991 -0.582990 -0.188224 -0.199357 2.518085 0.197811<br>1 7152164469 0 23-05-13 41 20.0 2.4 19.0 3.0 15.0 1.5 21 18.0 2.4 17.0 1.4 18.0 2.4 57 23.0 3.1 15.0 2.0 16.0 2.1 7 22.0 3.7 12.0 1.4 18.0 2.1 111 20.0 2.4 15.0 1.7 26.0 3.8 41 20.0 2.4 19.0 3.0 15.0 1.5 21 18.0 2.4 17.0 1.4 18.0 2.4 57 23.0 3.1 15.0 2.0 16.0 2.1 7 22.0 3.7 12.0 1.4 18.0 2.1 111 20.0 2.4 15.0 1.7 26.0 3.8 0 1 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0 1 0 1 0 0 1 1 0 1 0 0 1 1 0 0 1 1 0 1 0 0 1 -0.172344 0.306537 -0.284819 -0.154103 -0.269389 -0.209359 0.107670 0.479141 0.446757 -0.078369 -0.119798 0.200447 -0.049071 0.332875 0.268584 0.230138 2.439955 -0.134744 -0.185651 -0.174762 0.053523 0.221494 -0.045096 -0.262068 -0.207598 -0.045020 0.696383 -0.219326 -0.080043 0.067940 -0.029794 0.308707 0.020129 -0.030265 2.131241 -0.211954 0.379183 -0.238024 0.021080 -0.094302 -0.456275 8.984025 0.104676 0.363061 0.809582 -0.214188 -0.573109 0.098838 0.314816 -0.182383 -0.000156 0.079497 -0.685040 -0.717201 0.375128 -0.092188 -0.138763 -0.049273 -0.208746 -0.186143 -0.488855 -0.086250 -0.075446 -0.034505 -0.052678 -0.075578 0.206584 0.249883 -0.188644 -0.018512 3.141398 -0.062451 0.083078 0.018342 -0.490710 0.082603 -0.229644 -0.203048 -0.211574 0.492516 0.162593 -0.310779 0.153814 0.169410 0.057991 -0.582990 -0.188224 -0.199357 2.518085 0.197811 -0.172344 0.306537 -0.284819 -0.154103 -0.269389 -0.209359 0.107670 0.479141 0.446757 -0.078369 -0.119798 0.200447 -0.049071 0.332875 0.268584 0.230138 2.439955 -0.134744 -0.185651 -0.174762 0.053523 0.221494 -0.045096 -0.262068 -0.207598 -0.045020 0.696383 -0.219326 -0.080043 0.067940 -0.029794 0.308707 0.020129 -0.030265 2.131241 -0.211954 0.379183 -0.238024 0.021080 -0.094302 -0.456275 8.984025 0.104676 0.363061 0.809582 -0.214188 -0.573109 0.098838 0.314816 -0.182383 -0.000156 0.079497 -0.685040 -0.717201 0.375128 -0.092188 -0.138763 -0.049273 -0.208746 -0.186143 -0.488855 -0.086250 -0.075446 -0.034505 -0.052678 -0.075578 0.206584 0.249883 -0.188644 -0.018512 3.141398 -0.062451 0.083078 0.018342 -0.490710 0.082603 -0.229644 -0.203048 -0.211574 0.492516 0.162593 -0.310779 0.153814 0.169410 0.057991 -0.582990 -0.188224 -0.199357 2.518085 0.197811<br>2 7152197709 1 23-05-13 41 20.0 2.4 19.0 3.0 15.0 1.5 102 22.0 2.2 23.0 1.3 18.0 1.2 105 19.0 2.5 14.0 1.3 25.0 3.0 7 22.0 3.7 12.0 1.4 18.0 2.1 111 20.0 2.4 15.0 1.7 26.0 3.8 41 20.0 2.4 19.0 3.0 15.0 1.5 102 22.0 2.2 23.0 1.3 18.0 1.2 105 19.0 2.5 14.0 1.3 25.0 3.0 7 22.0 3.7 12.0 1.4 18.0 2.1 111 20.0 2.4 15.0 1.7 26.0 3.8 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 1 0 1 0 1 0 0 1 1 0 0 1 1 0 1 0 0 1 1 0 0 1 -0.172344 0.306537 -0.284819 -0.154103 -0.269389 -0.209359 0.107670 0.479141 0.446757 -0.078369 -0.119798 0.200447 -0.049071 0.332875 0.268584 0.230138 2.439955 -0.134744 -0.224511 -0.167284 0.105671 0.443601 -0.198075 -0.215514 0.209725 0.016978 0.096986 -0.200314 -0.168368 0.260454 0.205979 -0.005419 0.186287 -0.073216 2.441564 0.024952 -0.047530 -0.101366 -0.035293 0.257717 -0.357387 -0.254053 -0.407104 0.095872 0.209395 0.016708 0.497627 -0.155579 0.193132 -0.446539 -0.282615 -0.000503 2.565557 0.250364 0.375128 -0.092188 -0.138763 -0.049273 -0.208746 -0.186143 -0.488855 -0.086250 -0.075446 -0.034505 -0.052678 -0.075578 0.206584 0.249883 -0.188644 -0.018512 3.141398 -0.062451 0.083078 0.018342 -0.490710 0.082603 -0.229644 -0.203048 -0.211574 0.492516 0.162593 -0.310779 0.153814 0.169410 0.057991 -0.582990 -0.188224 -0.199357 2.518085 0.197811 -0.172344 0.306537 -0.284819 -0.154103 -0.269389 -0.209359 0.107670 0.479141 0.446757 -0.078369 -0.119798 0.200447 -0.049071 0.332875 0.268584 0.230138 2.439955 -0.134744 -0.224511 -0.167284 0.105671 0.443601 -0.198075 -0.215514 0.209725 0.016978 0.096986 -0.200314 -0.168368 0.260454 0.205979 -0.005419 0.186287 -0.073216 2.441564 0.024952 -0.047530 -0.101366 -0.035293 0.257717 -0.357387 -0.254053 -0.407104 0.095872 0.209395 0.016708 0.497627 -0.155579 0.193132 -0.446539 -0.282615 -0.000503 2.565557 0.250364 0.375128 -0.092188 -0.138763 -0.049273 -0.208746 -0.186143 -0.488855 -0.086250 -0.075446 -0.034505 -0.052678 -0.075578 0.206584 0.249883 -0.188644 -0.018512 3.141398 -0.062451 0.083078 0.018342 -0.490710 0.082603 -0.229644 -0.203048 -0.211574 0.492516 0.162593 -0.310779 0.153814 0.169410 0.057991 -0.582990 -0.188224 -0.199357 2.518085 0.197811<br>&quot;&quot;&quot;<br><br>X = temp_df.drop(hero_id_columns, axis=1)<br>X = X.drop([&#39;start_time&#39;], axis=1)<br>y = temp_df[&#39;res&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=2009)<br>print(f&quot;shape of training set: {X_train.shape}&quot;)<br>print(f&quot;shape of training label: {y_train.shape}&quot;)<br>print(f&quot;shape of test set: {X_test.shape}&quot;)<br>print(f&quot;shape of test label: {y_test.shape}&quot;)<br><br>&quot;&quot;&quot;<br>shape of training set: (13532, 300)<br>shape of training label: (13532,)<br>shape of test set: (3383, 300)<br>shape of test label: (3383,)<br>&quot;&quot;&quot;</pre><p>Also, I rescaled the attributes.</p><pre>rescale_cols = []<br>for hero_role in [&#39;r_carry&#39;,&#39;r_mid&#39;,&#39;r_off&#39;,&#39;r_ss&#39;,&#39;r_hs&#39;,\<br>    &#39;d_carry&#39;, &#39;d_mid&#39;, &#39;d_off&#39;, &#39;d_ss&#39;, &#39;d_hs&#39;]:<br>    <br>    # rescale_cols.append(f&quot;{hero_role}_id&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_attribute&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_attack_type&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_str&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_str_gain&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_str_lvl30&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_agi&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_agi_gain&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_agi_lvl30&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_int&quot;)<br>    rescale_cols.append(f&quot;{hero_role}_int_gain&quot;)<br>    # rescale_cols.append(f&quot;{hero_role}_int_lvl30&quot;)<br>    <br>scaler = StandardScaler()<br># scaler = MinMaxScaler()<br><br># scaler.fit_transform(X_train[rescale_cols])<br># train_scale_df = pd.DataFrame(data=scaler.fit_transform(X_train),columns=list(X_train.columns))<br># test_scale_df = pd.DataFrame(data=scaler.transform(X_test),columns=list(X_train.columns))<br>train_scale_df = pd.DataFrame(data=scaler.fit_transform(X_train[rescale_cols]),columns=rescale_cols)<br>test_scale_df = pd.DataFrame(data=scaler.transform(X_test[rescale_cols]),columns=rescale_cols)<br>X_train.reset_index(inplace=True,drop=True)<br>X_test.reset_index(inplace=True,drop=True)<br># for column in list(X_train.columns):<br>#     X_train[column] = train_scale_df[column]<br>#     X_test[column] = test_scale_df[column]<br>for column in rescale_cols:<br>    X_train[column] = train_scale_df[column]<br>    X_test[column] = test_scale_df[column]<br>X_train<br>&quot;&quot;&quot;<br>r_carry_str r_carry_str_gain r_carry_agi r_carry_agi_gain r_carry_int r_carry_int_gain r_mid_str r_mid_str_gain r_mid_agi r_mid_agi_gain r_mid_int r_mid_int_gain r_off_str r_off_str_gain r_off_agi r_off_agi_gain r_off_int r_off_int_gain r_ss_str r_ss_str_gain r_ss_agi r_ss_agi_gain r_ss_int r_ss_int_gain r_hs_str r_hs_str_gain r_hs_agi r_hs_agi_gain r_hs_int r_hs_int_gain d_carry_str d_carry_str_gain d_carry_agi d_carry_agi_gain d_carry_int d_carry_int_gain d_mid_str d_mid_str_gain d_mid_agi d_mid_agi_gain d_mid_int d_mid_int_gain d_off_str d_off_str_gain d_off_agi d_off_agi_gain d_off_int d_off_int_gain d_ss_str d_ss_str_gain d_ss_agi d_ss_agi_gain d_ss_int d_ss_int_gain d_hs_str d_hs_str_gain d_hs_agi d_hs_agi_gain d_hs_int d_hs_int_gain r_carry_attribute_0 r_carry_attribute_1 r_carry_attribute_2 r_carry_attribute_3 r_mid_attribute_0 r_mid_attribute_1 r_mid_attribute_2 r_mid_attribute_3 r_off_attribute_0 r_off_attribute_1 r_off_attribute_2 r_off_attribute_3 r_ss_attribute_0 r_ss_attribute_1 r_ss_attribute_2 r_ss_attribute_3 r_hs_attribute_0 r_hs_attribute_1 r_hs_attribute_2 r_hs_attribute_3 d_carry_attribute_0 d_carry_attribute_1 d_carry_attribute_2 d_carry_attribute_3 d_mid_attribute_0 d_mid_attribute_1 d_mid_attribute_2 d_mid_attribute_3 d_off_attribute_0 d_off_attribute_1 d_off_attribute_2 d_off_attribute_3 d_ss_attribute_0 d_ss_attribute_1 d_ss_attribute_2 d_ss_attribute_3 d_hs_attribute_0 d_hs_attribute_1 d_hs_attribute_2 d_hs_attribute_3 r_carry_attack_type_0 r_carry_attack_type_1 r_mid_attack_type_0 r_mid_attack_type_1 r_off_attack_type_0 r_off_attack_type_1 r_ss_attack_type_0 r_ss_attack_type_1 r_hs_attack_type_0 r_hs_attack_type_1 d_carry_attack_type_0 d_carry_attack_type_1 d_mid_attack_type_0 d_mid_attack_type_1 d_off_attack_type_0 d_off_attack_type_1 d_ss_attack_type_0 d_ss_attack_type_1 d_hs_attack_type_0 d_hs_attack_type_1 r_carry_id_emb_0 r_carry_id_emb_1 r_carry_id_emb_2 r_carry_id_emb_3 r_carry_id_emb_4 r_carry_id_emb_5 r_carry_id_emb_6 r_carry_id_emb_7 r_carry_id_emb_8 r_carry_id_emb_9 r_carry_id_emb_10 r_carry_id_emb_11 r_carry_id_emb_12 r_carry_id_emb_13 r_carry_id_emb_14 r_carry_id_emb_15 r_carry_id_emb_16 r_carry_id_emb_17 r_mid_id_emb_0 r_mid_id_emb_1 r_mid_id_emb_2 r_mid_id_emb_3 r_mid_id_emb_4 r_mid_id_emb_5 r_mid_id_emb_6 r_mid_id_emb_7 r_mid_id_emb_8 r_mid_id_emb_9 r_mid_id_emb_10 r_mid_id_emb_11 r_mid_id_emb_12 r_mid_id_emb_13 r_mid_id_emb_14 r_mid_id_emb_15 r_mid_id_emb_16 r_mid_id_emb_17 r_off_id_emb_0 r_off_id_emb_1 r_off_id_emb_2 r_off_id_emb_3 r_off_id_emb_4 r_off_id_emb_5 r_off_id_emb_6 r_off_id_emb_7 r_off_id_emb_8 r_off_id_emb_9 r_off_id_emb_10 r_off_id_emb_11 r_off_id_emb_12 r_off_id_emb_13 r_off_id_emb_14 r_off_id_emb_15 r_off_id_emb_16 r_off_id_emb_17 r_ss_id_emb_0 r_ss_id_emb_1 r_ss_id_emb_2 r_ss_id_emb_3 r_ss_id_emb_4 r_ss_id_emb_5 r_ss_id_emb_6 r_ss_id_emb_7 r_ss_id_emb_8 r_ss_id_emb_9 r_ss_id_emb_10 r_ss_id_emb_11 r_ss_id_emb_12 r_ss_id_emb_13 r_ss_id_emb_14 r_ss_id_emb_15 r_ss_id_emb_16 r_ss_id_emb_17 r_hs_id_emb_0 r_hs_id_emb_1 r_hs_id_emb_2 r_hs_id_emb_3 r_hs_id_emb_4 r_hs_id_emb_5 r_hs_id_emb_6 r_hs_id_emb_7 r_hs_id_emb_8 r_hs_id_emb_9 r_hs_id_emb_10 r_hs_id_emb_11 r_hs_id_emb_12 r_hs_id_emb_13 r_hs_id_emb_14 r_hs_id_emb_15 r_hs_id_emb_16 r_hs_id_emb_17 d_carry_id_emb_0 d_carry_id_emb_1 d_carry_id_emb_2 d_carry_id_emb_3 d_carry_id_emb_4 d_carry_id_emb_5 d_carry_id_emb_6 d_carry_id_emb_7 d_carry_id_emb_8 d_carry_id_emb_9 d_carry_id_emb_10 d_carry_id_emb_11 d_carry_id_emb_12 d_carry_id_emb_13 d_carry_id_emb_14 d_carry_id_emb_15 d_carry_id_emb_16 d_carry_id_emb_17 d_mid_id_emb_0 d_mid_id_emb_1 d_mid_id_emb_2 d_mid_id_emb_3 d_mid_id_emb_4 d_mid_id_emb_5 d_mid_id_emb_6 d_mid_id_emb_7 d_mid_id_emb_8 d_mid_id_emb_9 d_mid_id_emb_10 d_mid_id_emb_11 d_mid_id_emb_12 d_mid_id_emb_13 d_mid_id_emb_14 d_mid_id_emb_15 d_mid_id_emb_16 d_mid_id_emb_17 d_off_id_emb_0 d_off_id_emb_1 d_off_id_emb_2 d_off_id_emb_3 d_off_id_emb_4 d_off_id_emb_5 d_off_id_emb_6 d_off_id_emb_7 d_off_id_emb_8 d_off_id_emb_9 d_off_id_emb_10 d_off_id_emb_11 d_off_id_emb_12 d_off_id_emb_13 d_off_id_emb_14 d_off_id_emb_15 d_off_id_emb_16 d_off_id_emb_17 d_ss_id_emb_0 d_ss_id_emb_1 d_ss_id_emb_2 d_ss_id_emb_3 d_ss_id_emb_4 d_ss_id_emb_5 d_ss_id_emb_6 d_ss_id_emb_7 d_ss_id_emb_8 d_ss_id_emb_9 d_ss_id_emb_10 d_ss_id_emb_11 d_ss_id_emb_12 d_ss_id_emb_13 d_ss_id_emb_14 d_ss_id_emb_15 d_ss_id_emb_16 d_ss_id_emb_17 d_hs_id_emb_0 d_hs_id_emb_1 d_hs_id_emb_2 d_hs_id_emb_3 d_hs_id_emb_4 d_hs_id_emb_5 d_hs_id_emb_6 d_hs_id_emb_7 d_hs_id_emb_8 d_hs_id_emb_9 d_hs_id_emb_10 d_hs_id_emb_11 d_hs_id_emb_12 d_hs_id_emb_13 d_hs_id_emb_14 d_hs_id_emb_15 d_hs_id_emb_16 d_hs_id_emb_17<br>0 0.276557 0.719173 -1.074670 -0.608466 1.024124 1.007719 1.069307 -0.180172 -0.120364 0.462412 -0.820039 -0.505037 0.981664 0.966712 -0.057574 -0.462755 0.223211 -0.039930 1.299109 0.805536 -0.813628 -0.734298 -0.849308 -0.744214 0.507501 0.098578 2.137773 2.503586 0.055968 -0.314297 0.276557 0.719173 -1.074670 -0.608466 1.024124 1.007719 1.069307 -0.180172 -0.120364 0.462412 -0.820039 -0.505037 0.981664 0.966712 -0.057574 -0.462755 0.223211 -0.039930 1.299109 0.805536 -0.813628 -0.734298 -0.849308 -0.744214 0.507501 0.098578 2.137773 2.503586 0.055968 -0.314297 0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 1 1 0 1 0 1 0 0 1 0 1 1 0 1 0 1 0 0 1 0.042620 0.015981 -0.487638 -0.231282 -0.293553 -0.191861 0.005973 -0.519386 -0.021308 0.110553 0.188045 0.194030 0.074303 -0.141012 0.098220 0.280196 3.486585 -0.071219 -0.242995 0.112188 -0.002410 0.085824 -0.179351 -0.244309 -0.048686 0.205543 0.135025 0.482238 0.210107 -0.071866 -0.004019 -0.180991 0.577728 -0.367862 2.266167 0.049814 -0.068544 0.114125 0.055516 -0.031292 -0.423320 -0.242380 -0.040821 0.167895 0.045804 0.451037 0.204431 -0.058072 -0.135103 -0.046869 0.071325 -0.320034 2.274599 -0.330385 -0.627483 -0.114365 0.114085 0.177766 0.106177 -0.259375 0.092285 -0.005077 0.261092 -0.138407 0.034866 -0.118280 -0.172725 -0.281692 0.266667 -0.051936 2.004911 0.067136 -0.099879 -0.116322 -0.127396 -0.264771 -0.349473 -0.155593 -0.282978 -0.498084 0.135298 0.080397 -0.132282 0.234748 0.443107 -0.280855 0.075701 -0.148163 2.969444 -0.065711 0.042620 0.015981 -0.487638 -0.231282 -0.293553 -0.191861 0.005973 -0.519386 -0.021308 0.110553 0.188045 0.194030 0.074303 -0.141012 0.098220 0.280196 3.486585 -0.071219 -0.242995 0.112188 -0.002410 0.085824 -0.179351 -0.244309 -0.048686 0.205543 0.135025 0.482238 0.210107 -0.071866 -0.004019 -0.180991 0.577728 -0.367862 2.266167 0.049814 -0.068544 0.114125 0.055516 -0.031292 -0.423320 -0.242380 -0.040821 0.167895 0.045804 0.451037 0.204431 -0.058072 -0.135103 -0.046869 0.071325 -0.320034 2.274599 -0.330385 -0.627483 -0.114365 0.114085 0.177766 0.106177 -0.259375 0.092285 -0.005077 0.261092 -0.138407 0.034866 -0.118280 -0.172725 -0.281692 0.266667 -0.051936 2.004911 0.067136 -0.099879 -0.116322 -0.127396 -0.264771 -0.349473 -0.155593 -0.282978 -0.498084 0.135298 0.080397 -0.132282 0.234748 0.443107 -0.280855 0.075701 -0.148163 2.969444 -0.065711<br>1 0.094632 0.077247 -0.420146 0.682538 -0.813081 -0.806073 0.597392 1.000357 0.092491 -0.326729 0.023902 -0.849853 0.191944 0.815951 -0.057574 -0.897024 -0.192921 -1.209742 1.299109 -0.004309 -0.592330 -1.042349 1.120667 0.487325 0.165953 -0.084156 -0.525555 -0.664330 -0.160853 0.222449 0.094632 0.077247 -0.420146 0.682538 -0.813081 -0.806073 0.597392 1.000357 0.092491 -0.326729 0.023902 -0.849853 0.191944 0.815951 -0.057574 -0.897024 -0.192921 -1.209742 1.299109 -0.004309 -0.592330 -1.042349 1.120667 0.487325 0.165953 -0.084156 -0.525555 -0.664330 -0.160853 0.222449 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 1 0 1 0 1 0 1 0 0 1 0 1 1 0 1 0 1 0 0 1 0 1 -0.172344 0.306537 -0.284819 -0.154103 -0.269389 -0.209359 0.107670 0.479141 0.446757 -0.078369 -0.119798 0.200447 -0.049071 0.332875 0.268584 0.230138 2.439955 -0.134744 0.171250 0.249259 -0.114932 0.204678 0.279941 -0.160703 0.199625 0.222903 -0.177723 0.286112 -0.106457 0.379909 0.439271 -0.253183 0.378089 0.230612 3.638519 -0.128900 0.165036 0.748550 0.124970 0.010211 0.394594 8.848152 -0.150946 -0.410799 0.089460 0.455369 0.987360 0.098155 0.320007 -0.398864 0.127288 0.257199 -0.634356 0.232878 0.243321 0.097346 -0.124149 -0.106703 0.277970 -0.258756 0.252437 -0.072303 0.147313 0.256789 -0.150161 -0.224142 -0.323318 0.295318 0.085760 -0.330488 2.081970 0.051197 -0.114616 -0.225269 -0.139060 -0.645426 0.382825 -0.190596 0.212243 0.145735 -0.382326 0.145038 -0.276034 0.043593 0.360232 0.024999 0.405824 0.047757 3.002642 0.071456 -0.172344 0.306537 -0.284819 -0.154103 -0.269389 -0.209359 0.107670 0.479141 0.446757 -0.078369 -0.119798 0.200447 -0.049071 0.332875 0.268584 0.230138 2.439955 -0.134744 0.171250 0.249259 -0.114932 0.204678 0.279941 -0.160703 0.199625 0.222903 -0.177723 0.286112 -0.106457 0.379909 0.439271 -0.253183 0.378089 0.230612 3.638519 -0.128900 0.165036 0.748550 0.124970 0.010211 0.394594 8.848152 -0.150946 -0.410799 0.089460 0.455369 0.987360 0.098155 0.320007 -0.398864 0.127288 0.257199 -0.634356 0.232878 0.243321 0.097346 -0.124149 -0.106703 0.277970 -0.258756 0.252437 -0.072303 0.147313 0.256789 -0.150161 -0.224142 -0.323318 0.295318 0.085760 -0.330488 2.081970 0.051197 -0.114616 -0.225269 -0.139060 -0.645426 0.382825 -0.190596 0.212243 0.145735 -0.382326 0.145038 -0.276034 0.043593 0.360232 0.024999 0.405824 0.047757 3.002642 0.071456<br>2 -0.633065 -0.564679 -0.201971 0.553437 -0.813081 -0.926993 -0.110481 -0.622870 0.305346 -0.195205 0.023902 -1.194670 0.455184 -0.390138 1.061167 1.708587 0.223211 -0.273893 1.299109 1.129474 -0.371032 -0.888324 0.529675 0.179440 -0.858690 -0.266891 -1.009797 -0.664330 0.272789 0.651846 -0.633065 -0.564679 -0.201971 0.553437 -0.813081 -0.926993 -0.110481 -0.622870 0.305346 -0.195205 0.023902 -1.194670 0.455184 -0.390138 1.061167 1.708587 0.223211 -0.273893 1.299109 1.129474 -0.371032 -0.888324 0.529675 0.179440 -0.858690 -0.266891 -1.009797 -0.664330 0.272789 0.651846 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 0 0 1 0 0 1 0 1 0 1 1 0 0 1 0 1 0 1 0 1 1 0 0 1 0.155041 0.075458 0.128204 -0.307203 0.226403 -0.235786 -0.015866 0.107595 -0.196787 0.240416 -0.281368 -0.220980 -0.138494 -0.494391 0.455474 -0.202156 2.321033 0.441397 -0.028507 0.199534 0.015414 0.077699 -0.406724 -0.202727 0.282589 -0.146017 -0.279890 0.480175 0.223381 -0.107671 0.251850 0.161269 0.230595 0.502799 2.520607 0.274084 -0.427208 -0.002895 -0.226712 -0.093768 -0.299545 -0.240582 -0.367017 -0.259404 0.209881 0.137372 0.045118 -0.266958 -0.375146 0.135846 -0.216955 0.132457 2.391213 -0.107390 0.314599 -0.374596 0.125122 -0.136581 -0.160235 -0.250860 0.415069 -0.516348 -0.137149 -0.346949 0.004601 0.005514 0.085664 0.450544 0.349097 -0.142490 2.788246 -0.500418 0.489721 -0.311144 0.089835 0.190793 -0.108388 -0.262946 0.144517 -0.096459 0.182052 -0.095634 -0.108274 -0.081491 -0.486720 -0.193312 -0.159213 -0.017981 1.531305 0.061710 0.155041 0.075458 0.128204 -0.307203 0.226403 -0.235786 -0.015866 0.107595 -0.196787 0.240416 -0.281368 -0.220980 -0.138494 -0.494391 0.455474 -0.202156 2.321033 0.441397 -0.028507 0.199534 0.015414 0.077699 -0.406724 -0.202727 0.282589 -0.146017 -0.279890 0.480175 0.223381 -0.107671 0.251850 0.161269 0.230595 0.502799 2.520607 0.274084 -0.427208 -0.002895 -0.226712 -0.093768 -0.299545 -0.240582 -0.367017 -0.259404 0.209881 0.137372 0.045118 -0.266958 -0.375146 0.135846 -0.216955 0.132457 2.391213 -0.107390 0.314599 -0.374596 0.125122 -0.136581 -0.160235 -0.250860 0.415069 -0.516348 -0.137149 -0.346949 0.004601 0.005514 0.085664 0.450544 0.349097 -0.142490 2.788246 -0.500418 0.489721 -0.311144 0.089835 0.190793 -0.108388 -0.262946 0.144517 -0.096459 0.182052 -0.095634 -0.108274 -0.081491 -0.486720 -0.193312 -0.159213 -0.017981 1.531305 0.061710<br>&quot;&quot;&quot;</pre><ol><li>Logistic Regression</li></ol><pre>baseline_clf = LogisticRegressionCV(cv=5, random_state=2009, max_iter=10000).fit(X_train, y_train)<br>lr_preds = baseline_clf.predict(X_test)<br><br># accuracy_score(y_test, lr_preds)<br>lr_accuracy = accuracy_score(y_test, lr_preds)<br>lr_f1 = f1_score(y_test, lr_preds)<br>print(f&quot;Logistic Regression accuracy = {lr_accuracy}, f1_score = {lr_f1}&quot;)<br># Logistic Regression accuracy = 0.5566065622228791, f1_score = 0.6033844526705446<br>confusion_matrix(y_test, lr_preds)<br>&quot;&quot;&quot;<br>array([[ 742,  913],<br>       [ 587, 1141]])<br>&quot;&quot;&quot;<br>#define metrics<br>y_pred_proba = baseline_clf.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.plot([0,1],[0,1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.title(&#39;ROC AUC curve for LR&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*PCOKQ3zUA6yrKZ4onVvlxw.png" /><figcaption>ROC AUC curve for LR</figcaption></figure><p>2. Decision Tree</p><pre>dt_clf = DecisionTreeClassifier(random_state=2009, max_depth=9, min_samples_leaf=2)<br>dt_clf = dt_clf.fit(X_train, y_train)<br>dt_preds = dt_clf.predict(X_test)<br><br># accuracy_score(y_test, dt_preds)<br>dt_accuracy = accuracy_score(y_test, dt_preds)<br>dt_f1 = f1_score(y_test, dt_preds)<br>print(f&quot;Decision Tree accuracy = {dt_accuracy}, f1_score = {dt_f1}&quot;)<br># Decision Tree accuracy = 0.5353236772095773, f1_score = 0.59358841778697<br>confusion_matrix(y_test, dt_preds)<br>&quot;&quot;&quot;<br>array([[ 663,  992],<br>       [ 580, 1148]])<br>&quot;&quot;&quot;<br>#define metrics<br>y_pred_proba = dt_clf.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.plot([0,1],[0,1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.title(&#39;ROC AUC curve for DT&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*ciWQF47ichO1hmhaHzksxw.png" /><figcaption>ROC AUC curve for DT</figcaption></figure><p>3. Random Forest</p><pre>rf_clf = RandomForestClassifier(n_estimators=250, max_depth=10, max_features=8, min_samples_split=2, random_state=2009)<br>rf_clf.fit(X_train, y_train)<br>rf_preds = rf_clf.predict(X_test)<br><br># accuracy_score(y_test, rf_preds)<br>rf_accuracy = accuracy_score(y_test, rf_preds)<br>rf_f1 = f1_score(y_test, rf_preds)<br>print(f&quot;Random Forest accuracy = {rf_accuracy}, f1_score = {rf_f1}&quot;)<br># Random Forest accuracy = 0.5755246822347029, f1_score = 0.6397390868038133<br>confusion_matrix(y_test, rf_preds)<br>&quot;&quot;&quot;<br>array([[ 672,  983],<br>       [ 453, 1275]])<br>&quot;&quot;&quot;<br>precision, recall, fscore, support = score(y_test, rf_preds)<br>print(&#39;precision: {}&#39;.format(precision))<br>print(&#39;recall: {}&#39;.format(recall))<br>print(&#39;fscore: {}&#39;.format(fscore))<br>print(&#39;support: {}&#39;.format(support))<br>&quot;&quot;&quot;<br>precision: [0.59733333 0.56465899]<br>recall: [0.4060423  0.73784722]<br>fscore: [0.48345324 0.63973909]<br>support: [1655 1728]<br>&quot;&quot;&quot;<br>#define metrics<br>y_pred_proba = rf_clf.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.plot([0,1],[0,1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.title(&#39;ROC AUC curve for RF&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*KjoCjvu3av_h1r3AomIawQ.png" /><figcaption>ROC AUC curve for RF</figcaption></figure><p>4. XGBoosting</p><pre>parameters = {&#39;n_estimators&#39;: 300,<br>        &#39;learning_rate&#39;: 0.05,<br>        &#39;max_depth&#39;: 7,<br>        &#39;subsample_size&#39;: 0.8,<br>        &#39;random_state&#39;: 2009,<br>        &#39;reg_alpha&#39;: 0.2,<br>        &#39;colsample_bytree&#39;: 0.5,<br>        &#39;reg_lambda&#39;: 4,<br>        &#39;min_child_weight&#39;: 80,<br>        # &#39;eval_metric&#39;: &#39;logloss&#39;<br>        }<br>model = xgb.XGBClassifier(**parameters)<br>model.fit(X_train, y_train)<br><br># # Predict<br># preds = model.predict(X_test)<br># # Score<br># accuracy_score(y_test, preds)<br># Predict<br>xgb_preds = model.predict(X_test)<br>xgb_accuracy = accuracy_score(y_test, xgb_preds)<br>xgb_f1 = f1_score(y_test, xgb_preds)<br>print(f&quot;XGBoosting accuracy = {xgb_accuracy}, f1_score = {xgb_f1}&quot;)<br># XGBoosting accuracy = 0.5758202778598877, f1_score = 0.6112164725006772<br>confusion_matrix(y_test, xgb_preds)<br>&quot;&quot;&quot;<br>array([[ 820,  835],<br>       [ 600, 1128]])<br>&quot;&quot;&quot;<br>precision, recall, fscore, support = score(y_test, xgb_preds)<br>print(&#39;precision: {}&#39;.format(precision))<br>print(&#39;recall: {}&#39;.format(recall))<br>print(&#39;fscore: {}&#39;.format(fscore))<br>print(&#39;support: {}&#39;.format(support))<br>&quot;&quot;&quot;<br>precision: [0.57746479 0.57463067]<br>recall: [0.49546828 0.65277778]<br>fscore: [0.53333333 0.61121647]<br>support: [1655 1728]<br>&quot;&quot;&quot;<br>#define metrics<br>y_pred_proba = model.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>#create ROC curve<br>plt.plot(fpr,tpr)<br>plt.plot([0,1],[0,1])<br>plt.ylabel(&#39;True Positive Rate&#39;)<br>plt.xlabel(&#39;False Positive Rate&#39;)<br>plt.title(&#39;ROC AUC curve for XGB&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*kzcMquJJzUVcDN-AX5kNQw.png" /><figcaption>ROC AUC curve for XGB</figcaption></figure><pre>model_list = [&#39;Logistic Regression&#39;, &#39;Decision Tree&#39;, &#39;Random Forest&#39;, &#39;XGBoosting&#39;]<br>accuracy_list = [lr_accuracy, dt_accuracy, rf_accuracy, xgb_accuracy]<br>f1_list = [lr_f1, dt_f1, rf_f1, xgb_f1]<br>res2_df = pd.DataFrame({<br>    &#39;model&#39;: model_list,<br>    &#39;accuracy_score&#39;: accuracy_list,<br>    &#39;f1_score&#39;: f1_list<br>})<br>res2_df</pre><pre>&quot;&quot;&quot;<br>model accuracy_score f1_score<br>0 Logistic Regression 0.556607 0.603384<br>1 Decision Tree 0.535324 0.593588<br>2 Random Forest 0.575525 0.639739<br>3 XGBoosting 0.575820 0.611216<br>&quot;&quot;&quot;</pre><p>Now we can compare the results from the previous features and the embedded features.</p><pre># Previous results:<br>model accuracy_score f1_score<br>0 Logistic Regression 0.556607 0.602754<br>1 Decision Tree 0.561336 0.639105<br>2 Random Forest 0.569022 0.641945<br>3 XGBoosting 0.573160 0.617989<br><br># Graph embedded results:<br>model accuracy_score f1_score<br>0 Logistic Regression 0.556607 0.603384<br>1 Decision Tree 0.535324 0.593588<br>2 Random Forest 0.575525 0.639739<br>3 XGBoosting 0.575820 0.611216</pre><p>It’s obvious that Decision Tree performs worse after we add the embedded features. The accuracy of Random Forest and XGBoosting get improved while the f1- scores drop slightly. We can also check the classification report after adding features.</p><pre>Random Forest Classification Report<br>              precision    recall  f1-score   support<br>     class 0       0.60      0.41      0.48      1655<br>     class 1       0.56      0.74      0.64      1728<br><br>    accuracy                           0.58      3383<br>   macro avg       0.58      0.57      0.56      3383<br>weighted avg       0.58      0.58      0.56      3383<br><br>XGBoosting Classification Report<br>              precision    recall  f1-score   support<br>     class 0       0.58      0.50      0.53      1655<br>     class 1       0.57      0.65      0.61      1728<br><br>    accuracy                           0.58      3383<br>   macro avg       0.58      0.57      0.57      3383<br>weighted avg       0.58      0.58      0.57      3383</pre><p>The new report demonstrates similar results to the previous one in that Random Forest has a higher recall for class label 1 while XGBoosting has a higher precision for class label 1. Generally, XGBoosting has a better f1-score for both classes.</p><p>In the future, we can also implement Neural Networks and SVM for this task.</p><blockquote>Summary</blockquote><p>In this part, I have visualized the game data for insights.</p><p>To construct classifiers, I made a pipeline for data preprocessing, feature selection, modeling, and evaluation. Feature Engineering is one of the most important sections of this project. Based on research, I first used the hero attributes mentioned above. By comparing the performance of the models, XGBoosting generates the best result with an accuracy=0.573. Then I tried graph embedding for the good/bad against relationships between the heroes and the accuracy of XGBoosting rises to 0.575 while the f1-score drops a little bit. In general, adding embedded features has limited improvement for the task.</p><p>To sum up, I find it hard to predict accurate results with hero data only. The <a href="https://dl.acm.org/doi/10.1145/3208788.3208800">paper</a> I referred to incorporated some in-game statistics such as GPM, hero damage, and so on. Their f1-score of Logistic Regression, Random Forest, and SVM achieves 0.6+.</p><p>Hence I believe the draft alone is important for victory, but it is not the dominating factor. And referred paper also generates a second dataset for prediction with all winning teams in the reserved matches having at least twice as many scores as their opponents. Probably we can try this in the future as well.</p><p>This is all for PART 2 of my project. Thank you for reviewing! Please let me know if there’s any problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/1*96PlOfZ9qWEQ9GwTCcJjPw.jpeg" /><figcaption>jiayou a</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf1e56346cca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science for DOTA2(PART 2— Heroes EDA)]]></title>
            <link>https://medium.com/@xiaoyigu/data-science-for-dota2-part-2-heroes-eda-15cd705d2c76?source=rss-57eb0aee8b95------2</link>
            <guid isPermaLink="false">https://medium.com/p/15cd705d2c76</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[networkx]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[visualization]]></category>
            <dc:creator><![CDATA[Alleria]]></dc:creator>
            <pubDate>Thu, 18 May 2023 19:23:36 GMT</pubDate>
            <atom:updated>2023-05-18T23:23:40.163Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Keywords:</strong> EDA, Seaborn, Networkx, Topic Modeling, clustering</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dtu1uGpoS-KybQ_kTLSQ9g.png" /><figcaption>Arlinton Major 4 TPs for Ame</figcaption></figure><blockquote>Definitions</blockquote><p>Before exploring the data, I want to explain some definitions of the heroes in DOTA2. You can refer to <a href="https://dota2.fandom.com/wiki/Heroes">DOTA2wiki</a> for more information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z34eTHTwACPLmpyzweHdUA.png" /><figcaption>DOTA2 Map Latest Version</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*l2WqEotoLGtZwTBC" /><figcaption>Map Definition on DOTA2 WIKI(previous version)</figcaption></figure><ol><li>Camps. DOTA2 is a 5V5 game with 2 camps. As you can see in this map, the darker side(top right part) is the DIRE. The brighter part(bottom left part) is the RADIANT. There are 3 lanes for each camp. The horizontal two lanes are called the safe lane, and the vertical two are called the off lane. The diagonal is the mid lane. Usually, 2 heroes will go to the safe lane, 2 to the off lane and 1 hero to the mid lane.</li><li>Primary Attribute. There are four primary attributes in the current version: Strength, Agility, Intelligence, and Universal. Generally, strength heroes will have more hp, agility heroes will have higher attack speed, intelligence heroes will have more mana and universal heroes will have a balance of hp, attack speed and mana. Different attributes will affect the roles, choice of items, and strategies. There are altogether 124 heroes and for each primary attribute, there are 31 heroes.</li><li>Attack Type. DOTA2 has two attack types: Melee and Ranged. Melee means you have to be very close to the heroes in order to attack. Ranged means you can attack your opponent at a distance. But even if you are melee, your attack range will be a little bit different and you can use items to make your attack range even further.</li><li><a href="https://dota2.fandom.com/wiki/Role">Roles</a>. In a game, we basically define the heroes in 5 positions. The 2 heroes on the safe lane will have the role <strong>“Carry”</strong> and <strong>“Hard Support”</strong>. <strong>Carries</strong> have the largest amount of resources and shoulder the greatest responsibility to carry the team to win in the late game. <strong>Supports</strong> are heroes whose purpose is to keep their allies alive and give them opportunities to earn more gold and experience. Hard supports usually have the fewest resources. The 2 heroes on the off lane will have the role <strong>“Offlaner”</strong> and <strong>“Soft Support”</strong>. <strong>Offlaners</strong> heroes are those with abilities that allow them to solo the “suicide lane” (top lane for Radiant, bottom lane for Dire). Soft supports enjoy a little bit more resources than hard supports. The heroes on the mid lane are more flexible and the mid players should grasp the right timing to help the other lanes. Meanwhile, sometimes we will detailedly divide the heroes into roles such as <strong>Escape, Nuker, Initiator</strong>, etc. based on their abilities.</li></ol><p>This is the hero information downloaded in the previous <a href="https://medium.com/@xiaoyigu/data-science-for-dota2-part-1-data-collection-55d7d7cb07c1">part</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MaLp7aE1L8VDMY8RMOFGVg.png" /><figcaption>Screenshot of the Hero information</figcaption></figure><p>Our data includes both numerical and categorical variables:</p><pre>hero_id                 int64<br>official_name          object<br>primary_attr           object<br>attack_type            object<br>roles                  object<br>legs                    int64<br>name_id                object<br>pros                   object<br>cons                   object<br>base_strength         float64<br>add_strength          float64<br>lvl30_strength        float64<br>base_agility          float64<br>add_agility           float64<br>lvl30_agility         float64<br>base_intelligence     float64<br>add_intelligence      float64<br>lvl30_intelligence    float64<br>bio                    object<br>bad_against            object<br>good_against           object<br>work_well_with         object<br>link                   object<br>attribute              object<br>dtype: object</pre><p>The hero_id, legs(legs of the heroes), and all the strength/agility/intelligence values are numerical. More detailedly, base_strength means the initial strength of a hero, add_strength means the additional gained strength when the hero levels up, and lvl30_strength means the final strength when the hero levels up to 30. Here are the statistics of the numerical variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYV4N_FfXM0L-iKMuFLEHg.png" /><figcaption>Numerical Variables</figcaption></figure><p>Then for the categorical features, we have:</p><pre>official_name: full name of the heroes, e.g. Anti-Mage <br>primary_attr: the abbreviation for attribute, e.g. agi(for agility)<br>attack_type: includes Melee and Ranged<br>roles: the common roles of the hero in a list, e.g. [&#39;Carry&#39;, &#39;Escape&#39;, &#39;Nuker&#39;]<br>name_id: the shorter version of hero names, e.g. antimage<br>pros: description of hero advantages, e.g. Extremely mobile and hard to catch<br>cons: description of hero disadvantages, e.g. Low stat gain.\nLow health and mana.<br>bio: background of the hero in the DOTA2 world, e.g. &quot;They who live by the wand shall die by my blade.&quot;<br>bad_against: a list of heroes that counter the current hero<br>good_against: a list of heroes the current hero can counter<br>work_well_with: a list of heroes the current hero can work with<br>link: a detailed link of the hero in dota2wiki<br>attribute: full attribute name</pre><p>First of all, we can look at the attack type distribution of the 124 heroes.</p><pre># import packages<br>import pandas as pd<br>import os<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import ast<br>import matplotlib.patches as mpatches<br>from itertools import combinations<br>from sklearn.decomposition import LatentDirichletAllocation<br>from sklearn.feature_extraction.text import CountVectorizer<br>from sklearn.feature_extraction import text <br><br>pd.set_option(&#39;display.max_columns&#39;, None)</pre><pre>heroes_df = pd.read_csv(&#39;all_heroes.csv&#39;)<br># attack type analysis<br><br># setting the dimensions of the plot<br>fig, ax = plt.subplots(figsize=(5, 4))<br>sns.set_palette(&quot;Paired&quot;)<br>color_list = sns.color_palette(&quot;Paired&quot;).as_hex()<br># https://seaborn.pydata.org/generated/seaborn.color_palette.html<br># drawing the plot<br><br>sns.countplot(x = heroes_df[&#39;attack_type&#39;], ax=ax)<br>plt.title(&#39;Count of Different Attack Type&#39;)<br>plt.show()<br># the counts of melee and ranges are almost the same</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*Z9Tna73Ritgr2_vYNHdprw.png" /><figcaption>Attack Type Count</figcaption></figure><p>As you can see, DOTA2 has more ranged heroes than melee heroes. But they are almost in the same amount.</p><p>Next, we can have a look at the distribution of the basic strength/agility/intelligence of each hero.</p><pre># hero attribute analysis<br>def attr_analysis(heroes_df, attr_list):<br>    fig, axes = plt.subplots(1, len(attr_list), figsize=(8,3))<br>    # plt.title(f&#39;Distribution of Different Attributes&#39;, loc=&#39;left&#39;, x=0)<br>    for i, ax in zip(range(len(attr_list)), axes.flat):<br>        sns.histplot(heroes_df, x=attr_list[i], color=color_list[5-2*i], ax=ax)<br>    <br>    plt.show()<br>attr_analysis(heroes_df, [&#39;base_strength&#39;, &#39;base_agility&#39;, &#39;base_intelligence&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*6V1NhLlAVQYK388qu_59CQ.png" /><figcaption>Base attributes Distributions</figcaption></figure><p>It seems that the base attributes value has normal distributions. Interestingly, some heroes have 0 basic strength, agility and intelligence. I know that Medusa has 0 base strength and Ogre Magi has 0 intelligence. Let’s see who has 0 base agility.</p><pre>heroes_df[heroes_df[&#39;base_agility&#39;]==0] # that&#39;s tiny</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*cpORVhrezwbLmyxJK2AbhQ.png" /><figcaption>That’s Tiny</figcaption></figure><p>Then, we can look at the roles.</p><pre>roles_dict = {}<br>for roles in heroes_df.roles.tolist():<br>    for role in ast.literal_eval(roles):<br>        # print(role)<br>        if role not in roles_dict:<br>            roles_dict[role] = 1<br>        else:<br>            roles_dict[role] += 1<br>sns.barplot(data = pd.DataFrame({<br>    &#39;role&#39;: list(roles_dict.keys()),<br>    &#39;count&#39;: list(roles_dict.values())}),<br>            x = &#39;role&#39;, y=&#39;count&#39;)<br>plt.title(&#39;Distribution of Roles Count&#39;)<br>plt.show()<br># Reference: https://dota2.fandom.com/wiki/Role<br># Disabler and Nuker have the highest count</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*weIO3er0PGWD1s6UR_i8Eg.png" /><figcaption>Role Distributions</figcaption></figure><p>As you can see, Disablers and Nukers have the highest count. Heroes tagged as Disabler generally have abilities which are more focused to reliable crowd control, whether by single target or by area. Nukers are heroes with fast, strong, and/or sustainable spell or magical damage output, whether it be through single-target spells or area-of-effect ones.</p><p>What makes DOTA2 very complicated is the relationships of heroes. There is a ban and pick section(BP) at the beginning of each game. Players need to pick the heroes while considering the if the 5 heroes can work together well/if the opposite heroes will count our heroes/if our heroes can counter their draft.</p><p>Since we already have the bios of each hero, I will first calculate the similarity between each hero based on bios using TF-IDF. TF-IDF vectorizer transforms text input into numerical vectors. Unlike using word counts to represent a corpus, TF-IDF is helpful to emphasize the representative words. TF means term frequency(how many times the word appears in the document) and IDF means inverse document frequency(a measure of how much information the word provides, i.e., if it is common or rare across all documents). For example, if we could like to transform the job description corpus, which contains “Company Apple”, “Company Google” and “Company Amazon”, the word “Company” is not important, and “Apple”, “Google”, and “Amazon” are useful. TF-IDF can help us identify those relatively important words.</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.metrics.pairwise import linear_kernel<br>from sklearn.cluster import MiniBatchKMeans<br># reference: https://www.kaggle.com/code/yclaudel/recommendation-engine-with-networkx<br><br>text_content = heroes_df[&#39;bio&#39;]<br>vector = TfidfVectorizer(max_df=0.4,         # drop words that occur in more than X percent of documents<br>                            min_df=1,      # only use words that appear at least X times<br>                            stop_words=&#39;english&#39;, # remove stop words<br>                            lowercase=True, # Convert everything to lower case <br>                            use_idf=True,   # Use idf<br>                            norm=u&#39;l2&#39;,     # Normalization<br>                            smooth_idf=True # Prevents divide-by-zero errors<br>                            )<br>tfidf_bio = vector.fit_transform(text_content)<br><br># Clustering  Kmeans<br>k = 5<br># random_state has to be 2009, the id of my favorite player(DotA1)<br>kmeans = MiniBatchKMeans(n_clusters = k, random_state=2009)<br>kmeans.fit(tfidf_bio)<br>    <br>request_transform = vector.transform(heroes_df[&#39;bio&#39;])<br># new column cluster based on the description<br>heroes_df[&#39;cluster&#39;] = kmeans.predict(request_transform) <br><br>heroes_df[&#39;cluster&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*yYAQHg9dti8ipO6sduHkdA.png" /><figcaption>Clusters</figcaption></figure><p>You can use the scree plots or silhouette scores to find the best number of clusters. Here I manually set it as 5.</p><pre>for cluster in range(k):<br>    heroes_list = heroes_df[heroes_df[&#39;cluster&#39;]==cluster].official_name.tolist()<br>    # print(heroes_list)<br>    print(f&quot;cluster {cluster} --  heroes: {str(heroes_list)}&quot;)<br><br># output<br>&quot;&quot;&quot;<br>cluster 0 --  heroes: [&#39;Bane&#39;, &#39;Shadow Fiend&#39;, &#39;Puck&#39;, &#39;Razor&#39;, &#39;Sand King&#39;]<br>cluster 1 --  heroes: [&#39;Axe&#39;, &#39;Earthshaker&#39;, &#39;Morphling&#39;, &#39;Pudge&#39;, &#39;Tiny&#39;, &#39;Windranger&#39;, &#39;Kunkka&#39;, &#39;Shadow Shaman&#39;, &#39;Slardar&#39;, &#39;Tidehunter&#39;, &#39;Lich&#39;, &#39;Enigma&#39;, &#39;Tinker&#39;, &#39;Sniper&#39;, &#39;Warlock&#39;, &#39;Wraith King&#39;, &#39;Templar Assassin&#39;, &#39;Dragon Knight&#39;, &#39;Dazzle&#39;, &#39;Leshrac&#39;, &quot;Nature&#39;s Prophet&quot;, &#39;Dark Seer&#39;, &#39;Omniknight&#39;, &#39;Broodmother&#39;, &#39;Bounty Hunter&#39;, &#39;Weaver&#39;, &#39;Chen&#39;, &#39;Spectre&#39;, &#39;Doom&#39;, &#39;Ursa&#39;, &#39;Spirit Breaker&#39;, &#39;Gyrocopter&#39;, &#39;Alchemist&#39;, &#39;Invoker&#39;, &#39;Outworld Destroyer&#39;, &#39;Brewmaster&#39;, &#39;Lone Druid&#39;, &#39;Chaos Knight&#39;, &#39;Meepo&#39;, &#39;Treant Protector&#39;, &#39;Rubick&#39;, &#39;Disruptor&#39;, &#39;Nyx Assassin&#39;, &#39;Keeper of the Light&#39;, &#39;Io&#39;, &#39;Visage&#39;, &#39;Slark&#39;, &#39;Troll Warlord&#39;, &#39;Bristleback&#39;, &#39;Tusk&#39;, &#39;Abaddon&#39;, &#39;Legion Commander&#39;, &#39;Techies&#39;, &#39;Ember Spirit&#39;, &#39;Earth Spirit&#39;, &#39;Underlord&#39;, &#39;Phoenix&#39;, &#39;Arc Warden&#39;, &#39;Pangolier&#39;, &#39;Grimstroke&#39;, &#39;Hoodwink&#39;, &#39;Void Spirit&#39;, &#39;Snapfire&#39;, &#39;Dawnbreaker&#39;, &#39;Marci&#39;, &#39;Muerta&#39;]<br>cluster 2 --  heroes: [&#39;Sven&#39;, &#39;Zeus&#39;, &#39;Necrophos&#39;, &#39;Beastmaster&#39;, &#39;Queen of Pain&#39;, &#39;Death Prophet&#39;, &#39;Pugna&#39;, &#39;Luna&#39;, &#39;Clockwerk&#39;, &#39;Night Stalker&#39;, &#39;Batrider&#39;, &#39;Lycan&#39;, &#39;Ogre Magi&#39;, &#39;Undying&#39;, &#39;Magnus&#39;, &#39;Oracle&#39;, &#39;Monkey King&#39;, &#39;Dark Willow&#39;, &#39;Mars&#39;, &#39;Primal Beast&#39;]<br>cluster 3 --  heroes: [&#39;Anti-Mage&#39;, &#39;Bloodseeker&#39;, &#39;Juggernaut&#39;, &#39;Mirana&#39;, &#39;Storm Spirit&#39;, &#39;Vengeful Spirit&#39;, &#39;Riki&#39;, &#39;Venomancer&#39;, &#39;Phantom Assassin&#39;, &#39;Lifestealer&#39;, &#39;Enchantress&#39;, &#39;Huskar&#39;, &#39;Medusa&#39;, &#39;Centaur Warrunner&#39;, &#39;Skywrath Mage&#39;, &#39;Elder Titan&#39;]<br>cluster 4 --  heroes: [&#39;Crystal Maiden&#39;, &#39;Drow Ranger&#39;, &#39;Phantom Lancer&#39;, &#39;Lina&#39;, &#39;Lion&#39;, &#39;Witch Doctor&#39;, &#39;Faceless Void&#39;, &#39;Viper&#39;, &#39;Clinkz&#39;, &#39;Jakiro&#39;, &#39;Ancient Apparition&#39;, &#39;Silencer&#39;, &#39;Shadow Demon&#39;, &#39;Naga Siren&#39;, &#39;Timbersaw&#39;, &#39;Terrorblade&#39;, &#39;Winter Wyvern&#39;]<br>&quot;&quot;&quot;</pre><p>We can even use the LDA topic modeling method to detect the keywords for each bio. You may refer to this great <a href="https://www.kaggle.com/code/maksimeren/covid-19-literature-clustering#Topic-Modeling-on-Each-Cluster">notebook</a>.</p><pre># Functions for printing keywords for each hero bio<br>def selected_topics(model, vectorizer, top_n=4):<br>    current_words = []<br>    keywords = []<br>    <br>    for idx, topic in enumerate(model.components_):<br>        words = [(vectorizer.get_feature_names_out()[i], topic[i]) for i in topic.argsort()[:-top_n - 1:-1]]<br>        for word in words:<br>            if word[0] not in current_words:<br>                keywords.append(word)<br>                current_words.append(word[0])<br>                <br>    keywords.sort(key = lambda x: x[1])  <br>    keywords.reverse()<br>    return_values = []<br>    for ii in keywords:<br>        return_values.append(ii[0])<br>    # print(&#39;**&#39;,str(return_values))<br>    return return_values<br><br># def spacy_tokenizer(sentence):<br>#     nlp = nlp = spacy.load(&quot;en_core_web_sm&quot;)<br>#     return [word.lemma_ for word in nlp(sentence) if not (word.like_num or word.is_stop or word.is_punct or word.is_space or len(word)==1)]<br><br>def LDA(best_k, X_df):<br>    # First, we will create k vectorizers, one for each of our cluster labels<br>    vectorizers = []<br>    <br>    # add stopwords, you can remove some useless words here<br>    my_additional_stop_words = {&#39;david&#39;,&#39;voice&#39;,&#39;the&#39;,&#39;like&#39;,&#39;began&#39;,&#39;kind&#39;,&#39;boy&#39;,&#39;people&#39;}<br>    stop_words = text.ENGLISH_STOP_WORDS.union(my_additional_stop_words)<br>    for ii in range(0, best_k):<br>        # Creating a vectorizer<br>        vectorizers.append(CountVectorizer(min_df=3, stop_words=stop_words, lowercase=True, token_pattern=&#39;[a-zA-Z\-][a-zA-Z\-]{2,}&#39;))<br>    <br>    # Now we will vectorize the data from each of our clusters<br>    vectorized_data = []<br>    for current_cluster, cvec in enumerate(vectorizers):<br>        try:<br>            vectorized_data.append(cvec.fit_transform(X_df.loc[X_df[&#39;cluster&#39;] == current_cluster, &#39;bio&#39;]))<br>        except Exception as e:<br>            # print(&quot;Not enough instances in cluster: &quot; + str(current_cluster))<br>            vectorized_data.append(None)<br>            <br>    # number of topics per cluster<br>    NUM_TOPICS_PER_CLUSTER = best_k<br>    lda_models = []<br>    for ii in range(0, best_k):<br>        # Latent Dirichlet Allocation Model<br>        lda = LatentDirichletAllocation(n_components=NUM_TOPICS_PER_CLUSTER, max_iter=10, learning_method=&#39;online&#39;,verbose=False, random_state=2009)<br>        lda_models.append(lda)<br>    <br>    # For each cluster, we had created a corresponding LDA model in the previous step. We will now fit_transform all the LDA models on their respective cluster vectors<br>    clusters_lda_data = []<br>    for current_cluster, lda in enumerate(lda_models):<br>        # print(&quot;Current Cluster: &quot; + str(current_cluster))<br>        <br>        if vectorized_data[current_cluster] != None:<br>            clusters_lda_data.append((lda.fit_transform(vectorized_data[current_cluster])))<br>    <br>    # Extracts the keywords from each cluster<br>    all_keywords = []<br>    for current_vectorizer, lda in enumerate(lda_models):<br>        # print(&quot;Current Cluster: &quot; + str(current_vectorizer))<br><br>        if vectorized_data[current_vectorizer] != None:<br>            all_keywords.append(selected_topics(lda, vectorizers[current_vectorizer]))<br>    <br>    return all_keywords<br><br>all_keywords = LDA(k, heroes_df)<br><br>for cluster in range(k):<br>    keyword_list = all_keywords[cluster]<br>    # print(heroes_list)<br>    print(f&quot;cluster {cluster} --  keywords: {str(keyword_list)}&quot;)<br><br># output<br>&quot;&quot;&quot;<br>cluster 0 --  keywords: [&#39;form&#39;, &#39;lore&#39;, &#39;responses&#39;]<br>cluster 1 --  keywords: [&#39;dark&#39;, &#39;light&#39;, &#39;world&#39;, &#39;responses&#39;, &#39;seed&#39;, &#39;lore&#39;, &#39;power&#39;, &#39;knight&#39;, &#39;ancient&#39;, &#39;spirit&#39;, &#39;long&#39;]<br>cluster 2 --  keywords: [&#39;beast&#39;, &#39;night&#39;, &#39;dead&#39;, &#39;kin&#39;, &#39;king&#39;, &#39;creature&#39;, &#39;responses&#39;, &#39;pain&#39;, &#39;lore&#39;, &#39;death&#39;, &#39;father&#39;, &#39;fate&#39;, &#39;high&#39;, &#39;son&#39;]<br>cluster 3 --  keywords: [&#39;power&#39;, &#39;isle&#39;, &#39;form&#39;, &#39;responses&#39;, &#39;new&#39;, &#39;sacred&#39;, &#39;world&#39;, &#39;known&#39;, &#39;blood&#39;, &#39;lore&#39;, &#39;energy&#39;, &#39;life&#39;, &#39;creature&#39;, &#39;body&#39;, &#39;mortal&#39;, &#39;long&#39;, &#39;day&#39;]<br>cluster 4 --  keywords: [&#39;demon&#39;, &#39;time&#39;, &#39;hell&#39;, &#39;ice&#39;, &#39;lore&#39;, &#39;responses&#39;, &#39;greatest&#39;, &#39;day&#39;, &#39;final&#39;, &#39;single&#39;, &#39;world&#39;, &#39;alias&#39;, &#39;waste&#39;, &#39;power&#39;, &#39;spells&#39;]<br>&quot;&quot;&quot;</pre><p>It is shown that the keywords in cluster 0 include “form, lore, and responses”. And the heroes in cluster 0 are ‘Bane’, ‘Shadow Fiend’, ‘Puck’, ‘Razor’, and ‘Sand King’. Lore might be a good keyword for these heroes. You may explore the keywords by changing the number of clusters and parameters.</p><p>We can also transform the pros and cons of each hero as we embed the bios.</p><pre>tfidf_pros = vector.fit_transform(heroes_df[&#39;pros&#39;].fillna(&#39;&#39;))<br>tfidf_cons = vector.fit_transform(heroes_df[&#39;cons&#39;].fillna(&#39;&#39;))</pre><blockquote>Networkx</blockquote><p>Based on the relationships of the heroes, I will create a graph to visualize the relationships between the heroes. I mainly use the Networkx package(refer to this <a href="https://www.kaggle.com/code/yclaudel/recommendation-engine-with-networkx">notebook</a>)</p><pre>G_rl = nx.Graph(label=&#39;HEROES_RELATIONSHIP&#39;)<br>start_time = time.time()<br><br>for i, rowi in heroes_df.iterrows():<br>    if (i%100==0):<br>        print(&quot; iter {} -- {} seconds -- &quot;.format(i, time.time()-start_time))<br>        <br>    G_rl.add_node(rowi[&#39;official_name&#39;], key=rowi[&#39;hero_id&#39;], label=&#39;HERO&#39;, \<br>        h_attr=rowi[&#39;attribute&#39;])<br>    G_rl.add_edge(rowi[&#39;official_name&#39;], rowi[&#39;official_name&#39;], label=&#39;SAME_HERO&#39;)<br>    <br>    for element in ast.literal_eval(rowi.bad_against):<br>        G_rl.add_node(element, label=&#39;HERO&#39;)<br>        G_rl.add_edge(rowi[&#39;official_name&#39;], element, label=&#39;BAD_AGAINST&#39;)<br>    <br>    for element in ast.literal_eval(rowi.good_against):<br>        G_rl.add_node(element, label=&#39;HERO&#39;)<br>        G_rl.add_edge(rowi[&#39;official_name&#39;], element, label=&#39;GOOD_AGAINST&#39;)<br>        <br>    for element in ast.literal_eval(rowi.work_well_with):<br>        G_rl.add_node(element, label=&#39;HERO&#39;)<br>        G_rl.add_edge(rowi[&#39;official_name&#39;], element, label=&#39;WORK_WELL_WITH&#39;)<br>        <br>print(&quot; finish -- {} seconds --&quot;.format(time.time() - start_time))    <br><br># output<br># iter 0 -- 0.0005919933319091797 seconds -- <br># iter 100 -- 0.02933788299560547 seconds -- <br># finish -- 0.03383302688598633 seconds --</pre><p>For the bio/pros/cons similarity, I will also build a graph. We define the similarity calculation first and return the top 5 similar heroes.</p><pre># Find similar : get the top_n heroes with bio similar to the target hero bio <br>def find_similar(tfidf_matrix, index, top_n = 5):<br>    cosine_similarities = linear_kernel(tfidf_matrix[index:index+1], tfidf_matrix).flatten()<br>    related_docs_indices = [i for i in cosine_similarities.argsort()[::-1] if i != index] # prevent choosing itself<br>    return [index for index in related_docs_indices][0:top_n] </pre><pre># build similarity graph<br>G_sim = nx.Graph(label=&#39;HEROES_SIMILARITY&#39;)<br>start_time = time.time()<br><br>for i, rowi in heroes_df.iterrows():<br>    if (i%100==0):<br>        print(&quot; iter {} -- {} seconds -- &quot;.format(i, time.time()-start_time))<br><br>    indices_bio = find_similar(tfidf_bio, i ,top_n= 5)<br>    # s_bio_node = f&quot;Sim({rowi[&#39;official_name&#39;]})Bio&quot;<br>    # G_sim.add_node(s_bio_node, label=&#39;BIO_SIMILAR&#39;)<br>    # G_sim.add_edge(rowi[&#39;official_name&#39;], rowi[&#39;official_name&#39;], label=&#39;SAME_HERO&#39;)<br>    for element in indices_bio:<br>        G_sim.add_edge(rowi[&#39;official_name&#39;], heroes_df[&#39;official_name&#39;].loc[element], label=&#39;BIO_SIMILARITY&#39;)<br><br>    indices_pros = find_similar(tfidf_pros, i ,top_n= 5)<br>    # s_p_node = f&quot;Sim({rowi[&#39;official_name&#39;]})Pro&quot;<br>    # G_sim.add_node(s_p_node, label=&#39;PRO_SIMILAR&#39;)<br>    # G_sim.add_edge(rowi[&#39;official_name&#39;], s_p_node, label=&#39;PRO_SIMILARITY&#39;)<br>    for element in indices_pros:<br>        G_sim.add_edge(rowi[&#39;official_name&#39;], heroes_df[&#39;official_name&#39;].loc[element], label=&#39;PRO_SIMILARITY&#39;)<br>        <br>    indices_cons = find_similar(tfidf_cons, i ,top_n= 5)<br>    # s_c_node = f&quot;Sim({rowi[&#39;official_name&#39;]})Con&quot;<br>    # G_sim.add_node(s_c_node, label=&#39;CON_SIMILAR&#39;)<br>    # G_sim.add_edge(rowi[&#39;official_name&#39;], s_c_node, label=&#39;CON_SIMILARITY&#39;)<br>    for element in indices_cons:<br>        G_sim.add_edge(rowi[&#39;official_name&#39;], heroes_df[&#39;official_name&#39;].loc[element], label=&#39;CON_SIMILARITY&#39;) <br>print(&quot; finish -- {} seconds --&quot;.format(time.time() - start_time))   </pre><p>Then we can get the nodes and visualize the graphs for each hero.</p><pre>def get_all_adj_nodes(G, selected_hero, num_nodes):<br>    sub_graph = set()<br>    if num_nodes &gt; 124:<br>        num_nodes = 124 # max hero count=124<br>    sub_graph.add(selected_hero)<br>    for e in G.neighbors(selected_hero):<br>        if len(sub_graph) &gt; num_nodes:<br>            break<br>        sub_graph.add(e)<br>    return list(sub_graph)<br><br>def draw_sub_graph_counter(G, sub_graph, selected_hero, counter_type=&#39;BAD_AGAINST&#39;):<br>    # sub_graph.remove(selected_hero)<br>    # sub_graph = G.subgraph(sub_graph)<br>    <br>    colors = []<br>    for e in sub_graph: <br>        if e == selected_hero:<br>            print(e)<br>            colors.append(color_list[8]) # itself<br>        elif G[selected_hero][e][&#39;label&#39;] == &#39;BAD_AGAINST&#39;:<br>            colors.append(color_list[5])<br>        elif G[selected_hero][e][&#39;label&#39;] == &#39;GOOD_AGAINST&#39;:<br>            colors.append(color_list[1])<br>        elif G[selected_hero][e][&#39;label&#39;] == &#39;WORK_WELL_WITH&#39;:<br>            colors.append(color_list[3])<br>    # print(colors)<br>    plt.figure(figsize=(10,6))<br>    sub_graph = G.subgraph(sub_graph)<br>    print(sub_graph)<br>    nx.draw(sub_graph, with_labels=True, font_weight=&#39;normal&#39;, font_size=8, \<br>        alpha=1, node_color = colors, \<br>        pos=nx.spring_layout(G))<br>    plt.title(f&#39;Relationship Between {selected_hero} and the Neighbors&#39;)<br><br>    hero_patch = mpatches.Patch(color=color_list[8], label=&#39;SELF&#39;)<br>    bad_patch = mpatches.Patch(color=color_list[5], label=&#39;BAD_AGAINST&#39;)<br>    good_patch = mpatches.Patch(color=color_list[1], label=&#39;GOOD_AGAINST&#39;)<br>    well_patch = mpatches.Patch(color=color_list[3], label=&#39;WORK_WELL_WITH&#39;)<br>    plt.legend(handles=[hero_patch, bad_patch, good_patch, well_patch])<br>    plt.show()<br><br>def draw_sub_graph_similar(G, sub_graph, selected_hero, similar_type=&#39;BIO_SIMILAR&#39;):<br>    # sub_graph = G.subgraph(sub_graph)<br>    <br>    colors = []<br>    for e in sub_graph:<br>        if e == selected_hero: # itself<br>            colors.append(color_list[8])<br>        elif G[selected_hero][e][&#39;label&#39;] == &#39;BIO_SIMILARITY&#39;:<br>            colors.append(color_list[1])<br>        elif G[selected_hero][e][&#39;label&#39;] == &#39;PRO_SIMILARITY&#39;:<br>            colors.append(color_list[3])<br>        elif G[selected_hero][e][&#39;label&#39;] == &#39;CON_SIMILARITY&#39;:<br>            colors.append(color_list[5])<br>       <br>    # print(colors)<br>    sub_graph = G.subgraph(sub_graph)<br>    print(sub_graph)<br>    plt.figure(figsize=(10,6))<br>    nx.draw(sub_graph, with_labels=True, font_weight=&#39;normal&#39;, font_size=8, \<br>        alpha=1, node_color = colors, \<br>        pos=nx.spring_layout(G))<br>    plt.title(f&#39;Similarity Between {selected_hero} and the Neighbors&#39;)<br><br>    hero_patch = mpatches.Patch(color=color_list[8], label=&#39;SELF&#39;)<br>    bio_patch = mpatches.Patch(color=color_list[1], label=&#39;BIO_SIMILAR&#39;)<br>    pro_patch = mpatches.Patch(color=color_list[3], label=&#39;PRO_SIMILAR&#39;)<br>    con_patch = mpatches.Patch(color=color_list[5], label=&#39;CON_SIMILAR&#39;)<br>    plt.legend(handles=[hero_patch, bio_patch, pro_patch, con_patch])<br>    plt.show()</pre><p>Crystal Maiden is one of my favorite heroes. Let’s see the result:</p><pre>selected_hero = &#39;Crystal Maiden&#39;<br># you can choose the number of nodes to show<br>sub_graph = get_all_adj_nodes(G_rl, selected_hero, num_nodes = 10)<br><br>draw_sub_graph_counter(G_rl, sub_graph, selected_hero)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*NymHmUZgCl3wN_PCENu8eQ.png" /><figcaption>Undirected Graph for Relationship</figcaption></figure><p>Here I find a problem: Crystal Maiden is an intelligence hero and has a lot of magical spells. But Nyx Assassin has anti-magic spells. Therefore, CM will definitely not be good against Nyx. Let’s see what’s happening.</p><pre>ast.literal_eval(heroes_df[heroes_df[&#39;official_name&#39;]==&#39;Nyx Assassin&#39;].good_against.tolist()[0])<br># [&#39;Crystal Maiden&#39;, &#39;Dawnbreaker&#39;, &#39;Enchantress&#39;, &#39;Enigma&#39;, &#39;Ember Spirit&#39;, &#39;Medusa&#39;, &#39;Outworld Destroyer&#39;, &#39;Phoenix&#39;, &#39;Puck&#39;, &#39;Pugna&#39;, &#39;Silencer&#39;, &#39;Sniper&#39;, &#39;Storm Spirit&#39;, &#39;Tinker&#39;]</pre><p>It turns out that Nyx is good against CM. Probably when we build the graph, the edges will overwrite each other. And when we add nodes and edges for Nyx, the previous data for CM is overwritten. So it is recommended to build graphs one by one based on the selected heroes instead of all together! Or we can build a directed graph instead.</p><pre>G_rl_directed = nx.DiGraph(label=&#39;HEROES_RELATIONSHIP&#39;)<br>start_time = time.time()<br><br>for i, rowi in heroes_df.iterrows():<br>    if (i%100==0):<br>        print(&quot; iter {} -- {} seconds -- &quot;.format(i, time.time()-start_time))<br>        <br>    G_rl_directed.add_node(rowi[&#39;official_name&#39;], key=rowi[&#39;hero_id&#39;], label=&#39;HERO&#39;, \<br>        h_attr=rowi[&#39;attribute&#39;])<br>    # G_rl_directed.add_edges_from([(rowi[&#39;official_name&#39;], rowi[&#39;official_name&#39;])], label=&#39;SAME_HERO&#39;)<br>    <br>    for element in ast.literal_eval(rowi.bad_against):<br>        # G_rl_directed.add_node(element, label=&#39;HERO&#39;)<br>        G_rl_directed.add_edges_from([(rowi[&#39;official_name&#39;], element)], label=&#39;BAD_AGAINST&#39;)<br>    <br>    for element in ast.literal_eval(rowi.good_against):<br>        # G_rl_directed.add_node(element, label=&#39;HERO&#39;)<br>        G_rl_directed.add_edges_from([(rowi[&#39;official_name&#39;], element)], label=&#39;GOOD_AGAINST&#39;)<br>        <br>    for element in ast.literal_eval(rowi.work_well_with):<br>        # G_rl_directed.add_node(element, label=&#39;HERO&#39;)<br>        G_rl_directed.add_edges_from([(rowi[&#39;official_name&#39;], element)], label=&#39;WORK_WELL_WITH&#39;)<br>        <br>print(&quot; finish -- {} seconds --&quot;.format(time.time() - start_time))    <br><br>selected_hero = &#39;Crystal Maiden&#39;<br># you can choose the number of nodes to show<br>sub_graph = get_all_adj_nodes(G_rl_directed, selected_hero, num_nodes = 24)<br><br>colors = []<br>color_map = []<br>for e in sub_graph: <br>    if e == selected_hero:<br>        # colors.append(color_list[8]) # itself<br>        color_map.append((e,e,color_list[9]))<br>    elif G_rl_directed[selected_hero][e][&#39;label&#39;] == &#39;BAD_AGAINST&#39;:<br>        # colors.append(color_list[5])<br>        color_map.append((selected_hero,e,color_list[5]))<br>    elif G_rl_directed[selected_hero][e][&#39;label&#39;] == &#39;GOOD_AGAINST&#39;:<br>        # colors.append(color_list[1])<br>        color_map.append((selected_hero,e,color_list[1]))<br>    elif G_rl_directed[selected_hero][e][&#39;label&#39;] == &#39;WORK_WELL_WITH&#39;:<br>        # colors.append(color_list[3])<br>        color_map.append((selected_hero,e,color_list[3]))<br><br># sub_graph = G_rl_directed.subgraph(sub_graph)<br># print(color_map)<br><br># rebuild the subgraph<br>sub_G = nx.DiGraph()<br>for edge in color_map:<br>    sub_G.add_edges_from([(edge[0], edge[1], {&quot;color&quot;: edge[-1]})])<br>colors = nx.get_edge_attributes(sub_G,&#39;color&#39;).values()<br>plt.figure(figsize=(10,6))<br>nx.draw(sub_G, with_labels=True, font_weight=&#39;normal&#39;, font_size=8, \<br>    alpha=1,  edge_color=colors, node_color=color_list[0],\<br>    pos=nx.spring_layout(G_rl_directed))<br>plt.title(f&#39;Relationship Between {selected_hero} and the Neighbors&#39;)<br><br>hero_patch = mpatches.Patch(color=color_list[9], label=&#39;SELF&#39;)<br>bad_patch = mpatches.Patch(color=color_list[5], label=&#39;BAD_AGAINST&#39;)<br>good_patch = mpatches.Patch(color=color_list[1], label=&#39;GOOD_AGAINST&#39;)<br>well_patch = mpatches.Patch(color=color_list[3], label=&#39;WORK_WELL_WITH&#39;)<br>plt.legend(handles=[hero_patch, bad_patch, good_patch, well_patch])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*CCBNSvPhshnIuGfvihDzfA.png" /><figcaption>Updated Relationship on the Directed Graph</figcaption></figure><pre>ast.literal_eval(heroes_df[heroes_df[&#39;official_name&#39;]==selected_hero].work_well_with.tolist()[0])<br># [&#39;Juggernaut&#39;, &#39;Timbersaw&#39;, &#39;Sven&#39;]</pre><p>Now the edge colors are correct according to the raw dataset.</p><p>Since the similarity matrix is symmetric, I won’t build a directed graph.</p><pre>selected_hero = &#39;Crystal Maiden&#39;<br># you can choose the number of nodes to show<br>sub_graph = get_all_adj_nodes(G_sim, selected_hero,num_nodes = 8)<br>draw_sub_graph_similar(G_sim, sub_graph, selected_hero)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*YMhjD5x2mc0--dsD6TSZGQ.png" /><figcaption>Similarity Graph</figcaption></figure><pre># we can check the result<br>heroes_df[heroes_df[&#39;official_name&#39;]==selected_hero].cons.to_list()[0].split(&#39;\n&#39;)<br># [&#39;Very fragile.&#39;,<br># &#39;Horrendous base stats (low movement speed, low damage, low attributes).&#39;,<br># &#39;Ultimate requires channeling and requires her to be in close range with her enemies.&#39;]<br><br>heroes_df[heroes_df[&#39;official_name&#39;]==&#39;Bane&#39;].cons.to_list()[0].split(&#39;\n&#39;)<br># [&#39;No area capabilities, poor against early pushing line ups and illusion heroes.&#39;,<br># &#39;Low mobility.&#39;,<br># &quot;Fiend&#39;s Grip requires channeling.&quot;,<br># &#39;Low attack range.&#39;,<br># &#39;Mediocre intelligence gain for a hero with low-cooldown high-mana-cost spells.&#39;]</pre><p>Based on the speed and the attack range, yes CM and Bane seem to have similar cons.</p><p>The graph visualization gives us a good understanding of the relationships between heroes and also a good sense that we may use the graph embedding to predict the winning rate later.</p><p>This is the EDA part for the heroes in DOTA2. Hope you like these analyses. Please let me know if there’s any problem :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/1*oLvL88ogmUqB08wXvKlGcQ.jpeg" /><figcaption>jia you a</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15cd705d2c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science for DOTA2(PART 1 — Data Collection)]]></title>
            <link>https://medium.com/@xiaoyigu/data-science-for-dota2-part-1-data-collection-55d7d7cb07c1?source=rss-57eb0aee8b95------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d7d7cb07c1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dota-2]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scrapy]]></category>
            <dc:creator><![CDATA[Alleria]]></dc:creator>
            <pubDate>Thu, 11 May 2023 04:10:08 GMT</pubDate>
            <atom:updated>2023-05-18T18:26:24.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Science for DOTA2(PART 1 — Data Collection)</h3><p><strong>Keywords: </strong>Opendota API call, Python Requests, BeautifulSoup, Scrapy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NfPGxW5RykSnsIbn2XzJUA.jpeg" /><figcaption>Wings Got the TI6 Championship in Seattle KeyArena</figcaption></figure><p>It has been almost 2 years since TI10, 5 years since TI8 and 7 years since TI6 in which Wings got the last championship for China. Last year, when Ame decided to take a break and Somnus(Maybe) announced retirement, I thought my great memory with LGD would fade away. However, now Somnus returns, together with those amazing summer legends. I feel so encouraged. Before the end of my summer break, I’ll try to apply what I have learned to a small project — Data Science for DOTA2.</p><p>The first part will be data collection, including using Opendota API to get matches and player information; using <a href="https://requests.readthedocs.io/en/latest/"><em>requests</em></a> to get a simple page and parsing with <a href="https://beautiful-soup-4.readthedocs.io/en/latest/"><em>BeautifulSoup</em></a>; using <a href="https://scrapy.org/"><em>scrapy</em></a> to download detailed information for heroes. Later, for part 2, I plan to complete the<em> analysis of the data</em> and build a <em>prediction model</em> for the draft. For part 3, I will try to build a recommendation system, so that the players can have a better understanding of the heroes, and hopefully, the system can help new players.</p><ol><li>Opendota API</li></ol><p><a href="https://www.opendota.com/">Opendota</a> offers dota related data. You can log in with your Steam account and explore the matches. Here is the description of the free tier and the premium one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_E4Z86Q9OMDtDHWqvRxWA.jpeg" /><figcaption>Description</figcaption></figure><p>I think it is as cheap as DOTA2 :) Here I have an example to show how to use requests to get data from the API:</p><pre># get all the heroes information<br>import requests<br>import pandas as pd<br>pd.set_option(&#39;display.max_columns&#39;, None)<br>opendota_api_heros_url = &#39;https://api.opendota.com/api/heroes&#39;<br><br>data = requests.get(opendota_api_heros_url, timeout=3)<br>data_json = data.json()<br><br>en_hero_df = pd.DataFrame(data_json)<br>en_hero_df[&#39;en_name&#39;] = en_hero_df[&#39;name&#39;].apply(lambda x:x.replace(&#39;npc_dota_hero_&#39;, &#39;&#39;))<br>en_hero_df = en_hero_df.rename(columns = {&#39;localized_name&#39;: &#39;official_name&#39;, &#39;id&#39;: &#39;hero_id&#39;,\<br>                                          &#39;name&#39;: &#39;ingame_name&#39;})<br>en_hero_df.to_csv(&#39;dota2_heroes.csv&#39;, index=False, header=True)<br>en_hero_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSB-EamfznmhaAS1ky9zEA.jpeg" /><figcaption>Result</figcaption></figure><pre># get the win and lose info of an account. <br># this is Ame&#39;s account I think<br>def get_api_json(url, loop=True, proxy=None):<br>    try:<br>        return requests.get(url, headers={&#39;User-Agent&#39;: &#39;Chrome&#39;}, timeout=3, proxies=proxy).json()<br>    except requests.exceptions.RequestException as e:<br>        print(e)<br>        return get_api_json(url, loop, proxy) if loop is True else None<br>get_api_json(&quot;http://api.opendota.com/api/players/148351321/wl&quot;, loop=True)<br># result: {&#39;win&#39;: 769, &#39;lose&#39;: 842}</pre><p>Next, we can make an API call to get the information of a match.</p><pre># this is a match between PSG.LGD and Team Spirit<br>match_json = get_api_json(&quot;https://api.opendota.com/api/matches/6227419633&quot;, loop=True)<br>match_json[&#39;players&#39;][0][&#39;name&#39;]<br># result: 萧瑟</pre><p>I build a dictionary to map the hero ids to the official name:</p><pre>hero_id_to_name = dict(zip(en_hero_df[&#39;hero_id&#39;].values, en_hero_df[&#39;official_name&#39;].values))</pre><p>To get huge amounts of data, we can use the <a href="https://www.opendota.com/explorer"><em>explorer</em></a> of the website. You can use the basic version to select the attributes in the UI or you can switch to SQL command(based on<strong> </strong>PostgreSQL, check <a href="https://github.com/odota/core/blob/master/sql/create_tables.sql">this</a>). I first get all the match ids and their start time, then I download the detailed information.</p><pre># SELECT<br>        <br># matches.match_id,<br># matches.start_time<br><br># FROM matches<br># JOIN match_patch using(match_id)<br><br># WHERE matches.start_time &gt;= extract(epoch from timestamp &#39;2021-01-01T07:00:00.000Z&#39;)<br># AND matches.start_time &lt;= extract(epoch from timestamp &#39;2023-05-09T07:00:00.000Z&#39;)<br># ORDER BY matches.start_time DESC<br># LIMIT 100000<br><br>match_id_api = &#39;https://api.opendota.com/api/explorer?sql=SELECT%0A%20%20%20%20%20%20%20%20%0Amatches.match_id%2C%0Amatches.start_time%0A%0AFROM%20matches%0AJOIN%20match_patch%20using(match_id)%0A%0AWHERE%20matches.start_time%20%3E%3D%20extract(epoch%20from%20timestamp%20%272021-01-01T07%3A00%3A00.000Z%27)%0AAND%20matches.start_time%20%3C%3D%20extract(epoch%20from%20timestamp%20%272023-05-09T07%3A00%3A00.000Z%27)%0AORDER%20BY%20matches.start_time%20DESC%0ALIMIT%20100000&#39;<br>match_data = requests.get(match_id_api).json()<br>match_ids = [row[&#39;match_id&#39;] for row in match_data[&#39;rows&#39;]]<br>print(f&quot;Altogether we have {len(match_ids)} matches.&quot;)<br># Altogether we have xxx matches.</pre><p>I manually make a list including the game performance features I’m interested in:</p><pre>attributes_list= [&#39;region&#39;,<br> &#39;isRadiant&#39;,<br> &#39;win&#39;,<br> &#39;lose&#39;,<br> &#39;total_gold&#39;,<br> &#39;total_xp&#39;,<br> &#39;kills_per_min&#39;,<br> &#39;kda&#39;,<br> &#39;abandons&#39;,<br> &#39;neutral_kills&#39;,<br> &#39;tower_kills&#39;,<br> &#39;courier_kills&#39;,<br> &#39;lane_kills&#39;,<br> &#39;hero_kills&#39;,<br> &#39;observer_kills&#39;,<br> &#39;sentry_kills&#39;,<br> &#39;roshan_kills&#39;,<br> &#39;necronomicon_kills&#39;,<br> &#39;ancient_kills&#39;,<br> &#39;buyback_count&#39;,<br> &#39;observer_uses&#39;,<br> &#39;sentry_uses&#39;]</pre><p>Next, I write a loop to get all the information I need for future work. Here if you want to use the premium tier, you should input your credit card information on Opendota and please add “?api_key=YOUR_API” after each URL.</p><pre>from datetime import datetime<br>import time<br># https://www.opendota.com/api-keys<br>def get_hero_position_and_role(row_dict_list, player_dict_list, match_id, matches_list):<br>    # Please add ?api_key=YOUR_API after {match_id} to accelerate the api call<br>    # Refer the opendota website https://www.opendota.com/api-keys<br>    match_json = get_api_json(f&quot;https://api.opendota.com/api/matches/{match_id}&quot;, loop=True)<br>    matches_list.append(match_json)<br>    <br>    # match_id = match_json[&#39;match_id&#39;]<br>    # I have tested the following attributes and generally there will be no error<br>    row_dicts = []<br>    win_camp = None<br>    start_time, duration, game_mode = None, None, None<br>    radiant_score, dire_score = None, None<br>    try:<br>        if match_json[&quot;radiant_win&quot;]==True:<br>            win_camp = &#39;radiant&#39;<br>        else: <br>            win_camp = &#39;dire&#39;<br>        if match_json[&#39;game_mode&#39;]:  # mode 1: all pick, mode 2: captain mode<br>            game_mode = match_json[&#39;game_mode&#39;]<br>        else:<br>            game_mode = None<br>        start_time = match_json[&quot;start_time&quot;]<br>        start_time = datetime.fromtimestamp(start_time).strftime(&#39;%y-%m-%d&#39;)<br>        duration = match_json[&quot;duration&quot;]<br>        radiant_score = match_json[&#39;radiant_score&#39;] <br>        dire_score = match_json[&#39;dire_score&#39;] <br>    except:<br>        print(f&#39;unknown result id: {match_id}&#39;)<br><br>    if &#39;players&#39; in match_json.keys():<br>        for p in match_json[&#39;players&#39;]:<br>            row_dict = {}<br>            row_dict[&#39;match_id&#39;] = match_id<br>            row_dict[&#39;camp&#39;] = &#39;radiant&#39; if p[&#39;isRadiant&#39;] else &#39;dire&#39;<br>            row_dict[&#39;hero_id&#39;] = p[&#39;hero_id&#39;]<br>            row_dict[&#39;hero_name&#39;] = hero_id_to_name[p[&#39;hero_id&#39;]]<br>            if &#39;name&#39; in p:<br>                row_dict[&#39;player&#39;] = p[&#39;name&#39;]<br>            else:<br>                row_dict[&#39;player&#39;] = None<br>            row_dict[&#39;player_id&#39;] = p[&#39;account_id&#39;]<br>            if &#39;lane_role&#39; in p:<br>                row_dict[&quot;lane_role&quot;] = {1: &quot;safe&quot;, 2: &quot;mid&quot;, 3: &quot;off&quot;, 4:&#39;other&#39;}[p[&quot;lane_role&quot;]]<br>            else:<br>                row_dict[&quot;lane_role&quot;] = None<br>            if p[&quot;lh_t&quot;] and len(p[&quot;lh_t&quot;])&gt;=6:<br>                # print(p[&quot;lh_t&quot;])<br>                row_dict[&quot;6_min_last_hits&quot;] = p[&quot;lh_t&quot;][6]<br>            else:<br>                row_dict[&quot;6_min_last_hits&quot;] = None<br>            purchase_ward_observer = p[&quot;purchase_ward_observer&quot;] if &quot;purchase_ward_observer&quot; in p else 0<br>            purchase_ward_sentry = p[&quot;purchase_ward_sentry&quot;] if &quot;purchase_ward_sentry&quot; in p else 0<br>            row_dict[&quot;purchase_ward_count&quot;] = purchase_ward_observer + purchase_ward_sentry<br>            row_dict[&#39;gold_per_min&#39;] = p[&#39;gold_per_min&#39;]<br>            row_dict[&#39;hero_damage&#39;] = p[&#39;hero_damage&#39;]<br>            row_dict[&#39;tower_damage&#39;] = p[&#39;tower_damage&#39;]<br>            if &#39;rank_tier&#39; in p:<br>                row_dict[&#39;rank_tier&#39;] = p[&#39;rank_tier&#39;]<br>            for a in attributes_list:<br>                if a in p:<br>                    row_dict[a] = p[a]<br>                else:<br>                    row_dict[a] = None<br><br>            row_dicts.append(row_dict)<br>            player_dict_list.append(row_dict)<br><br>        w_df = pd.DataFrame(row_dicts)<br>        sorted_core_df = w_df.sort_values(&quot;6_min_last_hits&quot;, ascending=False).head(6)  # find the 6 heros with max last hits in 6 mins --&gt; cores<br>        # sorted_ward_df = w_df.sort_values(&#39;purchase_ward_count&#39;, ascending=False).head(4)  # find 4 heros with max wards purchase --&gt; support TAT<br>        def get_role(r):<br>            # define the cores first(cores have higher hits), define support then<br>            if r.lane_role==&#39;safe&#39;:<br>                if r.hero_id in sorted_core_df.hero_id.tolist():<br>                    return &#39;carry&#39;<br>                else:<br>                    return &#39;hard_support&#39;<br>            elif r.lane_role==&#39;off&#39;:<br>                if r.hero_id in sorted_core_df.hero_id.tolist():<br>                    return &#39;offlane&#39;<br>                else:<br>                    return &#39;soft_support&#39;<br>            elif r.lane_role==&#39;mid&#39;:<br>                if r.hero_id in sorted_core_df.hero_id.tolist():<br>                    return &#39;mid&#39;<br>                else:<br>                    return &#39;Unknown&#39;<br>            <br>            # elif r.lane_role==&#39;safe&#39; and r.hero_id in sorted_ward_df.hero_id.tolist():<br>            #     return &#39;soft_support&#39;<br>            # elif r.hero_id in sorted_ward_df.hero_id.tolist():<br>            #     return &#39;hard_support&#39;<br>        # print(sorted_ward_df)<br>        w_df[&#39;role&#39;] = w_df.apply(lambda r:get_role(r), axis=1)<br><br>        radiant_df = w_df[w_df[&#39;camp&#39;]==&#39;radiant&#39;]<br>        dire_df = w_df[w_df[&#39;camp&#39;]==&#39;dire&#39;]<br><br>        hero_positions_radiant = {radiant_df.hero_name.tolist()[i]:[radiant_df.role.tolist()[i], radiant_df.player_id.tolist()[i]] for i in range(len(radiant_df))}<br>        hero_positions_dire = {dire_df.hero_name.tolist()[i]:[dire_df.role.tolist()[i], dire_df.player_id.tolist()[i]] for i in range(len(dire_df))}<br>        <br>        res_dicts = {}<br>        res_dicts[&#39;match_id&#39;] = match_id<br>        res_dicts[&#39;start_time&#39;] = start_time<br>        res_dicts[&#39;duration&#39;] = duration<br>        res_dicts[&#39;game_mode&#39;] = game_mode<br>        res_dicts[&#39;win_camp&#39;] = win_camp<br>        res_dicts[&#39;radiant_hero&#39;] = hero_positions_radiant<br>        res_dicts[&#39;dire_hero&#39;] = hero_positions_dire<br>        res_dicts[&#39;radiant_score&#39;] = radiant_score<br>        res_dicts[&#39;dire_score&#39;] = dire_score<br><br>        row_dict_list.append(res_dicts)<br>    else:<br>        print(f&quot;Problem id: {match_id}&quot;)<br>    print(f&quot;current length: {len(row_dict_list)}&quot;)<br>    # print(f&quot;current length: {count}&quot;)<br>    return row_dict_list, player_dict_list, matches_list<br><br>team_dict_list = []<br>player_dict_list = []<br>count = 1<br>matches_list = []<br>for match_id in match_ids[:3]:<br>    # count += 1<br>    if count % 1200 == 0:<br>        time.sleep(65) # free tier 60 calls per minute<br>    count += 1<br>    team_dict_list, player_dict_list, matches_list = get_hero_position_and_role(team_dict_list, player_dict_list, match_id, matches_list)<br><br># team_dict_list[0]<br># {&#39;match_id&#39;: 7146139538,<br>#  &#39;start_time&#39;: &#39;23-05-08&#39;,<br>#  &#39;duration&#39;: 1409,<br>#  &#39;game_mode&#39;: 2,<br>#  &#39;win_camp&#39;: &#39;dire&#39;,<br>#  &#39;radiant_hero&#39;: {&#39;Death Prophet&#39;: [&#39;mid&#39;, 1459205302],<br>#   &#39;Jakiro&#39;: [&#39;hard_support&#39;, 1459031599],<br>#   &#39;Underlord&#39;: [&#39;offlane&#39;, 1423366323],<br>#   &#39;Gyrocopter&#39;: [&#39;soft_support&#39;, 1458610209],<br>#   &#39;Naga Siren&#39;: [&#39;carry&#39;, 1459124273]},<br>#  &#39;dire_hero&#39;: {&#39;Queen of Pain&#39;: [&#39;mid&#39;, 1526386891],<br>#   &#39;Disruptor&#39;: [&#39;hard_support&#39;, 1513040880],<br>#   &#39;Templar Assassin&#39;: [&#39;carry&#39;, 1427100407],<br>#   &#39;Pudge&#39;: [&#39;soft_support&#39;, 1517400698],<br>#   &#39;Mars&#39;: [&#39;offlane&#39;, 1529282248]},<br>#  &#39;radiant_score&#39;: 14,<br>#  &#39;dire_score&#39;: 34}</pre><p>Now you can save the data into your local server.</p><pre>import json <br><br># Combine dictionaries into a list <br>dict_list = matches_list<br>len(dict_list)<br> <br># Write list of dictionaries to JSON file (optional)<br>with open(&#39;data.json&#39;, &#39;w&#39;) as f: <br>    json.dump(dict_list, f) <br><br>team_df = pd.DataFrame(team_dict_list)<br>team_df.to_csv(&#39;team.csv&#39;, index=False, header=True)<br><br>player_df = pd.DataFrame(player_dict_list)<br># player_df.head(10)<br>player_df.to_csv(&#39;player.csv&#39;, index=False, header=True)</pre><p>I can share the data I have downloaded, if you would like to get the data, please email <a href="http://xiaoyigu@usc.edu/">me</a> as the dataset is very huge. Later I will try to upload them to a drive link and it will be shown once it is done.</p><p>2. DOTA2 wiki</p><p>I would like to say that <a href="https://dota2.fandom.com/wiki/">DOTA2 wiki</a> is a great source and I’m grateful to all the developers. Now I will show you how to download hero attributes using requests and BeautifulSoup. I checked <a href="https://dota2.fandom.com/robots.txt">https://dota2.fandom.com/robots.txt</a> and I didn’t find that getting hero information would be banned. But if it is not allowed, please let me know and I will delete it immediately.</p><p>Here I basically get the hero attributes from the base URL.</p><pre>import requests<br>from bs4 import BeautifulSoup<br># reference: https://www.crummy.com/software/BeautifulSoup/bs4/doc/<br><br>urls = [&#39;https://dota2.fandom.com/wiki/Table_of_hero_attributes&#39;]<br>r = requests.get(urls[0])<br>html_doc = r.content<br>soup = BeautifulSoup(html_doc, &#39;html.parser&#39;)<br><br>attr_list = []<br><br>def get_attributes(url, attr_list):<br>    r = requests.get(url)<br>    html_doc = r.content<br>    soup = BeautifulSoup(html_doc, &#39;html.parser&#39;)<br><br>    # print(soup.prettify())<br>    for tr in soup.tbody.find_all(&#39;tr&#39;)[1:]:<br>        hero_name = tr.a.get(&#39;href&#39;).split(&#39;/&#39;)[-1] # set the hero_name as in the url for future merge with other data<br>        tds = tr.find_all(&#39;td&#39;)<br>        attr_dict = {}<br>        attr_dict[&#39;hero&#39;] = hero_name<br>        attr_dict[&#39;base_strength&#39;] = float(tds[2].string)<br>        attr_dict[&#39;add_strength&#39;] = float(tds[3].string)<br>        attr_dict[&#39;lvl30_strength&#39;] = float(tds[4].string)<br>        attr_dict[&#39;base_agility&#39;] = float(tds[5].string)<br>        attr_dict[&#39;add_agility&#39;] = float(tds[6].string)<br>        attr_dict[&#39;lvl30_agility&#39;] = float(tds[7].string)<br>        attr_dict[&#39;base_intelligence&#39;] = float(tds[8].string)<br>        attr_dict[&#39;add_intelligence&#39;] = float(tds[9].string)<br>        attr_dict[&#39;lvl30_intelligence&#39;] = float(tds[10].string)<br>        attr_list.append(attr_dict)<br><br>for url in urls:<br>    get_attributes(url, attr_list)<br><br>print(f&quot;Altogether we have {len(attr_list)} heroes.&quot;)<br># Altogether we have 124 heroes.<br><br>attr_list[2]<br># {&#39;hero&#39;: &#39;Ancient_Apparition&#39;,<br>#  &#39;base_strength&#39;: 20.0,<br>#  &#39;add_strength&#39;: 1.9,<br>#  &#39;lvl30_strength&#39;: 75.1,<br>#  &#39;base_agility&#39;: 20.0,<br>#  &#39;add_agility&#39;: 2.2,<br>#  &#39;lvl30_agility&#39;: 83.8,<br>#  &#39;base_intelligence&#39;: 23.0,<br>#  &#39;add_intelligence&#39;: 3.4,<br>#  &#39;lvl30_intelligence&#39;: 121.6}</pre><p>Save the data:</p><pre>attribute_df = pd.DataFrame(attr_list)<br>attribute_df.to_csv(&#39;hero_attributes.csv&#39;, index=False, header=True)<br>attribute_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pINnSEzplazY703lHzpiaw.png" /><figcaption>Hero_attributes Result</figcaption></figure><p>Next, let’s use Scrapy to crawl hero details(URLs, bios, counter relationships, and pros/cons).</p><p>To use scrapy, you need to install it(pip install scrapy). And if you follow the <a href="https://docs.scrapy.org/en/latest/intro/tutorial.html">tutorial</a>, you will be able to create a project quickly. There are 2 important commands.</p><p>a. scrapy shell ‘<a href="https://dota2.fandom.com/wiki/Heroes&#39;">https://dota2.fandom.com/wiki/Heroes&#39;</a></p><p>Run this in your terminal. You will get into the scrapy shell and you can freely test the <a href="https://www.w3schools.com/cssref/css_selectors.php">CSS</a>/xpath selectors.</p><p>b. scrapy crawl Heroes -O heroes_url.json</p><p>Run this cmd to crawl data and you will get a heroes_url.json file with the data you crawled. Remember, “Heroes” here is the “name” in your spider class.</p><p>I’ll show the scripts. They should be inside the spiders/ folder. And they are simple ones.</p><pre># get heros, links and attributes<br>import scrapy<br><br>class HeroesSpider(scrapy.Spider):<br>    name = &quot;Heroes&quot; # Attention to the name here<br><br>    def start_requests(self):<br>        urls = [<br>            &quot;https://dota2.fandom.com/wiki/Heroes&quot;,<br>        ]<br>        for url in urls:<br>            yield scrapy.Request(url=url, callback=self.parse)<br><br>        <br>    def parse(self, response):<br>        count = 0<br>        <br>        for heroes in response.css(&#39;table&gt;tbody&gt;tr&#39;):<br>            for hero in heroes.css(&#39;td&gt;div&gt;div:first-child&#39;):<br>                count += 1<br>                print(hero.css(&#39;div&gt;a::attr(title)&#39;).get())<br>                print(count)<br>                if count &lt;= 31:<br>                    attribute = &#39;Strength&#39;<br>                elif count&gt;31 and count &lt;= 62:<br>                    attribute = &#39;Agility&#39;<br>                elif count&gt;62 and count &lt;= 93:<br>                    attribute = &#39;Intelligence&#39;<br>                else:<br>                    attribute = &#39;Universal&#39;<br>                    <br>                yield {<br>                    &quot;hero&quot;: hero.css(&#39;div&gt;a::attr(href)&#39;).get().split(&#39;/&#39;)[-1],<br>                    &quot;link&quot;: &#39;https://dota2.fandom.com&#39; + hero.css(&#39;div&gt;a::attr(href)&#39;).get(),<br>                    &#39;attribute&#39;: attribute<br>                }</pre><p>You need to run the above script first so that you will get the URLs for the following steps.</p><pre># get the heroes and their bios<br>import scrapy<br>import json<br><br><br>class HeroBioSpider(scrapy.Spider):<br>    name = &quot;HeroBio&quot;<br><br>    # attributes = [hero[&#39;attribute&#39;] for hero in json.load(content)]<br>    # names = [hero[&#39;hero&#39;] for hero in json.load(content)]<br>    <br>    def start_requests(self):<br>        <br>        f = open(&#39;heroes_url.json&#39;)<br>        urls = [hero[&#39;link&#39;] for hero in json.load(f)]<br>        urls = urls<br>        for url in urls:<br>            yield scrapy.Request(url=url, callback=self.parse)<br>        <br>    def parse(self, response):<br>        <br>        hero = response.url.split(&#39;/&#39;)[-1]<br>        <br>        bios = &#39;&#39;<br>        for bio in response.css(&#39;div#heroBio&gt;*&#39;):<br>            bios += &#39;.\n&#39; .join(bio.css(&#39;::text&#39;).getall())<br>        <br>        yield {<br>            &quot;hero&quot;: hero,<br>            &quot;bio&quot;: bios<br>        }</pre><pre># get the heroes and their counter relationships<br><br>import scrapy<br>import json<br><br><br>class HeroCounterSpider(scrapy.Spider):<br>    name = &quot;HeroCounter&quot;<br><br>    # f = open(&#39;heroes_url.json&#39;)<br>    # urls = [hero[&#39;link&#39;] for hero in json.load(f)]<br>    # attributes = [hero[&#39;attribute&#39;] for hero in json.load(content)]<br>    # names = [hero[&#39;hero&#39;] for hero in json.load(content)]<br>    <br>    def start_requests(self):<br>        f = open(&#39;heroes_url.json&#39;)<br>        urls = [hero[&#39;link&#39;]+&#39;/Counters&#39; for hero in json.load(f)]<br>        urls = urls<br>        for url in urls:<br>            yield scrapy.Request(url=url, callback=self.parse)<br>        <br>    def parse(self, response):<br>        counters_list = []<br>        hero_name = response.url.split(&#39;/&#39;)[-2]<br>        <br>        count = 0<br>        for hero in response.css(&#39;div.mw-parser-output&gt;*&#39;):<br>            if hero.css(&#39;div&gt;b&gt;a&#39;):<br>                count += 1<br>            if hero.css(&#39;h2&gt;span&#39;):<br>                counters_list.append(count)<br>            elif hero.xpath(&#39;.//h2/span[@id=&quot;Good_against...&quot;]&#39;):<br>                counters_list.append(count)<br>            elif hero.xpath(&#39;.//h2/span[@id=&quot;Works well with...&quot;]&#39;):<br>                counters_list.append(count)<br>        heros_list = response.css(&#39;div.mw-parser-output&gt;div&gt;b&gt;a::text&#39;).getall()<br>        <br>        bad_against = heros_list[:counters_list[1]]<br>        good_against = heros_list[counters_list[1]:counters_list[2]]<br>        work_well_with = heros_list[counters_list[2]:]<br>        yield {<br>            &quot;hero&quot;: hero_name,<br>            &quot;bad_against&quot;: bad_against,<br>            &quot;good_against&quot;: good_against,<br>            &quot;work_well_with&quot;: work_well_with<br>        }</pre><pre># get the heroes and their pros and cons<br>import scrapy<br>import json<br><br><br>class HeroProConSpider(scrapy.Spider):<br>    name = &quot;HeroProCon&quot;<br><br>    # f = open(&#39;heroes_url.json&#39;)<br>    # urls = [hero[&#39;link&#39;] for hero in json.load(f)]<br>    # attributes = [hero[&#39;attribute&#39;] for hero in json.load(content)]<br>    # names = [hero[&#39;hero&#39;] for hero in json.load(content)]<br>    <br>    def start_requests(self):<br>        f = open(&#39;heroes_url.json&#39;)<br>        urls = [hero[&#39;link&#39;]+&#39;/Guide&#39; for hero in json.load(f)]<br>        urls = urls<br>        for url in urls:<br>            yield scrapy.Request(url=url, callback=self.parse)<br>        <br>    def parse(self, response):<br>        hero_name = response.url.split(&#39;/&#39;)[-2]<br>        <br>        pros_css = response.xpath(&#39;.//table[tbody/tr/th[contains(text(),&quot;Playstyle&quot;)]]//tr[@valign=&quot;top&quot;]/td[1]/ul/li&#39;)<br>        pros = &#39;\n&#39;.join([pro.css(&#39;::text&#39;).get() for pro in pros_css])<br>        <br>        cons_css = response.xpath(&#39;.//table[tbody/tr/th[contains(text(),&quot;Playstyle&quot;)]]//tr[@valign=&quot;top&quot;]/td[2]/ul/li&#39;)<br>        cons = &#39;\n&#39;.join([con.css(&#39;::text&#39;).get() for con in cons_css])<br>        <br>        yield {<br>            &quot;hero&quot;: hero_name,<br>            &quot;pros&quot;: pros,<br>            &quot;cons&quot;: cons<br>        }</pre><p>These tasks are very basic applications of scrapy, you can explore yourself. The <a href="https://github.com/Alleria1809/DOTA2.git">folder</a> stores crawled data.</p><p>And this is the end of PART 1. Next, if you want to merge all the data with some keys such as hero name, here is the code for your reference:</p><pre>import pandas as pd<br>import os<br><br>pd.set_option(&#39;display.max_columns&#39;, None)</pre><pre># my scrapy project is named &quot;heroes&quot;<br>hero_detail_path = &#39;./heroes/heroes/heroes&#39;<br><br>pro_con_path = os.path.join(hero_detail_path, &#39;hero_pro_con.json&#39;)<br>bio_path = os.path.join(hero_detail_path, &#39;heroes_bios.json&#39;)<br>counter_path = os.path.join(hero_detail_path, &#39;heroes_counter.json&#39;)<br>url_path = os.path.join(hero_detail_path, &#39;heroes_url.json&#39;)<br><br>basic_hero_df = pd.read_csv(&#39;dota2_heroes.csv&#39;)<br>attr_df = pd.read_csv(&#39;hero_attributes.csv&#39;)<br>hero_pro_con_df = pd.read_json(pro_con_path)<br>hero_bio_df = pd.read_json(bio_path)<br>hero_counter_df = pd.read_json(counter_path)<br>hero_url_df = pd.read_json(url_path)<br><br># replace nature&#39;s prophet(it has messy unicode)<br>hero_pro_con_df.replace(&#39;Nature%27s_Prophet&#39;, &quot;Nature&#39;s_Prophet&quot;, inplace=True)<br>attr_df.replace(&#39;Nature%27s_Prophet&#39;, &quot;Nature&#39;s_Prophet&quot;, inplace=True)<br>hero_bio_df.replace(&#39;Nature%27s_Prophet&#39;, &quot;Nature&#39;s_Prophet&quot;, inplace=True)<br>hero_counter_df.replace(&#39;Nature%27s_Prophet&#39;, &quot;Nature&#39;s_Prophet&quot;, inplace=True)<br>hero_url_df.replace(&#39;Nature%27s_Prophet&#39;, &quot;Nature&#39;s_Prophet&quot;, inplace=True)<br><br>basic_hero_df.drop(columns=[&#39;ingame_name&#39;,&#39;en_name&#39;], inplace=True)<br>basic_hero_df[&#39;name_id&#39;] = basic_hero_df[&#39;official_name&#39;].apply(lambda x:x.lower().replace(&#39;-&#39;,&#39;&#39;).replace(&#39;_&#39;,&#39;&#39;).replace(&#39; &#39;,&#39;&#39;))<br>attr_df[&#39;name_id&#39;] = attr_df[&#39;hero&#39;].apply(lambda x:x.lower().replace(&#39;-&#39;,&#39;&#39;).replace(&#39;_&#39;,&#39;&#39;).replace(&#39; &#39;,&#39;&#39;))<br>hero_pro_con_df[&#39;name_id&#39;] = hero_pro_con_df[&#39;hero&#39;].apply(lambda x:x.lower().replace(&#39;-&#39;,&#39;&#39;).replace(&#39;_&#39;,&#39;&#39;).replace(&#39; &#39;,&#39;&#39;))<br>hero_bio_df[&#39;name_id&#39;] = hero_bio_df[&#39;hero&#39;].apply(lambda x:x.lower().replace(&#39;-&#39;,&#39;&#39;).replace(&#39;_&#39;,&#39;&#39;).replace(&#39; &#39;,&#39;&#39;))<br>hero_counter_df[&#39;name_id&#39;] = hero_counter_df[&#39;hero&#39;].apply(lambda x:x.lower().replace(&#39;-&#39;,&#39;&#39;).replace(&#39;_&#39;,&#39;&#39;).replace(&#39; &#39;,&#39;&#39;))<br>hero_url_df[&#39;name_id&#39;] = hero_url_df[&#39;hero&#39;].apply(lambda x:x.lower().replace(&#39;-&#39;,&#39;&#39;).replace(&#39;_&#39;,&#39;&#39;).replace(&#39; &#39;,&#39;&#39;))<br><br>basic_hero_df = basic_hero_df.merge(hero_pro_con_df, on=&#39;name_id&#39;).drop(columns=[&#39;hero&#39;])<br>basic_hero_df = basic_hero_df.merge(attr_df, on=&#39;name_id&#39;).drop(columns=[&#39;hero&#39;])<br>basic_hero_df = basic_hero_df.merge(hero_bio_df, on=&#39;name_id&#39;).drop(columns=[&#39;hero&#39;])<br>basic_hero_df = basic_hero_df.merge(hero_counter_df, on=&#39;name_id&#39;).drop(columns=[&#39;hero&#39;])<br>basic_hero_df = basic_hero_df.merge(hero_url_df, on=&#39;name_id&#39;).drop(columns=[&#39;hero&#39;])<br><br>basic_hero_df.to_csv(&#39;all_heroes.csv&#39;, index=False, header=True)<br>basic_hero_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKrltvZr-yZrkXZnTTKr4g.png" /><figcaption>Sample Output</figcaption></figure><p>This is all for the data collection part. There are a lot of things not included such as the details of hero mechanisms. I will explain them later in PART 2. Thank you for your time! Hope you enjoy data science and DOTA2 :).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/1*oLvL88ogmUqB08wXvKlGcQ.jpeg" /><figcaption>It’s so cute to be here.</figcaption></figure><p>Please let me know if there are any questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jntDOf_Lt2lSxMaK0tOAA.jpeg" /><figcaption>jiayou</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d7d7cb07c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression]]></title>
            <link>https://medium.com/@xiaoyigu/logistic-regression-e94450e5d3f6?source=rss-57eb0aee8b95------2</link>
            <guid isPermaLink="false">https://medium.com/p/e94450e5d3f6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alleria]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 00:32:46 GMT</pubDate>
            <atom:updated>2023-03-09T00:58:05.498Z</atom:updated>
            <content:encoded><![CDATA[<p>I wrote this article for a better understanding of logistic regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ru5wIqZEoamOkRKLazkLJQ.jpeg" /><figcaption>Fig 1: Generated Word Cloud Based on the Article</figcaption></figure><p><strong>Definition</strong></p><ul><li>It is similar to the binary classification we are familiar with.</li><li>It predicts the <strong>categorical</strong> dependent variables, usually binary. The dependent variables can also be multinomial. <a href="https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression">Sklearn</a> describes multinomial logistic regression with details.</li></ul><p><strong>Assumptions</strong></p><ul><li>The Observations are Independent (check with residual plot)</li><li>There is <strong>No</strong> Multicollinearity Among Explanatory (check with Variables variance inflation factor VIF)</li><li>There are No Extreme Outliers</li><li>p(x) = exp(b0+b1*x)/(1+exp(b0+b1*x)). Logit = log(p/(1-p))=b0+b1*x</li></ul><p>Reference: <a href="https://www.statology.org/assumptions-of-logistic-regression/">https://www.statology.org/assumptions-of-logistic-regression/</a></p><p><strong>Two phases</strong></p><ul><li>Use the logistic function(sigmoid) g(z) = 1/(1+exp(-z)) to calculate the probability(0~1), z=b0+b1*x.</li><li>Predict the class of a test sample based on the threshold.</li></ul><p><strong>Maximum likelihood estimation</strong></p><blockquote>Why log likelihood?</blockquote><p>If we use MSE like Linear Regression, the loss function will not be convex and it’s difficult to find the global minimum(due to non-linearity introduced into the model in the form of a sigmoid function). So here we use log likelihood as the loss function because it will be convex.</p><p>Reference:</p><p><a href="https://medium.com/analytics-vidhya/understanding-the-loss-function-of-logistic-regression-ac1eec2838ce#:~:text=Why%20doesn&#39;t%20MSE%20work,to%20find%20the%20global%20minimum">https://medium.com/analytics-vidhya/understanding-the-loss-function-of-logistic-regression-ac1eec2838ce#:~:text=Why%20doesn&#39;t%20MSE%20work,to%20find%20the%20global%20minimum</a>.</p><blockquote>Use MLE to fit the model:</blockquote><ul><li>Betas, x, y → likelihood function</li><li>Estimate betas to maximize the likelihood</li><li>Can use gradient descent to update betas and use mini-batch to improve the efficiency. Mini-batch may bring bad gradients if the data is noisy but we can still optimize them</li></ul><p><strong>Why logistic instead of linear regression?</strong></p><ol><li>Logistic regression can predict categorical Ys.</li><li>Linear regression:</li></ol><ul><li>Hard to fit the data, especially with outliers.</li><li>Linear regression predictions have the meaning of order and imply that the differences between different categories are the same. But in fact, the difference should not be the same.</li><li>Linear regression can generate probability&gt;1 or &lt;0.</li></ul><p><strong>Other Notes:</strong></p><ul><li>Logistic regression is also linear because it has a linear decision boundary.</li></ul><p><em>p(x) = exp(b0+b1*x)/(1+exp(b0+b1*x)). Logit = log(p/(1-p))=b0+b1*x</em></p><p><em>if we have p(x)=exp(1+x), and threshold=0.5, then exp(1+x)=0.5. The boundary is linear.</em></p><ul><li>For linear separable data, logistic regression may generate probability very close to 1/0, and it won’t stop unless you set the iterations when using Sklearn packages.</li></ul><p>Real Interview Questions:</p><ol><li>Is Logistic Regression Linear?</li><li>What are the assumptions of Logistic Regression?</li><li>Will multicollinearity be a problem if you use Logistic Regression?</li></ol><p><em>Please let me know if there are any questions or problems! 😆:)</em></p><p>Implement Logistic Regression from Scratch:</p><p><em>I have implemented 2 versions with/without Numpy :)</em></p><p><a href="https://github.com/Alleria1809/LogisticRegressionImplementation">GitHub - Alleria1809/LogisticRegressionImplementation: Implement Logistic Regression</a></p><p>References:</p><ol><li>Machine Learning for Data Science(DSCI552 at USC), M. R. Rajati, PhD</li><li><a href="https://www.youtube.com/watch?v=YYEJ_GUguHw&amp;t=3s">AssemblyAI</a> and <a href="https://www.youtube.com/watch?v=gN79XvB7vTo&amp;t=598s">Emma Ding</a> are useful resources!</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYYEJ_GUguHw%3Fstart%3D3%26feature%3Doembed%26start%3D3&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYYEJ_GUguHw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYYEJ_GUguHw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/86ff2cc6cf68e9ae42974ebd89c2bfc6/href">https://medium.com/media/86ff2cc6cf68e9ae42974ebd89c2bfc6/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgN79XvB7vTo%3Fstart%3D598%26feature%3Doembed%26start%3D598&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgN79XvB7vTo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgN79XvB7vTo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf3d6b492f8ef56e86ee514ad3ec8b86/href">https://medium.com/media/cf3d6b492f8ef56e86ee514ad3ec8b86/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e94450e5d3f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>