<?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 Patiparn Nualchan on Medium]]></title>
        <description><![CDATA[Stories by Patiparn Nualchan on Medium]]></description>
        <link>https://medium.com/@mpatiparn-n?source=rss-197add41248f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gosrwy2WLhB9fUmk3ZIMFg.jpeg</url>
            <title>Stories by Patiparn Nualchan on Medium</title>
            <link>https://medium.com/@mpatiparn-n?source=rss-197add41248f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:15:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mpatiparn-n/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[Store Clustering on 3 years sale data]]></title>
            <link>https://mpatiparn-n.medium.com/store-clustering-on-3-years-sale-data-81e6eafa72cb?source=rss-197add41248f------2</link>
            <guid isPermaLink="false">https://medium.com/p/81e6eafa72cb</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[sales]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[Patiparn Nualchan]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 15:19:13 GMT</pubDate>
            <atom:updated>2023-01-31T15:19:13.335Z</atom:updated>
            <content:encoded><![CDATA[<p>Use 3 years of sale data to cluster store as 4 clusters. Aim to separate action on each cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*t2eLdFewoDjGwnNAujnAyA.png" /></figure><p>In retail business, store is a marketplace that brand decide to invest and aim it to be the happy place for customer and brand in term of sale activation, but sometime store can’t work on that function… <strong><em>sals was not good!! what we can help them!?</em></strong> In this project we are going to explore it.</p><blockquote>for this project, if you image 20 feature information with 10000 up recording such as Welmart data, pls skip. In the real world not all of the brand can get such kind of information. We just know total sales in each store and that’s it!. what can we do. Not cry on your limitation just do the best, so let’s go!!</blockquote><h3>Clustering</h3><p>Unsupervise Machine Learning algorithm to group similar entities together as a cluster</p><p><a href="https://towardsdatascience.com/unsupervised-learning-and-data-clustering-eeecb78b422a">Unsupervised Learning and Data Clustering</a></p><p>Today I’m going to use <strong>K-Mean</strong> the most famous for Clustering task.</p><p><a href="https://towardsdatascience.com/k-means-clustering-from-a-to-z-f6242a314e9a">K-Means Clustering: From A to Z</a></p><h3>1. Data set</h3><p>same as other project, I start with the data. I have 3 years of sale data, 268 store_id and one more feature about store is store region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*NFqoKJglYewO9X2c9lUh9w.png" /><figcaption>data set by author</figcaption></figure><p>after reviewed, checked and cleaned it I will jump to visualize to do as much as the data can tell us. <em>(I cut 34 zero sale stores in all 3 years off, so the data were reduce from 268 to 234 stores)</em></p><h3>2. Data Visualization</h3><p>The data was small but it can tell us some interesting, let’s see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sluf02mWq3giqxm9sr20uQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*9_ZRglwY_brYGl2mdVNcfg.png" /><figcaption>each year sales mean by author</figcaption></figure><p>sales were decline every year in the big gap range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYxO3gs3cslB2q6lc-Hhtw.png" /><figcaption>violin plot each year sales by author</figcaption></figure><p>violin plot double confirm sales was decind and a lot of zero sale in Y2022</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDhKEaq0dzM9rRjZRJlftg.png" /><figcaption>Y2020–22 separate plot by author</figcaption></figure><p>separate plot in each year sales decline was noticeable in the heavy level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94bV0n7wD8u-MHh25rsv1A.png" /><figcaption>Y2020–22 only sales exceed 2000 by author</figcaption></figure><p>I put to all together and try to zoom-in by filter only sales exceed 2000 to show. It can notice 3 years sale movement together in one chart.</p><h4>Region</h4><p>I show you bar plot of region feature as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*bGKmwekoDyy3Zm2-vEWZxg.png" /><figcaption>Region by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViLNFGzmLOJ5Us50x3MB4Q.png" /><figcaption>Y2020–22 sales by region plot by author</figcaption></figure><p>and visualized it in each year below, you can see big drop was capital store continually and another noticeable drop was central region from Y21 to 22</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*1T9FhfCVASpecTwLXGH9fQ.png" /><figcaption>Y2020–22 scatter by region plot by author</figcaption></figure><p>scatter plot can see high sale in Y2020 was from capital but in Y2021 central some store was pop up and in Y2022 quite equal in the low range</p><p>All chart above were show and get us to know how bad was it and why we have to do something as much as we can.</p><h3>3. K-Mean Clustering</h3><p>as I mention above, I will use K-Mean and in this projet. I have set K already, It was 4. I would like to cluster all 234 stroes as 4 cluster/group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*_oXQp8pacEwfZ0mGkU7X3Q.png" /><figcaption>K- Mean code and output by author</figcaption></figure><p>K-mean was done with store <strong>cluster labels_ 0, 1, 2, 3 </strong>together with <strong>cluster_centers_. </strong>lets visualize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*eLAVDaYanq51KJ8Q3FuxRA.png" /><figcaption>2D plot can show 4 point of cluster center by author</figcaption></figure><p>2D plot can show <strong>4 point of cluster center (yellow point)</strong> but we cann’t see which cluster each data belong to, so we need to use 3D plot to see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*uqunNf_8y97ALg4lBB7sgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*o67yq9GxC7d0YRTSWfvZiw.png" /><figcaption>3D plot of 4 cluster by author</figcaption></figure><p>3D plot show color in each cluster and easy to see in each cluster. we can check average values in each cluster to deine group name and interpret</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*fo-4qXlyYwNn_SXk7ZD5aw.png" /><figcaption>cluster summary by author</figcaption></figure><h4>Cluster summary</h4><ul><li><strong>ClusterA: <em>11 BEST</em></strong> store to get sale back and keep with 39857 sum of 3 year sales</li><li><strong>ClusterB: <em>16 GOOD</em></strong> store that have potential and sales can growth in the future with 25601 sum of 3 year sales</li><li><strong>ClusterC: <em>49 BASE</em></strong> store that sale can genarate from suitable SKU, find suitable SKU to this grop and keep in in the distrubution objective</li><li><strong>ClusterD: <em>158 BAD</em></strong> store that can not return in any invest so sales shoud terminate in this group</li></ul><h3>Conclusion</h3><p>Main part is clustering and all above summary each action in each cluster. This project was not complex and easy to code but the result can imprement in thhe real world. It was enough for you to efford and do the best to solve your case.</p><p>I hope it can motivate you to start your code for your case, please enjoy 😄 full code same on my github <a href="https://github.com/MossMojito/clustering">https://github.com/MossMojito/clustering</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81e6eafa72cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classification Promotion on sales data]]></title>
            <link>https://mpatiparn-n.medium.com/classification-promotion-on-sales-data-e995687f93bf?source=rss-197add41248f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e995687f93bf</guid>
            <category><![CDATA[fmcg]]></category>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[promotion]]></category>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Patiparn Nualchan]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 17:18:13 GMT</pubDate>
            <atom:updated>2023-01-29T17:18:13.625Z</atom:updated>
            <content:encoded><![CDATA[<p>continues part of <a href="https://medium.com/@mpatiparn-n/regression-on-price-promotion-data-662a991fd68c?source=your_stories_page-------------------------------------">Regression on Price Promotion data</a>. It switch RSP and all of promotion to <strong>class 0 and 1</strong>. Learn how to classify them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*aaUVBJVyZytDGBQs7nONZA.png" /></figure><h3>Classification</h3><p>another part of Supervise learnign that the target is categorical/class not continuous data. It mean we can not calculate sum or average on the target. the main explore on it is frequency base calculation such as countplot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*O-6tNlHmeA3sCVDFEIO2NA.png" /><figcaption>Image from <a href="http://freepik.com/">Freepik</a></figcaption></figure><h3>1. Data set</h3><p>I manipulate data abit to switch it from Regression data to Classification data show as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*hhPqdWRnW7lCa1I1DA9H_g.png" /><figcaption><strong>Classification data</strong> by author</figcaption></figure><p>and I did some data cleaning and generated feature from ‘date’ same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*C7r1Odgvlt934R_9S0Targ.png" /><figcaption><strong>Classification data (use)</strong> by author</figcaption></figure><p>and I changed name of target feature from <strong>pro_npro to ‘pro_class’</strong> now we expand from original<strong><em> 6 features to 9 features columns.</em></strong></p><h3>2. Data Visualization</h3><p>as mentioned above, it limit to explore class target but it still. I first took a look as inside of class 1 (pro) because I combined all of price promotion together and it better to see each promotion inside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*rFrpKLyicN4Dqh_VWsNn2A.png" /><figcaption><strong>inside of class 1 (promotion)</strong> by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*jgiyMAXYq_VrwlQG5mPjrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*8WeN740VorgC5WVpANOlAw.png" /><figcaption><strong>Targer class 0(RSp) and 1(pro)</strong> by author</figcaption></figure><p>by eye we can see and say it’s <strong>balance</strong> (if Minority class is high gap with Majority class it call <a href="https://towardsdatascience.com/class-imbalance-a-classification-headache-1939297ff4a4"><strong>imbalance</strong> </a>case. It have to do some action<em>(simple approach</em><strong> </strong><em>are up or down sampling)</em> before create any model. To aviod domination of Majority on Minority — if imbalance stay in the end result, model will relply all Majority, so imbalance is very important issue in classification) lucklly, our data no need to do any approach ^^</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*edUvaiSsHYGyM0m7CH1KsA.png" /><figcaption><strong>imbalance simple approach by </strong>by my phd : Eakasit_Pacharawongsakda</figcaption></figure><p>Anyway, We can explore target class through other continuous feature by plot them then separate each class by color or any sub-graph blah blah blah</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpP6dxWt3y9tEmH-k7es1w.png" /><figcaption><strong>offtake</strong> plot by date color by target class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vxYMQLaEferXwV0LoAVc_w.png" /><figcaption><strong>stores</strong> plot by date color by target class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmBtBZ6fFeQMBkYHEYAnIg.png" /><figcaption><strong>sales_in</strong> plot by date color by target class</figcaption></figure><p>you can see <strong>offtake</strong> seem to separate class 0 in low rage and 1 in higher but not much in other (stores and sales_in)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUULFeHnGUxG4pL3gpUf2g.png" /><figcaption><strong>offtake </strong>displot color by target class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOsh9RW-UfUlDH3ISqiRfQ.png" /><figcaption><strong>store </strong>displot color by target class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_vyGwp3CUtrAtB0v0iEiQ.png" /><figcaption><strong>sales_in </strong>displot color by target class</figcaption></figure><p><em>[ *Remake: for </em><strong><em>Sales_in,</em></strong><em> it seem to have some outstanding data and it should remove as outlier, In actually outliers is a mistake or other wrong recording, but this case all of outstanding was correct (verified my author) and the previous task- Regression I decided to remove and did it, so this classification I would like to do it in case of not-remove to keep and see it effect ]</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*sM5MNziS1uvfBuSveUGEyQ.png" /><figcaption><strong>corr heatmap</strong> by authhor</figcaption></figure><p>final check with heatmap to show correlation off ‘<strong>pro_class</strong>’ with other all feature (we can calculate corr because we still keep target class as number 0, 1 to see and check this kind of thing, but in the formal and correct type it should be category type and it can’t be for the calculation)</p><p>for <strong>correlation </strong>world, it have its own world in many name of type to use depend on many factor, main factor is type of data such as below table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*KV6bMB6UQZOEEPakaQa72A.png" /><figcaption><a href="https://www.scribbr.com/statistics/correlation-coefficient/"><strong>Correlation coefficient type</strong></a></figcaption></figure><p>the <strong>default of .corr() is Pearson’s</strong> that were our result in heatmap.</p><h3>3. Preprocessing</h3><p>now we are ready to next step to the model, but we need preprocessing step to get our data ready too.</p><blockquote>In this time I decided to not do <strong><em>Standardizing</em></strong> and <strong><em>Normalization </em></strong>because as my research ,learn annd experience Treebase algorithm (Decisiontree, Randomforest or any boosting) not really need scale the data. But I’m not expert enough to say “it no need”. I just would like to not do and lets see how does it going to be 😆</blockquote><p>Therefore, we splited df_train as train and valid then did it as array([]) on feature that we selected <strong><em>[‘month’, ‘week_of_year’, ‘sales_in’, ‘stores’,’offtake’]</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*WH-UmZz_NyQy-O3px7O8BA.png" /><figcaption><strong>split train and Valid</strong> by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*HWhvh4XhmgUMOvO7yUXB5g.png" /><figcaption>did it as <strong>array</strong> by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*PgnoFMDCSB1j3JoR_O0J5g.png" /><figcaption>X_train[0:5] by author</figcaption></figure><h3>4. Model &amp; Measure regression performance</h3><p>I did it on Treebase same for the model, but I think main talking is measurement. Classification have unique measurement to measure prediction class correct or not correct it call <a href="https://en.wikipedia.org/wiki/Confusion_matrix"><strong>confusion metrix</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*ADIeBNSFrCOWWdr-lqEhgA.png" /><figcaption><strong>Classification measurement</strong> by my phd : Eakasit_Pacharawongsakda</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Confusion_matrix"><strong>confusion metrix</strong></a> is the result table/ <strong>TP = True Positive / FP = Flase Positive / TN = True Negative / FN = False Negative. </strong>They are variable to calculate</p><p>TP/FP/TN/FN are ready to calculate <strong>Precision / Recall / Accuracy and F1.</strong></p><p><a href="https://towardsdatascience.com/accuracy-precision-recall-or-f1-331fb37c5cb9">Accuracy, Precision, Recall or F1?</a></p><h4>4.1 DecisionTreeClassifier</h4><p>I did DecisionTree as a baseline same and measured it with <strong>F1 score</strong> (already combine Precision / Recall) together and <strong>Accuracy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2t5xUWvueMaehhkyrtQgw.png" /><figcaption>real offtake and <strong>DecisionTreeClassifier</strong> prediction result plot comparison <strong>on train </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*o1g6fuQxaKoO4r02lDPfXQ.png" /><figcaption><strong>DecisionTreeClassifier</strong> prediction report <strong>on train </strong>by author</figcaption></figure><p>baseline predicted on train was super powerful <strong>98 %Accuracy</strong> and <strong>99% F1 both on RSP and Pro </strong>with only 1 miss class (yellow hilight)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vsNsFsTOJl1fVXH8Te0MA.png" /><figcaption>real offtake and <strong>DecisionTreeClassifier</strong> prediction result plot comparison <strong>on valid </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*1K3BMI1PRSdzeBz4KKcB_w.png" /><figcaption><strong>DecisionTreeClassifier</strong> prediction report <strong>on valid </strong>by author</figcaption></figure><p>and for Valid was still good at <strong>86%Accuracy</strong> and <strong>91% F1 on RSP </strong>with 2 data miss class prediction (one each).</p><h4>4.2 RandomForestClassifier</h4><p>next to 100 trees as a Forest with Validation (TimeSeriesSplit) same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aek6dWB2B4fVrQocFupOPg.png" /><figcaption>real offtake and <strong>RandomForestClassifier </strong>prediction result plot comparison <strong>on train </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*JwPu3MfZH9_TqTts7IGI5w.png" /><figcaption><strong>RandomForestClassifier</strong>prediction report <strong>on train </strong>by author</figcaption></figure><p>RandomForestClassifier predicted 1 data miss same as DT and the score was same <strong>98 %Accuracy</strong> and <strong>99% F1 both on RSP and Pro</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BefaMBcGuCtG_R8KSznGFg.png" /><figcaption>real offtake and <strong>RandomForestClassifier </strong>prediction result plot comparison <strong>on valid </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*pZxKGbXpJLl9KAYUUBVO3Q.png" /><figcaption><strong>RandomForestClassifier</strong>prediction report <strong>on valid </strong>by author</figcaption></figure><p>it was same score and 2 data miss class prediction same as DT.</p><h4>4.3 XGBClassifier</h4><p>I love Xgb, so I will always see Xgb in my project 😄</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIhNm3twTVNbeANN087SiA.png" /><figcaption>real offtake and <strong>XGBClassifier </strong>prediction result plot comparison <strong>on train </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*rdyvMX3KVLtiFXiQiHv4tg.png" /><figcaption><strong>XGBClassifier </strong>prediction report <strong>on train </strong>by author</figcaption></figure><p>Xgb was same as prediction result as DT and Rnd with <strong>98 %Accuracy</strong> and <strong>99% F1 both on RSP and Pro</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9876JZ5Y9Jn1fsMNGBJwA.png" /><figcaption>real offtake and <strong>XGBClassifier </strong>prediction result plot comparison <strong>on valid </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*vUC_8aHi73zTocG_eTUCwQ.png" /><figcaption><strong>XGBClassifier </strong>prediction report <strong>on valid </strong>by author</figcaption></figure><p>it was also same score and 2 data miss class prediction same as DT and Rnd.</p><h4>Model summary</h4><ul><li>DT- Train : 98% Acc /99% F1 both | valid 86%Acc /91,75% F1 on RSP,Pro</li><li>Rnd- Train : 98% Acc /99% F1 both | valid 86%Acc /91,75% F1 on RSP,Pro</li><li>Xgg- Train : 98% Acc /99% F1 both | valid 86%Acc /91,75% F1 on RSP,Pro</li></ul><p>And the confusion matrix of Train of all 3 was [[56 0] [1 3]] and [[10 1] [1 3]] same. All Treebase classifiers were learned and predicted in the same way with super high result of train and high in valid. If it stop at this step we will summarize that this all 3 model was powerful and prefect to use to classify Promotion class, but is that correct conclusion without final test with unseen data?</p><h4><strong>Feature_importances</strong></h4><p>before go to unseen data test we have to know which feature was the most important for model prediction and as all 3 model above gave the same preformance so to see Feature_importances I pick up the most lightest model as simple DecisionTree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*XRnd0oFrYVLzqE9k8fpX0w.png" /></figure><p>as you can see offtake was outstanding score from other as we used to see and realised from Visualization part</p><h4>4.4 guest model : Logistic Regression</h4><p>Due to the important score of offtake was strongest so I have an idea to simplify this project by cut other feature off and keep only <strong>‘offtake’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*GXz7xKF3oVB14Oa_qBSPGQ.png" /><figcaption>train and val data for Logistic Regression by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-Hr7RcX1csLjE3X5SR1aA.png" /><figcaption>real offtake and <strong>Logistic Regression</strong> prediction result plot comparison <strong>on train </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*XsVx2wg3hQlmdbDqbXDOWg.png" /><figcaption><strong>Logistic Regression </strong>prediction report <strong>on train </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23Tufw7y0eSBbGb8dyiKXg.png" /><figcaption>real offtake and <strong>Logistic Regression</strong> prediction result plot comparison <strong>on valid </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*pcAEii4wQmO2zbuOvGYipg.png" /><figcaption><strong>Logistic Regression </strong>prediction report <strong>on valid </strong>by author</figcaption></figure><p><strong>Logistic Regression on train</strong> only ‘offtake’ feature was more general as you can see yellow hilight. there were many data miss their class so the <strong>accuracy was 77% and f1 84% on RSP and 64% on Pro</strong></p><p><strong>Logistic Regression on valid</strong> the result was same as Treebase with valid 86% Accuracy and 91,75% F1 on RSP,Pro.</p><blockquote>The result was interesting and difference with Treebase especially on train data that was more general so I will pick Logistic Regression to test with unseen data next 😁</blockquote><h3><strong>5. </strong>unseen data <strong>(df_test)</strong></h3><p>Now we complete training and eveluation step on our model with train and validate set of data. next we are going to test our model with unseen data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*k9Y2zFbPre_7Pi5XXL2JgQ.png" /><figcaption><strong>df_test</strong> by author</figcaption></figure><p>after read data we did some cleaning and added date feature and final preparation it from df to array([]) of X_test same as X_train to ready to test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*FpSwmujTiJI1HDhV7vCMaQ.png" /><figcaption><strong>df_test</strong> by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*BZjJqVfE0YE05IvE4iNxFg.png" /><figcaption><strong>X_test</strong> array by author</figcaption></figure><h4>5.1 Test with DecisionTreeClassifier</h4><p>same as mention above, all treebase gave the same so DecisionTree was good enough to pick up for test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBd9262odDhOUMu-15Wl4Q.png" /><figcaption>real offtake and <strong>DecisionTreeClassifier </strong>prediction result plot comparison <strong>on test </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*i6q3MHlGaWjlwCnU253w3Q.png" /><figcaption><strong>DecisionTreeClassifier </strong>prediction report <strong>on test </strong>by author</figcaption></figure><p>badly,<strong> </strong>DecisionTreeClassifier with superpowerful train 98% accuracy can not predicted any Pro class(1) on test data.</p><h4>5.2 test with guest model : Logistic Regression</h4><p>I hope more general model as Logistic Regression can predict Pro class at least 1 data is ok, lets see how does it predict on our test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MBCYz_UgGbfYGrHpFeGwA.png" /><figcaption>real offtake and <strong>Logistic Regression </strong>prediction result plot comparison <strong>on test </strong>by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*GbVqgem9bZuDPk5kNhtVNQ.png" /><figcaption><strong>Logistic Regression </strong>prediction report <strong>on test </strong>by author</figcaption></figure><p>Wow! Logistic Regression with only ‘offtake’ can predict 100% Accuracy and double confirm with prefect ROC chart below ^^</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*nAgelqlic1FXsZ5MDe9b0w.png" /><figcaption><strong>Logistic Regression </strong>ROC <strong>on test </strong>by author</figcaption></figure><h3>Conclusion</h3><ul><li>Classification is one of important algorithm to learn, practice and get familiar with. The main issue is usally discuss on confusion matrix (get confuse with confusion matrix 😄)</li><li>Treebase algorithm are wonderful in term of widely use both of Regression and Classification task but sometime we need something more simply. Regression, K-mean, SVM, KNN Navie Bayes blahh blah</li><li>No need to fix and stick on other people method if is not fix your problem, you case. be confident on your idea and do it and hope it error not alert 😄</li><li>Data scientist is scientist, any your action is your experiment in the science lab, bomb can happen but you will learn how to aviod next.</li></ul><p>Thank for you reading, hope you will enjoy my experiment and see you 😊</p><p>fullcode here on my github same <a href="https://github.com/MossMojito/classification">https://github.com/MossMojito/classification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e995687f93bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regression on Price Promotion data]]></title>
            <link>https://mpatiparn-n.medium.com/regression-on-price-promotion-data-662a991fd68c?source=rss-197add41248f------2</link>
            <guid isPermaLink="false">https://medium.com/p/662a991fd68c</guid>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[grocery-store]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[fmcg]]></category>
            <dc:creator><![CDATA[Patiparn Nualchan]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 17:45:53 GMT</pubDate>
            <atom:updated>2023-01-26T17:45:53.868Z</atom:updated>
            <content:encoded><![CDATA[<p>How to use regression model to predict offtake(sales_out) on sales_in , number of store on promotion data in retail business.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCw2HAfqEuK9fTy9wwCsZg.png" /></figure><p>Hello, it again for me to talk about sales forecasting/prediction in retails. I worked in this domain so long, sales is always the first of all.</p><p>In previous article, I used to talk about sales forecasting on one-single sales data(univariate) by sktime package and one another article was sales forecasting with Deep learning technic.</p><p>This article I will work on Tabular Data/ Table Data / Datafram data (whatever name) but it mean we work on <strong>multivariate</strong>.</p><h3>1. Data set</h3><p>I have Tabular of tain and test data(use it as unseen data) in csv. It contain: <strong><em>date, sales_in</em></strong><em>, number of </em><strong><em>stores</em></strong><em>, </em><strong><em>offtake</em></strong><em>(average sales_out pre store) as our target in numerical type of data and one categirical data </em><strong><em>pro</em></strong><em>(price_promotion)</em></p><blockquote>my interested in this project was the relation between <strong>sales_in — offtake</strong> and <strong>stores — offtake</strong>. how do they were related to? a lot of stores number should get high offtake? a lot of sales_in should get high offtake as well? Is that correct? , I would like to explore in this preject. let’s go together!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*Lov-EDp7EhoN4s5Fno1GBg.png" /><figcaption>df.tail to see the data from the bottom by author</figcaption></figure><p>after loaded and did some data cleaning, my first action was simple to generate more useful feature from existing feature such as <strong>date(time)</strong> to get <strong>year, month and week_of_year</strong> and get <strong>dummy of categirical data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*_3sddT7tmPMo9OWYaMOLiQ.png" /><figcaption>dataset afte extracted some feature such as <strong>Date(time)</strong> and get <strong>dummy of categirical data </strong>by author</figcaption></figure><p>now we expand from original<strong><em> 5 features to 12 features columns.</em></strong></p><h3>2. Data Visualization</h3><p>Now the data have no any missing values, we can explore it to get more insigh before any model making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*q7sZVW2XudZtWVOfCdJx4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*saPis2bCaS8eWJlRq_Y16A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*FTY2FtkjE_zGWhHKEXm7UA.png" /></figure><p>We start with our <strong>offtake (target), stores and sales_in.</strong></p><ul><li><strong>offtake: </strong>was stable, up and down in the range of 5–12(approximately)</li><li><strong>Stores</strong>: Trend Line was noticable going down and decline</li><li><strong>Sales_in</strong>: seem to be stable but we got 3 strange peak(investigated need)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*kwf9dFzfDp3lrmQRE8ljIQ.png" /><figcaption>sales_in after remove outlier .</figcaption></figure><p>For 3 peaks of Sales_in, author decided to call it as outlier that need to remove, so the new chart above show Sales_in after remove outlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*FRKfXu4xKgfWLbR3Tu-Iig.png" /></figure><p>For <strong>categirical data [‘Pro’], </strong>countplot show the normal situation of promotion. The normal price(RSP) was highest and so on in other price promotion.</p><p>I this article we will cut hevvy level of promotion such as BOGO (buy1 get1) and buy2+1 off. To keep just only normal price discount level.</p><blockquote>hevvy promotion is predictable, the offtake is going to be high. We need to explore what we can’t expect or assump by our ideas, so we cut it off !!! (it mean we need the power of Machine Learning to help us!)</blockquote><h3>3. Feature checking</h3><p>To describe each feature base on statistics measurement. we inspected<strong><em>: ‘types’, ‘counts’, ‘distincts’, ‘nulls’, ‘missing_ration’, ‘uniques’, ‘skewness’, ‘kurtosis’, corr_col : </em></strong>we define not a code to inspect below.</p><pre>obs = df_train.shape[0]<br>types = df_train.dtypes<br>counts = df_train.apply(lambda x: x.count())<br>uniques = df_train.apply(lambda x: [x.unique()]).transpose()<br>nulls = df_train.apply(lambda x: x.isnull().sum())<br>distincts = df_train.apply(lambda x: x.unique().shape[0])<br>missing_ration = (df_train.isnull().sum()/ obs) * 100<br>skewness = df_train.skew()<br>kurtosis = df_train.kurt() <br><br>corr = df_train.corr()[&#39;offtake&#39;]<br>corr_col = &#39;corr &#39;  + &#39;offtake&#39;<br>str = pd.concat([types, counts, distincts, nulls, missing_ration, uniques, skewness, kurtosis, corr], axis = 1, sort=False)<br>cols = [&#39;types&#39;, &#39;counts&#39;, &#39;distincts&#39;, &#39;nulls&#39;, &#39;missing_ration&#39;, &#39;uniques&#39;, &#39;skewness&#39;, &#39;kurtosis&#39;, corr_col ]<br>str.columns = cols<br>str.sort_values(by =&#39;corr offtake&#39;, ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfTFYA4-1mRsGNOHEh7y2w.png" /></figure><p><strong>‘corr offtake’</strong> showed relation between each feature call <strong><em>correlation.</em> </strong>It<strong><em> </em></strong>represent relation between feature in the range number between -1 till 1.</p><p><a href="https://towardsdatascience.com/what-is-correlation-975ea899aaed">What is correlation?</a></p><p>by <strong>Feature checking Table</strong>, <em>we see </em><strong><em>pro_2for</em></strong><em> was strongest relation with offtake in the positive and </em><strong><em>pro_RSP</em></strong><em> was also strongest relation with offtake in the negative. our interested feature </em><strong><em>sales-in</em></strong><em> was abit in negative and </em><strong><em>stores </em></strong><em>was quite ok in positive.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*CshEHrSmSX7wllrP5C5c0Q.png" /></figure><p>This chart show correlation, easy to see and summarize. Our 2 main focus variables<strong> Sales_in</strong> and <strong>Stores </strong>was<strong> 0.03 and 0.20</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSUB8wjyhm8PIwzrXYK17A.png" /></figure><p>scatterplot show and support score 0.03 and 0.20 of <strong>Sales_in</strong> and <strong>Stores.</strong></p><p>Untill this step, we can roughly concluded that the offtake is going to be high and higher with promotion doing and go back with RSP price. Our interested feature <strong>Sales_in</strong> and <strong>Stores</strong> have no any effect or relate to the offtake much. It seem to be simple conclusion but It make sense and practical in the real world. The question at this step is how to take those features to predict the offtake and which is the best important feature by score.</p><h3>4. Preprocessing</h3><p>Any model need data format correctly to train, so <strong>Preprocessing</strong> is needed.</p><p>This article have 2 set of data train and test, We import and work anything on train and keep the test as unseen data to test final model.</p><p><a href="https://towardsdatascience.com/train-test-split-and-cross-validation-in-python-80b61beca4b6">Train/Test Split and Cross Validation in Python</a></p><p>Work on<strong> train data, start </strong>with split the data as <strong>train </strong>and <strong>valid </strong>set. In this project the data was small. it just 102 record so I decided to split train[:90] and test[90:]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItySI-Mf3cicCe89g4l4zA.png" /><figcaption>train and valid set by author</figcaption></figure><p>it better to check Target(y) variation both of train and valid and it should be close and perform similarly each other as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xdgP0clj__sU6RBtOzfAA.png" /><figcaption>Target(y) check by author</figcaption></figure><h4>standardized and normalized</h4><blockquote><strong>Standardizing,</strong> the features around the center and 0 with a standard deviation of 1 is important when we compare measurements that have different units. Variables that are measured at different scales do not contribute equally to the analysis and might end up creating a bais</blockquote><blockquote><strong>Normalization</strong>, the goal of normalization is to change the values of numeric columns in the dataset to a common scale, without distorting differences in the ranges of values. For machine learning, every dataset does not require normalization. It is required only when features have different ranges.</blockquote><p><a href="https://pub.towardsai.net/how-when-and-why-should-you-normalize-standardize-rescale-your-data-3f083def38ff">How, When and Why Should You Normalize/Standardize/Rescale Your Data?</a></p><p><em>above article was a good article to explain </em><strong><em>standardized and normalized</em></strong><em>.</em></p><p>for my project, I used MinMaxScaler() for normalization and StandardScaler for Standardizing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*ns2U-zpexDYS_12IHCTSTA.png" /><figcaption>standardized and normalized step by author</figcaption></figure><p>again for displot for check variation if X both of train and Valid after standardized and normalized. It was good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5m_SdTj6br9PioHgKoNpQ.png" /><figcaption>distribution after standardized and normalized by author</figcaption></figure><p>Now we have X_train_std ready to fit in the model.</p><h3>5. Model &amp; Measure regression performance</h3><p>As show in the headline “Regression” so I will explore Regression model to predict the sales. in conclude I did 5 treebase models</p><ol><li><strong>DecisionTreeRegressor</strong> (as baseline)</li><li>DecisionTreeRegressor + <strong>TimeSeriesSplit</strong> <strong>Validation</strong></li><li>DecisionTreeRegressor + TimeSeriesSplit Validation + <strong>more params</strong></li><li><strong>RandomForestRegressor</strong> + TimeSeriesSplit Validation +more params</li><li><strong>Xgboost</strong> + TimeSeriesSplit Validation + more<strong> </strong>params</li></ol><p>For metric <strong>eveluation</strong>, I choose <strong>R-Square</strong> to get score (<em>high is good</em>) and <strong>MAE</strong>(mean_absolute_error) to see the error(<em>low is good</em>).</p><p><a href="https://towardsdatascience.com/what-are-the-best-metrics-to-evaluate-your-regression-model-418ca481755b">What are the best metrics to evaluate your regression model?</a></p><p>let’s me show some interesting part and compare it to you.</p><h4><strong>1. DecisionTreeRegressor</strong> (as baseline) was predict as show below.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_zhAW2zMUJOYLun7nvIag.png" /><figcaption><strong>1. DecisionTreeRegressor</strong> prediction plot by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*hLmFXQlb59MGqmK9I4j7GA.png" /><figcaption><strong>1. DecisionTreeRegressor</strong> model preformance plot by author</figcaption></figure><h4>2. DecisionTreeRegressor + <strong>TimeSeriesSplit</strong> <strong>Validation.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*kWZpVMyacor4XsdhXCQonw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKB8yoPCqUmoH8jjkMjo4A.png" /></figure><p>for the second model we plus on baseline with <strong>TimeSeriesSplit </strong>for Validation.<em>(I deciede to split sequentiallly to not shuffle the data, for me it make sense and pretical when use and explain to my team and boss)</em></p><p><strong>cv_ls</strong> was a varible to contain set of train and valid that was splited. I set 5 for <strong>n_split,</strong> mean divide whole data as 5 fold. 10 for <strong>test_size,</strong> mean 10 data point had splited to valid in each fold and step ahead in next fold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zi7Wxij1XXFM3o_gmgau-g.png" /><figcaption>2. DecisionTreeRegressor + <strong>TimeSeriesSplit</strong> <strong>Validation </strong>prediction plot by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*QaJiM6WA3t4FtRIfrP3oqw.png" /><figcaption>2. DecisionTreeRegressor + <strong>TimeSeriesSplit</strong> <strong>Validation</strong> model preformance plot by author</figcaption></figure><p>both of 1 and 2, model well perform in Train set with morethan 0.90 of R-Square but bad in Valid with nagative R-Square and error was big. We need more better model.</p><h4>3. DecisionTreeRegressor + TimeSeriesSplit Validation + <strong>more params</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*kATOKT3AuKf-Sdl1sP-r7A.png" /><figcaption>parameter adding for GridSearch by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKcq2Ttv310W4Goo-8TyTQ.png" /><figcaption>3. DecisionTreeRegressor + TimeSeriesSplit Validation + <strong>more params </strong>prediction plot by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*31AhHVlkU4no6K_ASfLfhQ.png" /><figcaption>3. DecisionTreeRegressor + TimeSeriesSplit Validation + <strong>more params </strong>model preformance plot by author</figcaption></figure><p>It was improve but error still high. by eye we can see 2 data point in valid was big gap but other point was good.</p><h4><strong>4. RandomForestRegressor</strong> + TimeSeriesSplit Validation +more params</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGfZ1ksDvOsyF9rzbXPNrg.png" /><figcaption>4. <strong>RandomForestRegressor</strong> + TimeSeriesSplit Validation +more params prediction plot by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*ldIbgLi5XXgIPwRNFxRneA.png" /><figcaption>4. <strong>RandomForestRegressor</strong> + TimeSeriesSplit Validation +more params model preformance plot by author</figcaption></figure><p>RandomForest improve one of 2 big gap above better and error was lower than 1.0. it good but we explored more.</p><h4><strong>5. Xgboost</strong> + TimeSeriesSplit Validation + more<strong> </strong>params</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eY_kLWv4nAENRWWYucVzXg.png" /><figcaption>5. <strong>Xgboost</strong> + TimeSeriesSplit Validation + more params prediction plot by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*_GMbh7ld9w0pPmEHUZJQbA.png" /><figcaption>5. <strong>Xgboost</strong> + TimeSeriesSplit Validation + more params model preformance plot by author</figcaption></figure><p>Xgboost was better from RandomForest both of R-squre and error in Valid and more better both same in Train set.<strong><em> It mean Xgboost was the best model in this project!!</em></strong></p><h4>Result Summay in each model focus on Valid set only</h4><ul><li>model_1: R-squre = -0.218 | MAE = 1.372</li><li>model_2: R-squre = -0.397 | MAE = 1.527</li><li>model_3: R-squre = 0.149 | MAE = 1.126</li><li>model_4: R-squre = 0.248 | MAE = 0.947</li><li><strong>model_5: R-squre = 0.337 | MAE = 0.866 ~ <em>(Best Model) &gt;&lt;</em></strong></li></ul><h4>Feature Important</h4><p>next step on Xgboost our best model to get score<em>(.feature_importances_)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*u2FqXFxtHnWQDlXL6A0Xxw.png" /></figure><p><strong>RSP </strong>and <strong>pro_2for</strong> were our best 2 features as we used to have the assumption on its correlation far above. Our main 2 interested features <strong>Sales_in</strong> and <strong>Stores</strong> were small, match with our assumption too.</p><p>anyway, it make sense and lastly we will take the <strong>best model to predict on</strong> <strong>unseen data</strong> (test set) and measure model performance in the same metric.</p><h3>6. Predict on Unseen data (test set)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*Um8j_Mtxb6n9tDGUcpzXhQ.png" /><figcaption>unseen data by author</figcaption></figure><p>We got 10 record ready to final test our best model Xgboost, but first of all we need to manipulate data same process as train data….. the complete test show as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*nYo_502tkQEs6vDToAW1sg.png" /><figcaption>complete unseen data by author</figcaption></figure><p>next to <strong>preprocessing</strong> step to get data ready to predict</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*O-t46LEEuAWlmSJWTKIoWQ.png" /><figcaption>unseen data preprocessing by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UWgSKuCziv2GNNMgvztOA.png" /><figcaption><strong>unseen data prediction</strong> by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*-hMnfeRnijDRt8nLja_1Sw.png" /><figcaption><strong>unseen data model performance </strong>by author</figcaption></figure><p>by eye we can see not big gap of test and predict data and by score was show <strong>R-squre = 0.635 | MAE = 0.575 on unseen(test). </strong>it good and better than train and Valid data in Model_5</p><h3>Conclusion</h3><ul><li>We explore <strong>multivariate</strong> data<em>(not only one-single data),</em> how to predict offtake data on sales_in, stores and promotion data in retails business domain</li><li><strong>Correlation</strong> is important to roughly see and prove the questions untill set assumption with our domain experience on data.</li><li><strong>Valadation</strong> is important for any model.</li><li><strong>Treebase Regressions</strong> are useful and flexible to use.</li></ul><p><strong>Next!!</strong>, This project the data set was so small. To make more and more powerful of the model, more train data is needed (at least 1000 for train record: 100 for test) Anyway those prediction was used to my real task already. This was enough for me from this project ^^</p><blockquote>lastly, I have an idea for <strong>next project</strong> to combine and convert promotion price to class of data <strong>1(promotion) or 0 (no promotion)</strong> then create <strong>Classification model</strong> to classify which data record belong to which class.</blockquote><blockquote>hope to see you in the next project<strong> Classification on Price Promotion data</strong></blockquote><p>&gt;&gt; full code here <a href="https://github.com/MossMojito/Regression">https://github.com/MossMojito/Regression</a></p><p>Thank for your reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=662a991fd68c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sales Forecast with only monthly sales data[Deep Lerning Tims series Forecasting]]]></title>
            <link>https://mpatiparn-n.medium.com/sales-forecast-with-only-monthly-sales-data-deep-lerning-tims-series-forecasting-e96d6d1d5902?source=rss-197add41248f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e96d6d1d5902</guid>
            <category><![CDATA[jason-brownlee]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[deep-lerning-tims-series]]></category>
            <category><![CDATA[sales-forecasting]]></category>
            <dc:creator><![CDATA[Patiparn Nualchan]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 09:03:01 GMT</pubDate>
            <atom:updated>2022-12-29T09:03:01.761Z</atom:updated>
            <content:encoded><![CDATA[<p>Get understand deep learning time series forecasting technique. let’s talks!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*hlwzE71zn7KH7RyBHWV6Aw.png" /><figcaption>source : <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.investopedia.com%2Fterms%2Ff%2Fforecasting.asp&amp;psig=AOvVaw11mEbmXdQucuDkdHdTQC-h&amp;ust=1668686589174000&amp;source=images&amp;cd=vfe&amp;ved=2ahUKEwji-LCM1LL7AhWPyaACHWwMARwQjRx6BAgAEAo">https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.investopedia.com%2Fterms%2Ff%2Fforecasting.asp&amp;psig=AOvVaw11mEbmXdQucuDkdHdTQC-h&amp;ust=1668686589174000&amp;source=images&amp;cd=vfe&amp;ved=2ahUKEwji-LCM1LL7AhWPyaACHWwMARwQjRx6BAgAEAo</a></figcaption></figure><p>Almost all of the content, I digest from famous Forecasting book <strong><em>“Deep Learning for Time Series Forecasting” by Jason Brownlee.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*Ho2Gn5S6lSEruQL5Jrc6NA.png" /></figure><p>I make it easy to consume for me and hope it can also help you too 😄</p><h3>Part I “Start with Data”</h3><p>I will start with the data. With my exprerience, to start with data can help you to see the overview and if you familiar with the model you will realise that data input is important same as model turing or other techniqus that make your model robust.</p><p>what about <strong>“only monthly sales data”</strong> ? pls see below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/90/1*d9aT-CN3OXF170ygkUG9ig.png" /></figure><p>It’s no featureX1,X2,X3,… that you can take it train model as you familiar to do Regression model. this kind of data call <strong>“sequential data” (</strong>the<strong> </strong>sequence of data by time step-day/month/year). This data has their suitable technique to deal with call <strong>“Time series forecasting”</strong></p><blockquote><strong><em>[0] Jason Brownlee: </em></strong>“<strong>Time series</strong> <strong>forecasting</strong>” classes of methods that you can design experiments include the following:</blockquote><blockquote>1. Baseline. Simple forecasting methods such as persistence and averages.</blockquote><blockquote>2.Autoregression. The Box-Jenkins process and methods such as SARIMA.</blockquote><blockquote>3.Exponential Smoothing. Single, double and triple exponential smoothing methods.</blockquote><blockquote>4.Linear Machine Learning. Linear regression methods and variants such as regularization.</blockquote><blockquote>5.Nonlinear Machine Learning. kNN, decision trees, support vector regression and more.</blockquote><blockquote>6.Ensemble Machine Learning. Random forest, gradient boosting, stacking and more.</blockquote><blockquote><strong>7.Deep Learning. MLPs, CNNs, LSTMs, and Hybrid models.</strong></blockquote><p>In this section we are focus on <strong>Deep Learning method.</strong></p><h3><strong>Part II “Series as Supervised Learning”</strong></h3><p>as above since No4 till 7 are the Supervised Learning that we have to train, test model. but the data have no feature!! what should we do?? let’s talk about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atpd-2dwI1-hPfGDBamelA.png" /><figcaption><strong>Series as Supervised Learning</strong></figcaption></figure><p>If you confuse and have the question about how <strong>Sequential data able to train Supervise model. </strong>I confident above figure can breakthrough your unclear and bright it 😍</p><p>Supervise learning need feature X, lable y to learn and generate model to predict unseen data next. This step we will take a look, how to transform “<strong>Sequential data -&gt; Supervise input data” </strong>step by step.</p><p>first, we have to split all data(108 months) to train and test set. it simples just split last 12 months(1 year) be a test. <em>&gt;&gt;&gt; 96 months as a train/12 months as a test data set &lt;&lt;&lt;</em></p><p>Second, consider and fix how many feature you need(how many prior time step).<em> &gt;&gt;&gt; In this case we use 24 tims step to predict next 1 time step &lt;&lt;&lt; </em>lets talk about <strong>CODE </strong>below</p><pre>def series_to_supervised(data, n_in=1, n_out=1):<br>    df = DataFrame(data)      <br>    cols = list()      <br>    # input sequence (t-n, ... t-1)      <br>    for i in range(n_in, 0, -1):      <br>        cols.append(df.shift(i))      <br>    # forecast sequence (t, t+1, ... t+n)      <br>    for i in range(0, n_out):      <br>        cols.append(df.shift(-i))      <br>    # put it all together      <br>    agg = concat(cols, axis=1)      <br>    # drop rows with NaN values      <br>    agg.dropna(inplace=True)      <br>    return agg.values      <br>      <br>data = series_to_supervised(train, n_in=n_input)      <br> train_x, train_y = data[:, :-1], data[:, -1]</pre><h3>Part III “Deep Learning-MLPs, CNNs, LSTMs, and Hybrid models” (fit and predict)</h3><p>from part II we got train_X and train_y ready to fit to model. let’s me recap those models as follow</p><p><strong>(1) MLP and (2) CNN</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*5I-eT4mQCH9ft4IYFW0FLA.png" /><figcaption>source : <a href="https://www.researchgate.net/publication/336358944/figure/fig2/AS:811915186012166@1570587073649/The-common-architecture-of-MLP-and-CNN-designed-for-classification-and-regression-based.png">https://www.researchgate.net/publication/336358944/figure/fig2/AS:811915186012166@1570587073649/The-common-architecture-of-MLP-and-CNN-designed-for-classification-and-regression-based.png</a></figcaption></figure><blockquote>[1] The common architecture of MLP and CNN designed for classification and regression based neural network. <strong>MLP is consisted of fully-connected (FC) layers</strong> and <strong>CNN also contains convolution layers</strong>, pooling layers besides that.</blockquote><p><strong>(3) RNN(LSTM)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*a4w_UN-RGCUYDd1hPVLf0A.png" /><figcaption>source : <a href="http://andrisfaesal.blogspot.com/2021/01/perbedaan-cnn-vs-rnn-vs-ann-untuk.html#">http://andrisfaesal.blogspot.com/2021/01/perbedaan-cnn-vs-rnn-vs-ann-untuk.html#</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*mg5ypAF6N8MimuBWtM21rA.png" /></figure><blockquote><strong>RNN</strong> have feedback loops in the recurrent layer. This lets them maintain information in ‘memory’ over time. But, it can be difficult to train standard RNNs to solve problems that require learning long-term temporal dependencies.</blockquote><blockquote><strong>LSTM</strong> networks are a type of RNN that uses special units in addition to standard units. LSTM units include a ‘memory cell’ that can maintain information in memory for long periods of time. This memory cell lets them learn longer-term dependencies.</blockquote><blockquote><strong>LSTM</strong> deal with vanishing and exploding gradient problem by introducing new gates, such as input and forget gates, which allow for a better control over the gradient flow and enable better preservation of “long-range dependencies”</blockquote><p>source : <a href="https://ashutoshtripathi.com/2021/07/02/what-is-the-main-difference-between-rnn-and-lstm-nlp-rnn-vs-lstm/">https://ashutoshtripathi.com/2021/07/02/what-is-the-main-difference-between-rnn-and-lstm-nlp-rnn-vs-lstm/</a></p><p><strong>(4) CNN-LSTM</strong>, CNN network that learns input features and an LSTM that interpretsthem.</p><p><strong>(5) ConvLSTM</strong>, combination of CNNs and LSTMs where the LSTM units read input data using the convolutional process of a CNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*jJTAEDTAf0vtTcLrrvqo2w.png" /></figure><h4>train set to fit model</h4><p>As above, we will compare 5 model <strong><em>(1) MLP, (2)CNN, (3)LSTM, (4)CNN-LSTM, (5)ConvLSTM</em></strong> fit to train_X, train_y as we have already done spliting and series to supervised data transformation. lets talk about <strong>CODE </strong>below</p><pre># fit a model<br>def mlp_model_fit(train, config):           <br> # unpack config<br> n_input, n_nodes, n_epochs, n_batch = config<br> # prepare data<br> data = series_to_supervised(train, n_in=n_input) <br> train_x, train_y = data[:, :-1], data[:, -1]<br> # define model<br> model = Sequential()<br> model.add(Dense(n_nodes, activation=&#39;relu&#39;, input_dim=n_input))<br> model.add(Dense(1))<br> model.compile(loss=&#39;mse&#39;, optimizer=&#39;adam&#39;)<br> # fit<br> model.fit(train_x, train_y, epochs=n_epochs, batch_size=n_batch, verbose=0)<br> return model</pre><pre># fit a model<br>def cnn_model_fit(train, config):<br> # unpack config<br> n_input, n_filters, n_kernel, n_epochs, n_batch = config<br> # prepare data<br> data = series_to_supervised(train, n_in=n_input)<br> train_x, train_y = data[:, :-1], data[:, -1]<br> train_x = train_x.reshape((train_x.shape[0], train_x.shape[1], 1))<br> # define model<br> model = Sequential()<br> model.add(Conv1D(filters=n_filters, kernel_size=n_kernel, activation=&#39;relu&#39;, input_shape=(n_input, 1)))<br> model.add(Conv1D(filters=n_filters, kernel_size=n_kernel, activation=&#39;relu&#39;))<br> model.add(MaxPooling1D(pool_size=2))<br> model.add(Flatten())<br> model.add(Dense(1))<br> model.compile(loss=&#39;mse&#39;, optimizer=&#39;adam&#39;)<br> # fit<br> model.fit(train_x, train_y, epochs=n_epochs, batch_size=n_batch, verbose=0)<br> return model</pre><pre># fit a model<br>def lstm_model_fit(train, config):<br> # unpack config<br> n_input, n_nodes, n_epochs, n_batch, n_diff = config<br> # prepare data<br> if n_diff &gt; 0:<br>  train = difference(train, n_diff)<br> data = series_to_supervised(train, n_in=n_input)<br> train_x, train_y = data[:, :-1], data[:, -1]<br> train_x = train_x.reshape((train_x.shape[0], train_x.shape[1], 1))<br> # define model<br> model = Sequential()<br> model.add(LSTM(n_nodes, activation=&#39;relu&#39;, input_shape=(n_input, 1)))<br> model.add(Dense(n_nodes, activation=&#39;relu&#39;))<br> model.add(Dense(1))<br> model.compile(loss=&#39;mse&#39;, optimizer=&#39;adam&#39;)<br> # fit<br> model.fit(train_x, train_y, epochs=n_epochs, batch_size=n_batch, verbose=0)<br> return model</pre><pre>def cl_model_fit(train, config):<br> # unpack config<br> n_seq, n_steps, n_filters, n_kernel, n_nodes, n_epochs, n_batch = config<br> n_input = n_seq * n_steps<br> # prepare data<br> data = series_to_supervised(train, n_in=n_input)<br> train_x, train_y = data[:, :-1], data[:, -1]<br> train_x = train_x.reshape((train_x.shape[0], n_seq, n_steps, 1))<br> # define model<br> model = Sequential()<br> model.add(TimeDistributed(Conv1D(filters=n_filters, kernel_size=n_kernel, activation=&#39;relu&#39;, input_shape=(None,n_steps,1))))<br> model.add(TimeDistributed(Conv1D(filters=n_filters, kernel_size=n_kernel, activation=&#39;relu&#39;)))<br> model.add(TimeDistributed(MaxPooling1D(pool_size=2)))<br> model.add(TimeDistributed(Flatten()))<br> model.add(LSTM(n_nodes, activation=&#39;relu&#39;))<br> model.add(Dense(n_nodes, activation=&#39;relu&#39;))<br> model.add(Dense(1))<br> model.compile(loss=&#39;mse&#39;, optimizer=&#39;adam&#39;)<br> # fit<br> model.fit(train_x, train_y, epochs=n_epochs, batch_size=n_batch, verbose=0)<br> return model</pre><pre>def conl_model_fit(train, config):<br> # unpack config<br> n_seq, n_steps, n_filters, n_kernel, n_nodes, n_epochs, n_batch = config<br> n_input = n_seq * n_steps<br> # prepare data<br> data = series_to_supervised(train, n_in=n_input)<br> train_x, train_y = data[:, :-1], data[:, -1]<br> train_x = train_x.reshape((train_x.shape[0], n_seq, 1, n_steps, 1))<br> # define model<br> model = Sequential()<br> model.add(ConvLSTM2D(filters=n_filters, kernel_size=(1,n_kernel), activation=&#39;relu&#39;, input_shape=(n_seq, 1, n_steps, 1)))<br> model.add(Flatten())<br> model.add(Dense(n_nodes, activation=&#39;relu&#39;))<br> model.add(Dense(1))<br> model.compile(loss=&#39;mse&#39;, optimizer=&#39;adam&#39;)<br> # fit<br> model.fit(train_x, train_y, epochs=n_epochs, batch_size=n_batch, verbose=0)<br> return model</pre><h4>test set to predict model</h4><p>now we create function(def) of all 5 model, next we are going to talk about prediction part that talk test set. but first of all let recap our test set and how complex dose it is and how to get it ready to use in model.predict()</p><p><em>&gt;&gt;&gt; split 96 months as a train/</em><strong><em>12 months as a test data set </em></strong><em>&lt;&lt;&lt;</em></p><p><em>&gt;&gt;&gt; use 24 tims step to </em><strong><em>predict next 1 time step</em></strong><em> &lt;&lt;&lt;</em></p><p>it mean 12 months test set is the result of 24 times step prior, see below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*7p9pX2TvOm1jKfft6mu6dw.png" /></figure><p>as you can see, our 12 times step test is test_y that we will use to measure error prediction. for <em>test_X we have to generate from 24 times step prior</em> if 12 test(test_y) by loop it back to history it then split history and reshape to x_input. <strong>yess we get test_X name x_input!!!</strong> lets see more and <strong>CODE</strong> below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oz_-EjCgBbM9bhEtuf0sDQ.png" /></figure><pre># forecast with a pre-fit model<br>def model_predict(model, history, config):<br> # unpack config<br> n_input, _, _, _, _ = config<br> # prepare data<br> x_input = array(history[-n_input:]).reshape((1, n_input, 1))<br> # forecast<br> yhat = model.predict(x_input, verbose=0)<br> return yhat[0]</pre><p>a difference about input dimentional you need to know in each model, so in term of code to prepare data, pls see below</p><pre>#mlp- 2D_input_shape<br>x_input = array(history[-n_input:]).reshape(1, n_input)<br><br>#cnn- 3D_input_shape<br>train_x = train_x.reshape((train_x.shape[0], train_x.shape[1], 1))<br>x_input = array(history[-n_input:]).reshape((1, n_input, 1))<br><br>#lstm- 3D_input_shape<br>train_x = train_x.reshape((train_x.shape[0], train_x.shape[1], 1))<br>x_input = array(history[-n_input:]).reshape((1, n_input, 1))<br><br>#cnn-lstm- 4D_input_shape<br>train_x = train_x.reshape((train_x.shape[0], n_seq, n_steps, 1))<br>x_input = array(history[-n_input:]).reshape((1, n_seq, n_steps, 1))<br><br>#convlstm- 5D_input_shape<br>train_x = train_x.reshape((train_x.shape[0], n_seq, 1, n_steps, 1))<br>x_input = array(history[-n_input:]).reshape((1, n_seq, 1, n_steps, 1))</pre><blockquote><strong><em>[0]Jason Brownlee: </em>Cnn-lstm,</strong> The number of lag observations per sample is simply (n seq n steps). This is a 4-dimensional input array now with the dimensions: [samples, subsequences, timesteps,features]</blockquote><blockquote><strong><em>[0]Jason Brownlee: </em>Convlstm,</strong> This type of model is called a Convolutional LSTM, or ConvLSTM for short. It is provided in Keras as a layer called ConvLSTM2D for 2D data. We can configure it for use with 1D sequence data by assuming that we have one row with multiple columns. As with the CNN-LSTM, the input data is split into subsequences where each subsequence has a fixed number of time steps, although we must also specify the number of rows in each subsequence, which in this case is fixed at 1. The shape is five-dimensional, with the dimensions: [samples, subsequences, rows,columns, features].</blockquote><h4>Prediction</h4><p>Now we got 5 model have already fit and we understood the X_input(test_X), so next step is predict. lets see CODE below</p><pre># walk-forward validation for univariate data<br>def walk_forward_validation(data, n_test, cfg):<br> predictions = list()<br> # split dataset<br> train, test = train_test_split(data, n_test)<br> # fit model<br> model = cnn_model_fit(train, cfg)<br> # seed history with training dataset<br> history = [x for x in train]<br> # step over each time-step in the test set<br> for i in range(len(test)):<br>  # fit model and make forecast for history<br>  yhat = model_predict(model, history, cfg)<br>  # store forecast in list of predictions<br>  predictions.append(yhat)<br>  # add actual observation to history for the next loop<br>  history.append(test[i])<br> # estimate prediction error<br> error = measure_rmse(test, predictions)<br> print(&#39; &gt; %.3f&#39; % error)<br> return error<br> <br># repeat evaluation of a config<br>def repeat_evaluate(data, config, n_test, n_repeats=30):<br> # fit and evaluate the model n times<br> scores = [walk_forward_validation(data, n_test, config) for _ in range(n_repeats)]<br> return scores</pre><p>we predict through <strong>Walk-forward validation</strong>. That is a Cross-Validation Technique for Time-Series Data and we repeat n = 30 for evaluation</p><p><a href="https://audhiaprilliant.medium.com/walk-forward-optimization-cross-validation-technique-for-time-series-data-61739f58f2c0">Walk-Forward Optimization — Cross-Validation Technique for Time-Series Data</a></p><h4>Prediction Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*2rXRV5Xv7LcuEoN_fud3LQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*q9f7EAD8JorthNaPTFQvrQ.png" /></figure><p>by eye, we can see it go to the same way but can’t definitely separate or measure which is the best model. To know it we have to <strong>Evaluate</strong> them to measure prediction error in number.</p><h3>Part IV “Evaluation” measure prediction error</h3><p>any model need Evaluation to measure the error and decide does the model good enough to use. RMSE is one of popular measurement</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*_AWwVJKZwf5zKWvsfU0hVw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*pYD6zYWBnBBnVc-BMldmoA.png" /></figure><p>Barchart show the lowest RMSE_Score was cnn_predict from CNN model. It was very close to MLP model at around 1500, RMSE_Score of complexity model was higher it mean to add more complexity was not guarantee best model (less error). it depend on the data and problem as well.</p><h3>Part V “Summary and Feature work”</h3><p>first, lets plot the best model CNN with Actual. pls see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*kkoMZFgDS1yHJyZdJsabiQ.png" /></figure><ul><li>We understand and learn how to tranform <strong>Time series data to supervise data</strong> (you can solve the problem with Machine Learning after the data have already perform in Supervise data such as <em>Ensemble </em><strong>Machine Learning</strong> — Random forest, gradient boosting, stacking and more…)</li><li>In this project, I decide to talk about one step prediction, but in the real world the <strong>Multu-step forecasting</strong> is more practical.</li><li>We will pick up our best model CNN and move to learn about <strong>Multu-step forecasting with Machine Learnig ngmodel adding (XGboost)</strong></li></ul><p>Thank you for your attention since beginnig part till the final.</p><p><a href="https://www.researchgate.net/figure/The-common-architecture-of-MLP-and-CNN-designed-for-classification-and-regression-based_fig2_336358944">[1] Robust Sub-meter Level Indoor Localization with a Single WiFi Access Point — Regression versus Classification</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e96d6d1d5902" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xgboost time series forcasting with sktime [ep#2]]]></title>
            <link>https://mpatiparn-n.medium.com/xgboost-time-series-forcasting-with-sktime-ep-2-5a5525d902ab?source=rss-197add41248f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a5525d902ab</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[sktime]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[sales-forecasting]]></category>
            <dc:creator><![CDATA[Patiparn Nualchan]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 08:35:25 GMT</pubDate>
            <atom:updated>2022-12-29T08:35:25.667Z</atom:updated>
            <content:encoded><![CDATA[<p>build,fine- tune and eveluate ML model on time series data with sktime</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKWNyyotALFd-yLksIoKaQ.jpeg" /></figure><p>Again Hello, in this ep#2 we are going to talk about step 3–5 (as below). Don’t waste the time, let’s go !!</p><ol><li>Time series data (rough concept to deal with <strong>one single — sales data</strong>)</li><li>Time series analysis (<strong>EDA</strong> and <strong>stationary testing</strong>)</li></ol><h4>3. Time series forecasting (modeling and prediction)</h4><h4>4. Time series cross validation (temporal cross validation)</h4><h4>5. fine-tune xgboost (get best parameter)</h4><p>Briefly recap, from ep#1 we get the data ready y_train, y_test (by <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.model_selection.temporal_train_test_split.html"><em>temporal_train_test_split</em></a>) from and fh (by <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.base.ForecastingHorizon.html"><em>ForecastingHorizon</em></a>). Our goal is to create <strong>model </strong>to predict 12 week(3 month) sales ahead.</p><p>3 Time series forecasting, Sktime <strong>transform time sequence to supervise </strong>and ready to do <strong>Machine Learning task</strong>, so we can mention now we are working on Regression. I pick up some of Regression model as follow.</p><ul><li>AutoARIMA* (a classic Time series technique)</li><li>KNeighborsRegressor</li><li>LinearRegression</li><li>XgbRegressor</li></ul><p>for the model performance was take <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.performance_metrics.forecasting.MeanAbsolutePercentageError.html#sktime.performance_metrics.forecasting.MeanAbsolutePercentageError"><strong>mean_absolute_percentage_error</strong></a>(MAPE) by sktime.performance_metrics.forecasting <em>[MAPE is measured in percentage error relative to the test data. Because it takes the absolute value rather than square the percentage forecast error]. code here.</em></p><pre>from sktime.performance_metrics.forecasting import mean_absolute_percentage_error<br>print(&#39;MAPE: %.4f&#39; % mean_absolute_percentage_error(y_test, y_pred, symmetric=False))</pre><h4>AutoARIMA</h4><p><em>In Auto ARIMA, the model itself will generate the optimal p, d, and q values which would be suitable for the data set to provide better forecasting.</em></p><p><a href="https://towardsdatascience.com/time-series-forecasting-using-auto-arima-in-python-bb83e49210cd">Time Series forecasting using Auto ARIMA in python</a></p><p>code here,</p><pre>from sktime.forecasting.arima import AutoARIMA<br><br>forecaster = AutoARIMA(start_p=8, max_p=9, suppress_warnings=True)<br><br>forecaster.fit(y_train)<br>y_pred = forecaster.predict(fh)<br>plot_series(y_train, y_test, y_pred, labels=[&quot;y_train&quot;, &quot;y_test&quot;, &quot;y_pred&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZfKbxITRJHU7mIud2eCkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*SDHhrYet7BpnyqlsxVfRJg.png" /></figure><p>as you can see, y_pred can’t predict any up and down trend and MAPE showed 0.75(75% of error).</p><h4>KNeighborsRegressor</h4><p><em>The KNN algorithm uses ‘</em><strong><em>feature similarity</em></strong><em>’ to predict the values of any new data points. This means that the new point is assigned a value based on how closely it resembles the points in the training set.</em></p><p><a href="https://www.analyticsvidhya.com/blog/2018/08/k-nearest-neighbor-introduction-regression-python/">K-Nearest Neighbors Algorithm | KNN Regression Python</a></p><p>code here,</p><pre>regressor = KNeighborsRegressor(n_neighbors=3)<br><br>forecaster = make_reduction(regressor, strategy=&quot;recursive&quot;, window_length= window_length)<br>forecaster.fit(y_train)<br>y_pred = forecaster.predict(fh)<br>plot_series(y_train, y_test, y_pred, labels=[&quot;y_train&quot;, &quot;y_test&quot;, &quot;y_pred&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCu_cJezGf9AJuOuxzRjOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*Fp_ZRItQB2XJ8ImkCbyNcA.png" /></figure><p>as above KNNRegressor can predict trend of up and down, but it had a gap between actual and predict value (as was my yellow color hand writing) formal reapresent by MAPE 0.8094. Howevey, it can capture trend line so I make it as <strong>candidate </strong>model</p><h4>LinearRegression</h4><p><em>Linear regression shows the linear relationship between the independent variable (X-axis) and the dependent variable (Y-axis), consequently</em></p><p><a href="https://www.analyticsvidhya.com/blog/2021/06/linear-regression-in-machine-learning/">Linear Regression Algorithm To Make Predictions Easily</a></p><p>code here,</p><pre>from sklearn.linear_model import LinearRegression<br>regressor = LinearRegression()<br><br>forecaster = make_reduction(regressor, strategy=&quot;recursive&quot;, window_length= window_length)<br>forecaster.fit(y_train)<br>y_pred = forecaster.predict(fh)<br>plot_series(y_train, y_test, y_pred, labels=[&quot;y_train&quot;, &quot;y_test&quot;, &quot;y_pred&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NY-6mWWtI6NLsX903Qs68g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Hfrgt6iXxp1X3mqAr5vHsQ.png" /></figure><p>as above Linear Regression predicted heavy up and down trend. It was the effect of noise data and MAPE was so bad at 1.87 (more explore can do by remove that noise and re-predict and see how does it can improve.)</p><h4>XgbRegressor</h4><p><a href="https://xgboost.ai/"><em>XGBoost</em></a><strong><em> </em></strong><em>is a decision-tree-based ensemble Machine Learning algorithm that uses a </em><a href="https://en.wikipedia.org/wiki/Gradient_boosting"><em>gradient boosting</em></a><em> framework. In prediction problems involving unstructured data (images, text, etc.) artificial neural networks tend to outperform all other algorithms or frameworks.</em></p><p><a href="https://towardsdatascience.com/https-medium-com-vishalmorde-xgboost-algorithm-long-she-may-rein-edd9f99be63d">XGBoost Algorithm: Long May She Reign!</a></p><p>code here,</p><pre>from xgboost import XGBRegressor<br>regressor = XGBRegressor(objective=&#39;reg:squarederror&#39;, random_state=42)<br><br>forecaster = make_reduction(regressor, strategy=&quot;recursive&quot;, window_length= window_length)<br>forecaster.fit(y=y_train)<br>y_pred = forecaster.predict(fh=fh)<br>plot_series(y_train, y_test, y_pred, labels=[&quot;y_train&quot;, &quot;y_test&quot;, &quot;y_pred&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAt6PY8sj3KBj8xGyGLXBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*YLPYXEloYRuWlKBC5VlMwg.png" /></figure><p>XgboostRegressor can predict up and down trend in a acceptable level, but almost same error as KNN (yellow gap) and MAPE at 0.96. However, it can predict so I pick it us as a <strong>candidate </strong>model to improve.</p><p>4 Time series <strong>cross-validation</strong>, to make more model robustness and well performance. we have to do cross-validation.</p><p><a href="https://towardsdatascience.com/dont-use-k-fold-validation-for-time-series-forecasting-30b724aaea64">Don’t Use K-fold Validation for Time Series Forecasting</a></p><p>first, We don’t use K-Fold as we familiar for Time series. (sequential data can’t shuffle or random) so cross-validation for Time series is special (temporal cross validation).</p><p><strong>SlidingWindowSplitter/ ExpandingWindowSplitter </strong>are two main of<strong> </strong>temporal cross validation.</p><p>In this artical, I used <strong>ExpandingWindowSplitter and pick up only 2 candidate model KNeighborsRegressor</strong> and <strong>XgbRegressor.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1WrNJ2tPgruGOR_JYwcpQ.png" /><figcaption>ExpandingWindowSplitter concept by author</figcaption></figure><p><strong>KNeighborsRegressor: ExpandingWindowSplitter</strong></p><pre>regressor = KNeighborsRegressor(n_neighbors=3)<br>forecaster = make_reduction(regressor, strategy=&quot;recursive&quot;, window_length= window_length)<br><br>cv = ExpandingWindowSplitter(step_length=12, fh=fh, initial_window=52)<br>results = evaluate(<br>    forecaster=forecaster, y=y, cv=cv, strategy=&quot;refit&quot;, return_data=True<br>)<br>results.iloc[:, :5].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*n45ppJgPe5D0t7klsn0EVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LI6AVJHx4OvSps4SHT7ArQ.png" /></figure><p>KNeighborsRegressor: ExpandingWindowSplitter prediction line trend was up and down trend, but in the last len MAPE was higher than previous. By eye we can see big gap as well.</p><p><strong>XgbRegressor: ExpandingWindowSplitter</strong></p><pre>regressor = XGBRegressor(objective=&#39;reg:squarederror&#39;, random_state=42)<br>forecaster = make_reduction(regressor, strategy=&quot;recursive&quot;, window_length= window_length)<br><br>cv = ExpandingWindowSplitter(step_length=12, fh=fh, initial_window=52)<br>results = evaluate(<br>    forecaster=forecaster, y=y, cv=cv, strategy=&quot;refit&quot;, return_data=True<br>)<br>results.iloc[:, :5].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*itfVKsjqPFVqCQcN1T1P0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*deaOomclNZJr0GUTfRh_5g.png" /></figure><p>as above XgbRegressor: ExpandingWindowSplitter<strong> </strong>prediction line trend was getting close to the train line compare with KNeighborsRegressor. By result summary table <strong><em>MAPE was getting better by len_train_window</em></strong><em>. &gt;&gt;&gt;&gt;&gt;&gt; Pick up XgbRegressor to fine-tune &gt;&gt;&gt;&gt;&gt;&gt;</em></p><p>5 <strong>XgbRegressor Fine- Tuning, </strong><a href="https://neptune.ai/blog/hyperparameter-tuning-in-python-complete-guide"><em>Hyperparameter tuning</em></a><em> is process of determining the right combination of hyperparameters that maximizes the model performance.</em></p><p><a href="https://towardsdatascience.com/xgboost-fine-tune-and-optimize-your-model-23d996fab663">XGBoost: A Complete Guide to Fine-Tune and Optimize your Model</a></p><p>code here,</p><pre>from sktime.forecasting.model_selection import (ForecastingGridSearchCV,<br>                                                SlidingWindowSplitter)<br><br>param_grid = {<br>    &#39;estimator__max_depth&#39;: [3, 6, 10, 15],<br>    &#39;estimator__learning_rate&#39;: [0.01, 0.1, 0.2, 0.3],<br>    &#39;estimator__colsample_bytree&#39;: np.arange(0.4, 1.0),<br>    &#39;estimator__n_estimators&#39;: [100, 500, 1000]<br>}<br><br>regressor = XGBRegressor(objective=&#39;reg:squarederror&#39;, random_state=42)<br>forecaster = make_reduction(regressor, strategy=&quot;recursive&quot;)<br><br>cv = ExpandingWindowSplitter(step_length=12, fh=fh, initial_window=52)<br>gscv = ForecastingGridSearchCV(<br>    forecaster, cv=cv, param_grid=param_grid, strategy=&quot;refit&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*BbT9ucMIbOYYh5uOumHXew.png" /></figure><p>MAPE was better from begining (single model) at 0.9653, ExpandingWindowSplitter (Validation) last len at 0.5319 and last perfomance (Hyperparameter tuning) was 0.5114. <strong><em>Hyperparameter tuning can improve 47% improve from single model and 4% from Validation</em></strong><em>.</em></p><h4>Conclusion</h4><ul><li>We explored 4 models to predict 12 weeks ahead</li><li>KNeighborsRegressor and XgbRegressor were 2 candiate models to make more model robustness</li><li>final XgbRegressor with Hyperparameter tuning</li></ul><p>Future work we can re-work on Xgboost with <strong><em>noise removing or add more train data or add more feature untill feature engineering on date term to generate more interesting feature.</em></strong></p><blockquote>Thank for your reading till the end, I’m not expert person in any time series or sktime world, I just one who need to learn and explore to practice myself by doing and note it, I will be appreciate on any advise from some expert on some point I was wrong and other additional commemt.</blockquote><p>you can take full code on my github here <a href="https://github.com/MossMojito/sktime_Xgboost/blob/main/sktime_xgboost.ipynb">https://github.com/MossMojito/sktime_Xgboost/blob/main/sktime_xgboost.ipynb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a5525d902ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xgboost time series forcasting with sktime [ep#1]]]></title>
            <link>https://mpatiparn-n.medium.com/xgboost-time-series-forcasting-with-sktime-ep-1-ee8ab8aa933a?source=rss-197add41248f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8ab8aa933a</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[sales-forecasting]]></category>
            <category><![CDATA[sktime]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Patiparn Nualchan]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 13:08:12 GMT</pubDate>
            <atom:updated>2022-12-25T13:08:12.974Z</atom:updated>
            <content:encoded><![CDATA[<p>sktime introduction and explore sequential data to get ready for modeling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKWNyyotALFd-yLksIoKaQ.jpeg" /><figcaption>photo modify by Author on <a href="https://www.indeed.com/career-advice/career-development/types-of-graphs-and-charts">https://www.indeed.com/career-advice/career-development/types-of-graphs-and-charts</a> and Juan Moyano/Stocksy photo</figcaption></figure><p>Hello, welcome to my note about time series ML experiment on sales forecasting project. I implement to my real job to forecast next a few week sales ahead. In this artical we will talk about</p><h4>1. Time series data (rough concept to deal with <strong>one single — sales data</strong>)</h4><h4>2. Time series analysis (<strong>EDA</strong> and S<strong>tationary testing</strong>)</h4><p>3. Time series forecasting (modeling and prediction)</p><p>4. Time series cross validation (temporal cross validation)</p><p>5. fine-tune xgboost (get best parameter)</p><p><strong>Lets’get it started !!!</strong> In genaral we familiar with data as Tabular(DataFrame) with n features X1, X2, X3,…Xn and label Y(target).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Vyint4C3fg8Zl-LcwNThA.png" /><figcaption>supervised learning overview by <a href="https://www.tibco.com/reference-center/what-is-supervised-learning">https://www.tibco.com/reference-center/what-is-supervised-learning</a></figcaption></figure><p>We split data(X_train, X_test, y_train, y_test). Use train data to build model-&gt; fit(X_train<strong>,</strong> so let’s talk about it!</p><p>1Time series <strong>one single — sales data (univariate): </strong>As below, it doesn’t have any feature. It just one single column of sequential data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*oeD4cAIkztIWrG4NJfYEHw.png" /></figure><p>what we have to do is to <strong>tranform time sequence for supervised task</strong>. we can also define function by hand with below code, but we don’t. We use sktime!</p><pre>def series_to_supervised(data, n_in=1, n_out=1):<br>    df = DataFrame(data)      <br>    cols = list()      <br>    # input sequence (t-n, ... t-1)      <br>    for i in range(n_in, 0, -1):      <br>        cols.append(df.shift(i))      <br>    # forecast sequence (t, t+1, ... t+n)      <br>    for i in range(0, n_out):      <br>        cols.append(df.shift(-i))      <br>    # put it all together      <br>    agg = concat(cols, axis=1)      <br>    # drop rows with NaN values      <br>    agg.dropna(inplace=True)      <br>    return agg.values      <br>      <br>data = series_to_supervised(train, n_in=n_input)      <br> train_x, train_y = data[:, :-1], data[:, -1]</pre><p>First of all, most of information of this article was from a good medium article about time series with sktime as show below.</p><p><a href="https://towardsdatascience.com/build-complex-time-series-regression-pipelines-with-sktime-910bc25c96b6">Build Complex Time Series Regression Pipelines with sktime</a></p><p>I learned, explored and made the story talking up in my taste, Thanks it for reference and hope you/reader also enjoy with my taste</p><h4><a href="https://www.sktime.org/en/stable/"><strong>sktime package</strong></a><strong> : </strong><em>framework for a wide range of time series machine learning tasks.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*LOVOBqQs6KvMxo5rmd3d_w.png" /></figure><p><strong>sktime</strong> have many fucntion to make time series more convenience. We start with <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.compose.make_reduction.html"><strong>make_reduction</strong></a><strong> </strong>function: <em>tranform single data to lag of data as feature X . for example Y = 5 was from =2, 3 and 4 sequentially by lag_1, lag_2 and lag_3.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*tfL4mXzC0d0TakmhviIn9g.png" /><figcaption>image by <a href="https://medium.com/@rtkilian?source=user_profile-------------------------------------"><strong>Rhys Kilian</strong></a><strong> </strong>from<strong> </strong>Build Complex Time Series Regression Pipelines with sktime artical</figcaption></figure><p>Before make_reduction we can’t skip split data.<em> </em>We work make_reduction on Train data. the split data function call <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.model_selection.temporal_train_test_split.html?highlight=temporal_train_test_split"><strong>temporal_train_test_split</strong></a><strong>: </strong><em>split data by sequential</em> <em>(last 4 week, last 3 month, last 6 month,..blah blah blah).</em> The difference from our general train_test_split is shuffling. base on sequential data, time series can’t split with shuffling or randomly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*GNKzcblwpwTBHOuSp8iM8A.png" /><figcaption>image by <a href="https://www.researchgate.net/profile/Marcello-La-Rosa-2"><strong>Marcello La Rosa</strong></a> on <a href="https://www.researchgate.net/publication/334581217_Survey_and_Cross-benchmark_Comparison_of_Remaining_Time_Prediction_Methods_in_Business_Process_Monitoring">Survey and Cross-benchmark Comparison of Remaining Time Prediction Methods in Business Process Monitoring</a></figcaption></figure><p>one another important function is <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.forecasting.base.ForecastingHorizon.html?highlight=ForecastingHorizon"><strong>ForecastingHorizon</strong></a><strong>:</strong><em> array of relative or absolute values are specific data points for which we want to generate forecasts.</em></p><pre>test_size = 12<br>window_length = 52<br><br>y= df.squeeze()<br><br>y_train, y_test = temporal_train_test_split(y, test_size= test_size)<br>fh = ForecastingHorizon(y_test.index, is_relative = False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*FxY1dr4BnGIOEoQaF-5sRA.png" /></figure><p>With those 3 functions, now we get ready to create model, but we still don’t. Because we have to do one of important step to make more understanding and familiar with the data. That’s EDA &gt;&gt;&gt; let’s go!!</p><p>2 Time series analysis (<strong>EDA</strong> and <strong>stationary testing</strong>). Step back before split any data, we shouldn’t skip EDA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*oeD4cAIkztIWrG4NJfYEHw.png" /><figcaption>image by author</figcaption></figure><p>Data have 2 columns, “date” and “milk” (sales of milk chocolate). The data was time sequential record in a day. I explored the data as 3 level</p><ul><li><strong>resamples by day (‘D’)</strong> &gt;&gt;&gt; to make sum of sales by day</li><li>add[‘year’], [‘month’] and [‘week_of_year’] feature &gt;&gt;&gt; for more explore</li><li>Visualize whole year sales &gt;&gt;&gt; <strong><em>overview sales by day in a year</em></strong>.</li></ul><pre>df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;])<br>df.set_index(&#39;date&#39;, inplace= True)<br><br>df_day = df.resample(&#39;D&#39;).sum()<br>df_day = df_day.reset_index(drop=False)<br><br>df_day[&#39;year&#39;] = df_day[&#39;date&#39;].dt.year<br>df_day[&#39;month&#39;] = df_day[&#39;date&#39;].dt.month<br>df_day[&#39;week_of_year&#39;] = df_day[&#39;date&#39;].dt.week</pre><pre>df_day_y21 = df_day[(df_day[&#39;year&#39;]==2021)]<br><br>df_day_y21.set_index(&#39;date&#39;, inplace= True)<br>calplot.calplot(df_day_y21[&#39;milk&#39;],edgecolor= None, cmap= &#39;afmhot_r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrMnnJFHxyB99KsC9C-10w.png" /></figure><pre>df_day_y22 = df_day[(df_day[&#39;year&#39;]==2022)]<br><br>df_day_y22.set_index(&#39;date&#39;, inplace= True)<br>calplot.calplot(df_day_y22[&#39;milk&#39;],edgecolor= None, cmap= &#39;afmhot_r&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*21bV3D2s11UkIsEicypACA.png" /></figure><p>As above both of Y21 and Y22, sales was active around three preiod a year. First active was in Feb, second was quite ambiguous in May(Jun) till Aug and last active was in Nov till Dec. Next explore is monthly</p><ul><li><strong>resamples by month(‘M’)</strong> &gt;&gt;&gt; to make sum of sales by month</li><li>also add[‘year’], [‘month’] and [‘week_of_year’] feature</li><li>Visualize whole year sales &gt;&gt;&gt; <strong><em>compare sales of Y21 and Y22</em></strong>.</li></ul><pre>df_month = df.resample(&#39;M&#39;).sum()<br>df_month = df_month.reset_index(drop=False)<br><br>df_month[&#39;year&#39;] = df_month[&#39;date&#39;].dt.year<br>df_month[&#39;month&#39;] = df_month[&#39;date&#39;].dt.month<br>df_month[&#39;week_of_year&#39;] = df_month[&#39;date&#39;].dt.week</pre><pre>eda_df = df_month.pivot(index=&#39;month&#39;, columns=&#39;year&#39;, values=&#39;milk&#39;)<br>eda_df.plot(kind=&#39;line&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*-c7oqkmYZk51vS0hnsp2ug.png" /></figure><pre>eda_df.plot(kind=&#39;bar&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*xP-0SZ7hK3UqD5ytIahDFg.png" /></figure><p>As above, trend line was not big difference. it was quite stable at around 4500–5000 units. I assume abnormal sales was happen in OCT’21. Last explore is weekly.</p><ul><li><strong>resamples by week(‘W’)</strong> &gt;&gt;&gt; to make sum of sales by week</li><li>also add[‘year’], [‘month’] and [‘week_of_year’] feature</li><li>Visualize whole year sales &gt;&gt;&gt; <strong><em>continuously of sales by week</em></strong>.</li></ul><pre>df_week = df.resample(&#39;W&#39;).sum()<br>df_week = df_week.reset_index(drop=False)<br><br>df_week[&#39;year&#39;] = df_week[&#39;date&#39;].dt.year<br>df_week[&#39;month&#39;] = df_week[&#39;date&#39;].dt.month<br>df_week[&#39;week_of_year&#39;] = df_week[&#39;date&#39;].dt.week<br><br>df_week.set_index(&#39;date&#39;, inplace= True)</pre><pre>Cmilk_df = df_week[[&#39;milk&#39;]]<br><br>Cmilk_df.plot(figsize= (10,3))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4yS8T-gZekgRREmrdZd9Q.png" /></figure><p>As above we can see two year sales continuously was quite stable at around 1000–1500 units a week. by line plot we can rough inspect this data is <strong>stationary. </strong>but to make it as a formal summary we step next to test stationary by <a href="https://www.machinelearningplus.com/time-series/augmented-dickey-fuller-test/"><strong>ADF-test</strong></a></p><p><a href="https://medium.com/@cmukesh8688/why-is-augmented-dickey-fuller-test-adf-test-so-important-in-time-series-analysis-6fc97c6be2f0">Why is Augmented Dickey–Fuller test (ADF Test) so important in Time Series Analysis</a></p><p>code here,</p><pre>from statsmodels.tsa.stattools import adfuller<br><br>result = adfuller(Cmilk_df.values.flatten())<br><br>print(&#39;ADF Statistic: %f&#39; % result[0])<br>print(&#39;p-value: %f&#39; % result[1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*bRvsWtOOPNm7F91HjxcdNw.png" /></figure><p>The p-value was very less than the significance level of 0.05 and hence we can reject the null hypothesis and take that <strong>the series is stationary.</strong></p><p>The test result will make our model no need to add more additional term to fix non-stationary such as <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.transformations.series.detrend.Deseasonalizer.html?highlight=deseasonalizer"><em>Deseasonalizer</em></a> and <a href="https://www.sktime.org/en/stable/api_reference/auto_generated/sktime.transformations.series.detrend.Detrender.html"><em>Detrender</em></a><em> </em>that includes in sktime.</p><h4>ep#1 conclusion</h4><p>Since we start till this step, we deal with one-single data. Transform and ready for supervise task. Explored and understood the data character by 3 levels of EDA (day, month and week level) and also test stationary (by ADF-test).</p><p>Therefore we are ready to bomb many models and see how does it each model predict our next sales. I will pick up one of good model to make it robust and learn more to fine-tune.</p><p>&gt;&gt;&gt;&gt;&gt; lets go to ep#2. <em>(complete notebook code as in ep#2 ) &gt;&gt;&gt;&gt;&gt;&gt; Thx.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8ab8aa933a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Game of Thrones เล่าความสัมพันธ์ตัวละคร ผ่าน Social Network Analysis]]></title>
            <link>https://mpatiparn-n.medium.com/game-of-thrones-%E0%B9%80%E0%B8%A5%E0%B9%88%E0%B8%B2%E0%B8%84%E0%B8%A7%E0%B8%B2%E0%B8%A1%E0%B8%AA%E0%B8%B1%E0%B8%A1%E0%B8%9E%E0%B8%B1%E0%B8%99%E0%B8%98%E0%B9%8C%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B8%A5%E0%B8%B0%E0%B8%84%E0%B8%A3-%E0%B8%9C%E0%B9%88%E0%B8%B2%E0%B8%99-social-network-analysis-2698a489e402?source=rss-197add41248f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2698a489e402</guid>
            <category><![CDATA[network-analysis]]></category>
            <category><![CDATA[game-of-thrones]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[centrality]]></category>
            <category><![CDATA[graph-theory]]></category>
            <dc:creator><![CDATA[Patiparn Nualchan]]></dc:creator>
            <pubDate>Wed, 09 Jun 2021 08:35:31 GMT</pubDate>
            <atom:updated>2021-06-09T08:35:31.451Z</atom:updated>
            <content:encoded><![CDATA[<p>เมื่อไม่กี่สัปดาห์มานี้ ผมได้ดูตัวอย่าง <strong>Eternals</strong> ภาพยนต์เรื่องล่าสุดจาก <strong>Marvel studios</strong> และปลื้มใจกับการได้เห็น 2 นักแสดงที่รับบท <strong>Jon Snow</strong> และ <strong>Robb Stark</strong> จากซีรี่ย์ <strong>Game of Thrones </strong>อยู่ในจอด้วยกันอีกครั้ง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5V9KU-UiaqWvzpqtYASceg.jpeg" /><figcaption>ภาพจาก <a href="https://twitter.com/MCU_Direct/status/1169644273777741824/photo/1">https://twitter.com/MCU_Direct/status/1169644273777741824/photo/1</a></figcaption></figure><p>ด้วยความคิดถึง และ ลืมไปแล้วว่า ตัวละครมากมายใน <strong>Game of Thrones </strong>นั้นมีใคร มาจาก<strong>House</strong> ไหน และเชื่อมโยงกันยังไง วันนี้ผมในฐานะแฟนซีรี่ย์ที่คิดถึง จะพาย้อนกลับไปทบทวนความจำ ดูความสัมพันธ์ของตัวละครจาก <strong>House</strong>ต่างๆ ให้หายคิดถึง ในวิถี<strong>Data</strong> ผ่าน <a href="https://en.wikipedia.org/wiki/Social_network_analysis"><strong>Social Network Analysis</strong> (การวิเคราะห์เครือข่ายทางสังคม)</a></p><figure><img alt="ภาพจาก" src="https://cdn-images-1.medium.com/max/925/1*sVV6RoZsGaeT4FhTPppzhA.jpeg" /><figcaption>ภาพจาก <a href="https://magdatabac.com/pcm-personality-types-game-of-thrones/">https://magdatabac.com/pcm-personality-types-game-of-thrones/</a></figcaption></figure><p>เนื้อหาในวันนี้ ผมนำมาจากบทความที่น่าสนใจมากๆบทความนึง ใครที่สนใจอยากอ่านตัวเต็ม สามารถเข้าตามลิ้งด้านล่างนี้ได้เลย <a href="https://shiring.github.io/networks/2017/05/15/got_final">https://shiring.github.io/networks/2017/05/15/got_final</a></p><p>ก่อนจะเริ่ม ผมขอพาทุกคนทำความรู้จักกับ <strong>Social Network Analysis(SNA)</strong> ก่อน พูดง่ายๆ <strong>SNA</strong> ก็คือการวิเคราะห์หาความสัมพันธ์ ความเชื่อมโยงกันของสมาชิกในเครือข่าย(<strong>Network</strong>) เห็นภาพง่ายที่สุดคือความเชื่อมโยงของเรากับเพื่อนใน <strong>Facebook</strong> ที่สามารถบอกได้เบื้องต้นว่าเรามีเพื่อนที่เชื่อมโยงกับเราอยู่ในระดับไหน ใครเป็นเพื่อนที่เรามีความสัมพันธ์มากที่สุด และอื่นๆอีกมากมายที่จะค่อยๆเล่าให้ฟัง</p><p>ในทางการประยุกต์ใช้งาน <strong>SNA</strong> สามารถนำไปประยุกต์ใช้หาความสัมพันธ์ ความเชื่อมโยงของเครือข่าย ได้หลากหลาย เช่น ความเชื่อมโยงของลูกค้าธนาคารที่ทำธุรกรรมทางการเงิน เป็นต้น</p><p>ในทางการประยุกต์ใช้งาน <strong>SNA</strong> สามารถนำไปประยุกต์ใช้หาความสัมพันธ์ ความเชื่อมโยงของเครือข่าย ได้หลากหลาย เช่น ความเชื่อมโยงของลูกค้าธนาคารที่ทำธุรกรรมทางการเงิน เป็นต้น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Dkk5t6kWxO5I3EH7hOIKvQ.jpeg" /></figure><p><strong>Social Network Analysis(SNA) </strong>นั้นมองความสัมพันธ์ของเครือข่ายในหลายมิติ โดยรวมสรุปให้เข้าใจง่ายๆ 3 มุมมอง</p><ol><li>มุมมองสมาชิก( <strong>Node</strong>)</li><li>มุมมองเส้นความสัมพันธ์ (<strong>Edge</strong>)</li><li>มุมมอง<strong>Network</strong> โดยรวม</li></ol><p>มาถึงจุดนี้ก็น่าจะพอเห็นภาพของเนื้อหาในวันนี้ เพื่อไม่ให้เสียเวลา เรามาเข้าเรื่องกันดีเลยกว่า โดยในทางการวิเคราะห์จะใช้ภาษา <strong>R</strong> แต่ผมจะไม่ขอยก <strong>code</strong> มา แต่จะเป็นการยก <strong>Result</strong> มาอธิบาย เพื่อไม่ให้ยากในความเข้าใจเกินไป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*S_TD8sRFqdktXAnaOCYWlg.png" /></figure><p>เรามาทำความรู้จักกับ <strong>Dataset</strong> กันก่อน <strong>Dataset</strong> ที่ใช้เป็น มาจาก <strong>Kaggle Dataset</strong> <a href="https://www.kaggle.com/mylesoneill/game-of-thrones">https://www.kaggle.com/mylesoneill/game-of-thrones</a> โดยมี <strong>source</strong> และ <strong>target</strong> เป็น ชื่อตัวละคร หรือ <strong>Nodes</strong> ความเชื่อมโยงจาก <strong>source</strong> ไป <strong>target</strong> นั้นคือ <strong>Edges</strong> โดยมี <strong>type</strong> เป็นตัวกำกับรูปแบบความสัมพันธ์ ในที่นี้ ความสัมพันธ์นั้นคือ ความเป็นสมาชิกใน <strong>House</strong> ของตัวละคร (<strong>Node</strong>)</p><pre>head(union_edges)</pre><pre>##               source            target   type   color   lty<br>## 1         Lysa Arryn      Robert Arryn mother #7570B3 solid<br>## 2       Jasper Arryn        Alys Arryn father #1B9E77 solid<br>## 3       Jasper Arryn         Jon Arryn father #1B9E77 solid<br>## 4          Jon Arryn      Robert Arryn father #1B9E77 solid<br>## 110 Cersei Lannister  Tommen Baratheon mother #7570B3 solid<br>## 210 Cersei Lannister Joffrey Baratheon mother #7570B3 solid</pre><p>และมีข้อมูลอีกชุดหนึ่ง เกี่ยวกับ <strong>Characters</strong> ของตัวละคร รวมถึงข้อมูล <strong>House</strong></p><pre>head(union_characters)<br>##            name male culture          house popularity      house2   color  shape<br>## 1    Alys Arryn    0    &lt;NA&gt;    House Arryn 0.08026756        &lt;NA&gt;    &lt;NA&gt; circle<br>## 2 Elys Waynwood    0    &lt;NA&gt; House Waynwood 0.07023411        &lt;NA&gt;    &lt;NA&gt; circle<br>## 3  Jasper Arryn    1    &lt;NA&gt;    House Arryn 0.04347826        &lt;NA&gt;    &lt;NA&gt; square<br>## 4   Jeyne Royce    0    &lt;NA&gt;    House Royce 0.00000000        &lt;NA&gt;    &lt;NA&gt; circle<br>## 5     Jon Arryn    1 Valemen    House Arryn 0.83612040        &lt;NA&gt;    &lt;NA&gt; square<br>## 6    Lysa Arryn    0    &lt;NA&gt;    House Tully 0.00000000 House Tully #F781BF circle<br></pre><p>เริ่ม <strong>plot </strong>กราฟแรกด้วยภาพรวมของตัวละครทั้งหมดจาก <strong>9 House </strong>หลัก โดยสีของแต่ละ <strong>Node </strong>จะบอกถึง <strong>House </strong>รูปร่างจะบอกถึงเพศ (สี่เหลี่ยม= เพศชาย ส่วนวงกลม= เพศหญิง), ขนาดของ <strong>Node </strong>บอกถึงความ <strong>Popular </strong>ของตัวละคร โดย <strong>Dataset </strong>มีค่า <strong>populality score </strong>ระบุอยู่ ในส่วนของ <strong>Edge </strong>ก็มีการแบ่งสีระบุความหมายกำกับไว้เช่นกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lpxwxj8Tglnw57txpKGwig.png" /></figure><p>จากกราฟจะเห็น<strong> Network</strong> ของตัวละครจาก <strong>House</strong> หลักทั้ง<strong>9</strong> ที่ใหญ่พอสมควร มีการแบ่งสีและรูปร่างเพื่อให้ง่ายต่อการทำความเข้าใจจากที่กล่าวไปก่อนหน้า แต่จากกราฟตอนนี้ ยังไม่สามารถที่จะบอกหรือสรุปอะไรได้มากนัก และในแง่ของการมองภาพรวม ถือเป็นภาพรวม <strong>Netwotk</strong> ที่ดีและทำความเข้าใจได้ไม่ยาก</p><p>สิ่งน่าสนใจคือ <strong>House Greyjoy</strong> ไม่มีความสัมพันธ์ทางครอบครัวกับ <strong>House</strong> ใดๆเลย</p><h3><strong>Network Analysis</strong></h3><p>จากความยุ่งเหยิงของกราฟด้านบน เรามาลุยหาคำตอบ ด้วยคำถามเบสิคที่สุดก็คือ <strong><em>Who is the most important characters are in this network? </em></strong>การหาความสำคัญในลักษณะนี้ เราใช้ทฤษฎีของกราฟ หาคำตอบได้โดยการมองมุมมองของ<strong>Node</strong> ว่า <strong>Node</strong> มีความเป็นศูนย์กลางของ <strong>Network</strong> มากแค่ไหน เรียกว่า การวัด <a href="https://bookdown.org/markhoff/social_network_analysis/centrality.html"><strong>Centrality</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*haEQF29HdDGZi27f3pST1w.png" /><figcaption>ภาพจาก <a href="https://combattb.org/combat-tb-neodb/graph-algorithms/">https://combattb.org/combat-tb-neodb/graph-algorithms/</a></figcaption></figure><p><strong>Centrality</strong> วัดได้หลายวิธี สรุปคร่าวๆ ดังนี้</p><ul><li><strong>Node Degree</strong> เป็นมิติวัดที่มองได้ง่ายที่สุด คือการมองว่ามีกี่<strong>Node</strong> ที่เชื่อมต่อกับ <strong>Node </strong>นั้นๆ</li><li><strong>Closeness</strong> การวัดในแง่ความไวในการส่งข้อมูลจาก<strong>Node</strong> สู่<strong>Node</strong> หรือเครือข่ายย่อย หรือทั่วเครือข่าย</li><li><strong>Betweenness</strong> พิจารณา <strong>Node</strong> ที่เชื่อมโยงกับ <strong>Node</strong> อื่นๆในลักษณะคล้ายสะพานเชื่อม(<strong>Bridge</strong>) เรียกได้ว่าจุดเชื่อมต่อที่สำคัญ ซึ่งมีความสำคัญกับเครือข่ายเนื่องจาก หาก<strong>Node</strong> นี้ถูกตัดการเชื่อมต่อออกไป ก็เหมือนสะพานขาด การส่งต่อข้อมูลจะเกิดปัญหาทันที</li><li><strong>Eigenvector </strong>มองความเป็น “<strong>Hub</strong>” ของ <strong>Node</strong> โดยแปลง <strong>Node</strong> เป็น <strong>Matrix</strong> และคำนวนค่า <a href="https://www.mathsisfun.com/algebra/eigenvalue.html"><strong>Eiganvactor</strong></a> ค่าที่มากจะบอกความเป็นศูนย์กลางของ <strong>Node</strong> นั้นกับ <strong>Node</strong> แวดล้อม แต่ วิถีการนี้มีอาจมี <strong>bias </strong>ซ่อนอยู่ ซึ่งเป็นที่มาของ วิธีถัดไป</li><li><strong>PageRank </strong>ให้ความสำคัญกับทิศทางการเชื่อมต่อไปหา <strong>Node</strong> ด้วย เช่น หากทิศทางการเชื่อมต่อมีการ link จากหลายๆ <strong>Node</strong> มาหา <strong>Node</strong> นั้นเยอะๆ มองได้ว่า <strong>Node</strong> นั้นๆ มีความสำคัญมาก</li></ul><p>หมดช่วงทฤษฎีแบบรวบรัว กลับมาเข้าเรื่อง <strong>Game of Thrones</strong> กันต่อดีกว่า จากเนื้อหาที่ได้กล่าวไป <strong>Centrality </strong>นำมาวิเคราะห์ความสัมพันธ์ตัวละคร และบ้านได ้และให้ผลที่น่าสนใจออกมาดังนี้</p><p><strong>Node Degree: Quellon Greyjoy</strong> ด้วยความที่มีภรรยาถึง <strong>3</strong> คน และภรรยาทั้ง <strong>3</strong> ก็มีลูกมากมาย ทำให้มีจำนวน <strong>Node</strong> หรือ ตัวละครที่เกี่ยวข้องมากที่สุดถึง <strong>12</strong> <strong>Node</strong> ด้วยกัน สำหรับแฟนซีรี่ย์อาจจะ ไม่คุ้นชื่อนี้เท่าไหร่ เนื่องจากเป็นตัวละครที่ไม่ถูกหยิบยกไปเล่าให้ซีรี่ย์</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*FQq1Bo20e7tv7Q5i1LuUiQ.jpeg" /></figure><pre>##            rowname degree degree_std<br>## 1  Quellon Greyjoy     12 0.05797101<br>## 2      Walder Frey     10 0.04830918<br>## 3   Oberyn Martell     10 0.04830918<br>## 4     Eddard Stark      9 0.04347826<br>## 5    Catelyn Stark      8 0.03864734<br>## 6       Emmon Frey      7 0.03381643<br>## 7  Genna Lannister      7 0.03381643<br>## 8     Merrett Frey      7 0.03381643<br>## 9    Balon Greyjoy      7 0.03381643<br>## 10 Jason Lannister      7 0.03381643</pre><p>ข้อมูลน่าสนใจ <strong>House Stark (Eddard Stark)</strong> ที่พวกเราคุ้นเคย ติดเป็นลำดับที่ <strong>4</strong></p><p><strong>Closeness: Sansa Stark</strong> ลูกสาวคนโตของตระกูล <strong>Stark </strong>มีค่า <strong>Closeness </strong>มากที่สุด และไม่ได้ห่างจากอันดับถัดไปอย่าง<strong> Tyrion Lannister </strong>มากนัก การแต่งงานกันของทั้งคู่เหมือนเป็นการเชื่อมโยง <strong>2 House</strong> ใหญ่สำคัญอย่าง <strong>Stark</strong> และ <strong>Lannister</strong> เข้าด้วยกัน ส่งผลให้ทั้งคู่ถือได้ว่าเป็น<strong>2</strong> ตัวละครที่มีอิทธิพลต่อเชื่อมโยงกันของเครือข่ายมาก</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*aTJcpP-d1vd1D28DaIAOoA.jpeg" /><figcaption>ภาพจาก <a href="https://www.quora.com/How-many-times-has-Sansa-Stark-been-married-in-GOT">https://www.quora.com/How-many-times-has-Sansa-Stark-been-married-in-GOT</a></figcaption></figure><pre>##             rowname    closeness closeness_std<br>## 1       Sansa Stark 0.0002013288  9.726028e-07<br>## 2  Tyrion Lannister 0.0002012882  9.724070e-07<br>## 3   Tywin Lannister 0.0002011668  9.718201e-07<br>## 4  Joanna Lannister 0.0002005616  9.688965e-07<br>## 5      Eddard Stark 0.0002002804  9.675381e-07<br>## 6     Catelyn Stark 0.0001986492  9.596579e-07<br>## 7  Cersei Lannister 0.0001984915  9.588960e-07<br>## 8   Jaime Lannister 0.0001975894  9.545382e-07<br>## 9    Jeyne Marbrand 0.0001966568  9.500330e-07<br>## 10  Tytos Lannister 0.0001966568  9.500330e-07</pre><p><strong>Betweenness: Eddard Stark</strong> มีค่าสูงที่สุด เนื่องจาก เรื่องราวต่างๆนั้นเกิดขึ้นกับ <strong>House Stark</strong> โดยเฉพาะ <strong>Sansa</strong> ที่แต่งงานกับ <strong>Tyrion</strong> แห่ง <strong>House Lannister</strong> ซึ่งทำให้ <strong>Edge betweenness</strong> ของ <strong>Sansa</strong> และ <strong>Tyrion</strong> สูงที่สุด จะสังเกตุเห็นได้ง่ายๆในกราฟด้านล่าง จากขนาดของ <strong>Edge</strong> ที่เป็น <strong>path</strong> ที่หนาที่สุด</p><pre>##              rowname betweenness betweenness_std<br>## 1       Eddard Stark    6926.864       0.3248846<br>## 2        Sansa Stark    6165.667       0.2891828<br>## 3   Tyrion Lannister    5617.482       0.2634718<br>## 4    Tywin Lannister    5070.395       0.2378123<br>## 5   Joanna Lannister    4737.524       0.2221999<br>## 6  Rhaegar Targaryen    4301.583       0.2017533<br>## 7    Margaery Tyrell    4016.417       0.1883784<br>## 8           Jon Snow    3558.884       0.1669192<br>## 9        Mace Tyrell    3392.500       0.1591154<br>## 10   Jason Lannister    3068.500       0.1439191</pre><pre>#    rowname                              edge betweenness<br>## 1      160      Sansa Stark|Tyrion Lannister    5604.149<br>## 2      207          Sansa Stark|Eddard Stark    4709.852<br>## 3      212        Rhaegar Targaryen|Jon Snow    3560.083<br>## 4      296       Margaery Tyrell|Mace Tyrell    3465.000<br>## 5      213             Eddard Stark|Jon Snow    3163.048<br>## 6      131  Jason Lannister|Joanna Lannister    3089.500<br>## 7      159 Joanna Lannister|Tyrion Lannister    2983.591<br>## 8      171  Tyrion Lannister|Tywin Lannister    2647.224<br>## 9      192    Elia Martell|Rhaegar Targaryen    2580.000<br>## 10     300         Luthor Tyrell|Mace Tyrell    2565.000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gAuF5q6YicTEV273xmFdQ.png" /></figure><p>เมื่อมี <strong>Shortest path</strong> ก็ต้องมี <strong>Longest path</strong> เรามาลองดูมิติของ<strong>Longest path</strong> หรือเส้นเชื่อมโยงความสัมพันธ์ที่ยาวที่สุดกันบ้าง ตามกราฟล่าง จะเห็นว่า <strong>Longest path</strong> นั้นผ่าน <strong>Node</strong> หรือ ตัวละครทั้งหมด <strong>22 Node</strong> ด้วยกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5b3LP4JGiOVNX4Ls-15KsA.png" /></figure><p>สื่งที่น่าสนใจก็คือ เส้นทางนี้ ผ่านทั้ง <strong>Sansa Stark</strong> และ <strong>Tyrion Lannister</strong> รวมไปถึง <strong>Eddard Stark</strong> ซึ่งมีค่า <strong>Betweeness </strong>สูงที่สุด ตอกย้ำถึงความสำคัญของ <strong>3</strong> ตัวละครหลักนี้ได้เป็นอย่างดี</p><p><strong>Eigenvector : Tywin Lannister</strong> จอมบงการแห่ง <strong>House Lannister</strong> ตัวละครที่แฟนซีรี่ย์หลายคน ไม่ค่อยชอบเท่าไหร่นัก และจากการที่เขาเป็นตัวละครหลักของ <strong>House Lannister</strong> ส่งผลให้ค่า <a href="https://www.geeksforgeeks.org/eigenvector-centrality-centrality-measure/"><strong>Eigenvecter Centrality</strong></a> มีค่าสูงที่สุด รวมไปถึง <strong>Lannister</strong> คนอื่นๆด้วยที่มีค่าสูงไล่ๆกันมาเช่นกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8T-0vdEzD8vlYU9qS3xTlg.jpeg" /><figcaption>ภาพจาก <a href="https://screenrant.com/game-thrones-rules-lannister-family-follow/">https://screenrant.com/game-thrones-rules-lannister-family-follow/</a></figcaption></figure><pre>##                name eigen_centrality<br>## 1   Tywin Lannister        1.0000000<br>## 2  Cersei Lannister        0.9168980<br>## 3  Joanna Lannister        0.8358122<br>## 4    Jeyne Marbrand        0.8190076<br>## 5   Tytos Lannister        0.8190076<br>## 6   Genna Lannister        0.7788376<br>## 7   Jaime Lannister        0.7642870<br>## 8  Robert Baratheon        0.7087042<br>## 9        Emmon Frey        0.6538709<br>## 10      Walder Frey        0.6516021</pre><p>PageRank: <strong>Oberyn Martell, Quellon Greyjoy </strong>และ <strong>Walder Frey</strong> มีค่า<strong>PageRank</strong> มากที่สุด <strong>3</strong> อันดับแรก เนื่องจากทั้ง <strong>3</strong> ตัวละครนี้ มีคู่สมสรมากกว่า <strong>1</strong> รวมถึงลูกหลานที่เยอะ <em>(ในกรณีนี้การใช้ </em><strong><em>PageRank</em></strong><em> อาจจะไม่สะท้อนความเป็น </em><strong><em>Centrality</em></strong><em> ที่ดีเท่าไหร่ เนื่องจาก เราไม่สามารถมองแค่ว่าการมีคู่สมรสเยอะ จะทำให้ตัวละครนั้นมีความสำคัญมาก </em><strong><em>PakeRank</em></strong><em> จึงเหมาะกับการใช้งานเกี่ยวกับ </em><strong><em>Website </em></strong><em>ที่มองว่าการมีเส้นเชื่อมเข้ามาหา </em><strong><em>Website</em></strong><em> นั้นมาก ถือว่า </em><strong><em>Website</em></strong><em> นั้นมีน้ำหนักความสำคัญมาก ซึ่งจริงๆแล้วนั้นคือที่มาของ </em><strong><em>PageRank</em></strong><em> นั้นเอง เนื่องจาก </em><strong><em>PageRank</em></strong><em> ถูกพัฒนาจาก </em><strong><em>Google</em></strong><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*IM-HNPJPCRmGFFnjTCbmiA.jpeg" /><figcaption>ภาพจาก <a href="https://id.pinterest.com/YoanTriset/oberyn-martell/">https://id.pinterest.com/YoanTriset/oberyn-martell/</a> และ <a href="https://www.theverge.com/2016/6/21/11987496/game-of-thrones-season-six-finale-red-wedding-walder-frey-lady-stoneheart">https://www.theverge.com/2016/6/21/11987496/game-of-thrones-season-six-finale-red-wedding-walder-frey-lady-stoneheart</a></figcaption></figure><pre>##                 name   page_rank<br>## 1     Oberyn Martell 0.018402407<br>## 2    Quellon Greyjoy 0.016128129<br>## 3        Walder Frey 0.012956029<br>## 4       Eddard Stark 0.011725019<br>## 5       Cregan Stark 0.010983561<br>## 6      Catelyn Stark 0.010555473<br>## 7       Lyarra Stark 0.009876629<br>## 8  Aegon V Targaryen 0.009688458<br>## 9      Balon Greyjoy 0.009647049<br>## 10         Jon Arryn 0.00962374</pre><h3>- Clustering -</h3><p>แถมๆๆ นอกจาก <strong>Network Analysis </strong>แล้วยังมีอีกหนึ่งเรื่องที่น่าศึกษาและเป็นประโยชน์อย่างมากเกี่ยวกับการศีกษาเครือข่าย ก็คือ <a href="https://users.dimi.uniud.it/~massimo.franceschet/R/communities.html"><strong>Community Analysis</strong></a> หรือการวิเคราะห์ชุมชม</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rkr3ycPyNvA8AQ5jlB_rgw.png" /><figcaption>ภาพจาก <a href="https://blog.insightdatascience.com/graph-based-machine-learning-6e2bd8926a0">https://blog.insightdatascience.com/graph-based-machine-learning-6e2bd8926a0</a></figcaption></figure><p>ให้เราคิดภาพตามง่ายว่า <strong>Network Analysis</strong> เน้นไปที่การหาความเป็นศูนย์กลาง หรือ <strong>Centrality</strong> เราต่อยอดจากการได้ <strong>Node</strong> ที่เป็นศูนย์กลางแล้วคือ การแบ่งกลุ่มของ <strong>Node</strong> ออกเป็นกลุ่มย่อย หรือเรียกว่า <strong>Cluster</strong> <em>(คล้ายๆกับที่เราแบ่ง </em><strong><em>Cluster</em></strong><em> การระบาดของโรค </em><strong><em>Covid-19</em></strong><em> ในบ้านเรานั้นแหละครับ)</em></p><p>จากตัวละครทั้งหมดที่เราเห็นกราฟแรกสุด เราทำการ <strong>Clustering</strong> ด้วย <strong>cluster_edge_betweenness() function</strong> ได้ดังนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-VjdFUMvjrlL0V015BNEQ.png" /></figure><p>จากกราฟจะเห็นว่า <strong>Node</strong> ต่างๆถูกแบ่งกลุ่มย่อย (<strong>Clustering</strong>) จากตัวละครหลายร้อย ทั้ง <strong>9 House</strong> แบกออกเป็นกลุ่มย่อยได้ <strong>24 Cluster</strong> เห็นได้ชัดว่า ถึงแม้การวิเคราะห์นี้จะเป็นการวิเคราะห์ความสัมพันธ์ครอบครัว และบ้าน แต่ไม่ได้หมายความว่า กลุ่มของความสัมพันธ์ของตัวละครนั้น จะอยู่ที่ <strong>9</strong> กลุ่มตาม <strong>House</strong> หากแต่สามารถแบ่งย่อยได้อีกความสัมพันธ์มิติอื่นๆที่ซับซ้อน และแฝงอยู่ในเนื้อเรื่อง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxaQgM9Xv7ARyY4B4JF7gw.jpeg" /></figure><p>โดย <strong>Cluster</strong> ใหญ่และมี <strong>Overlapping</strong> มากที่สุด หนีไม่พ้น <strong>Cluster</strong> ของ <strong>Sansa</strong> <strong>Stark </strong>และ <strong>Tyrion Lannister</strong> ที่ส่วนใหญ่เป็น <strong>House Stark</strong></p><p><strong>Cluster</strong> รองลงมาเป็นของ <strong>House Targaryen</strong> ที่นำมาโดยตัวละครสาวสาย มารดาแหง่มังกร อย่าง <strong>Daenerys Targaryen</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYEezcVv1u6zHXzhtU8_Rw.jpeg" /><figcaption>ภาพจาก <a href="https://www.besthdwallpaper.com/game-of-thrones/game-of-thrones-daenerys-targaryen-mangkraefntaachii-dt_th-17353.html">https://www.besthdwallpaper.com/game-of-thrones/game-of-thrones-daenerys-targaryen-mangkraefntaachii-dt_th-17353.html</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*SqmrOyybWhwgMhI_sRrDgA.jpeg" /><figcaption>ภาพจาก <a href="https://www.looper.com/227637/the-entire-house-lannister-backstory-explained/">https://www.looper.com/227637/the-entire-house-lannister-backstory-explained/</a></figcaption></figure><p>ที่น่าสนใจคือ <strong>House Lannister</strong> มีตัวละคร กระจายตัวอยู่ใน <strong>Cluster</strong> อื่นๆมากที่สุด จากกลยุทธ์อันชาญฉลาดของ <strong>Lannister </strong>ในการสร้างพันมิตรทางการรบ และการฑูต ด้วยจุดมุ่งหมายที่คือการยึดครอง บัลลังก์เหล็กแห่งเจ็ดอาณาจักร ไว้กับตนเอง ทำให้ต้องมีการส่งตัวละครเข้าไป แทรกซึม หรือเชื่อมโยงกับ <strong>House</strong> อื่นๆมากมาย</p><h3>Conclusion</h3><p>มาถึงตรงนี้ เราคงพอสรุปกันได้แล้วว่า ตัวละครที่สำคัญที่สุดของ <strong>Game of Thrones</strong> ผ่าน <strong>Network Analysis</strong> ด้วยรูปแบบความสัมพันธ์ทางครอบครัว นั้นก็คือ <strong>Sansa Stark </strong>และ<strong> Tyrion Lannister</strong> 2 ตัวละครหลักที่เป็นตัวดำเนินเรื่องราว และเป็นตัวละครที่มาจาก <strong>House</strong> หลัก ทั้ง <strong>2 House</strong></p><blockquote>ข้อดีของ <strong>Centrality</strong> ข้อนึงคือ การมีวิธีคำนวณที่หลากหลาย เราจะเห็นการวัดความเป็น <strong>Centrality</strong> ในหลายมิติจากวิธีต่างๆที่อาจจะให้ค่าคำตอบเหมือนหรือต่างกันก็ไป ซึ่งล้วนแต่เป็นประโยชน์ทั้งสิ้น และต้องพิจารณาเลือกวิธีใช้งานให้เหมาะสม</blockquote><p>สิ่งที่น่าคิดสำหรับการมองความสัมพันธ์ผ่าน <strong>Network Analysis</strong> นี้ ก็คือ เราจะเห็นว่า <strong>Jon Snow และ Daenerys Targaryen</strong> ซึ่งเป็น <strong>2</strong> ตัวละครที่สำคัญมากๆในเรื่อง หรือเรียกว่าเป็น พระเอก นางเอก เลยก็ว่าได้ แต่ไม่ได้ถูกมองเป็น <strong>Node</strong> ที่มีความสำคัญ เนื่องจากความสัมพันธ์ทางครอบครัวของทั้ง <strong>2</strong> ตัวละคร ไม่มากเท่ากับตัวละครจาก <strong>House</strong> หลักอย่าง <strong>Stark</strong> และ <strong>Lannister</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AanBSOtM37_jUHD46Be91g.jpeg" /><figcaption>ภาพจาก <a href="https://www.zimbio.com/TV+News/articles/a4eUhQD-hRt/Still+Unclear+How+Daenerys+Jon+Snow+Related">https://www.zimbio.com/TV+News/articles/a4eUhQD-hRt/Still+Unclear+How+Daenerys+Jon+Snow+Related</a></figcaption></figure><p>ซึ่งเป็นการชี้ให้เห็นชัดๆอีกครั้งว่า <strong>Centrality </strong>นั้นพิจารณา <strong>Node</strong> ที่เชื่อมโยง กันด้วยความสัมพันธ์ใดความสัมพันธ์นึง ในที่นี้มองที่ความสัมพันธ์ทางครอบครัวและบ้าน แต่หากเปลี่ยนรูปแบบความสัมพันธ์เป็นอย่างอื่นเช่น การต่อสู้ หรือการดำเนินเรื่องในแง่อื่นๆ การวัด <strong>Centrality </strong>ของเรื่องก็อาจจจะเปลี่ยนตามไปด้วย และเชื่อว่าหาก รูปแบบความสัมพันธ์ไม่ใช้ เรื่องของความสัมพันธ์ครอบครัว <strong>Jon Snow</strong> และ <strong>Daenerys Targaryen</strong> จะต้องเป็นหนึ่งในตัวละครที่มีความสำคัญกับเครือข่ายที่สูงมากๆ อย่างแน่นอน</p><p>ท้ายที่สุด ถึงแม้ <strong>Season 8</strong> ซึ่งเป็น <strong>Season</strong>จบ จะจบไปแล้วหลายปี และสร้างความไม่ประทับใจให้กับแฟนๆอยากมาก แต่ก็ปฏิเสษไม่ได้ว่าภาพรวมของเรื่องราวทั้งหมด เรื่องราวที่ซับซ้อน อันเป็นเสน่ห์ของ <strong>Game of Thrones</strong> นั้นได้สร้างความประทับใจให้กับหลายๆคนก่อนหน้าไปแล้ว และถึงวันนี้จะมีกระแสการเรียกร้องให้ <strong>HBO</strong> กลับมาทำ <strong>Season 8 </strong>ใหม่แต่ความหวังก็ดูเลื่อนลาง สำหรับตอนนี้ก็คงได้แต่รอดูผลงาน ของนักแสดง จากผลงานอื่นให้หายคิดถึงแทน เพราะฉะนั้น เรามาเตรียมรอดู และให้กำลังใจ <strong>Jon Snow</strong> และ <strong>Robb Stark</strong>จาก<strong> Game of Thrones </strong>ใน <strong>Eternals </strong>กันเถอะครับ <em>(ระหว่างรอถึงเดือน พฤศจิกายนนี้ ใครทนไม่ได้ก็ไปย้อนดูกันตั้งแต่ </em><strong><em>Season 1</em></strong><em> จนจบให้ตาแฉะไปเลยค่าบ ทันๆเชื่อสิ ลุยย!! )</em></p><blockquote>บทความนี้ถือเป็นบทความแรกของผมเลย หากมีความผิดพลาดจุดไหน ก็ต้องขออภัย มา ณ ที่นี้ด้วยนะครับ และสำหรับเพื่อนๆที่ชอบการเล่าเรื่องราวทั่วไปๆ ในวิถี <strong>Data</strong> ง่ายๆแบบนี้ ก็ฝากกดปรมมือ รวมถึง แสดงความคิดเห็น หรือคำแนะนำด้านล่าง เพื่อเป็นกำลังใจให้กันและกันได้เลยครับ (ในอนาคตอาจจะมีบทความที่ <strong>2 3 4</strong> และต่อๆไป มาให้ติดตามอ่านเล่นกันอีก ฝากติดตามด้วยนะครับ ^^)</blockquote><p>สุดท้ายต้อง ขอขอบคุณ บทความต้นฉบับที่ผมได้กล่าวไปแล้วข้างต้น รวมถึง <strong>ดร.เอกสิทธิ์ พัชรวงศ์ศักดา</strong> อาจารย์เอกสุดหล่อของผม เจ้าของผลงานหนังสือ <a href="https://www.naiin.com/product/detail/508551"><strong>A Little Book of Big Data and Machine Learning</strong></a><strong> </strong>และ เฟจ<strong> </strong><a href="https://www.facebook.com/datacube.th"><strong>Data Cube</strong></a><strong> </strong>จาก<strong> CITE (College of innovative Technology and Engineering)</strong> <strong>DPU</strong> ที่ทำให้ผมมีโอกาสเขียนบทความนี้ และรวมถึงบทความต่อๆไปด้วยนะครับ <em>~</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*LhaqPkf2KRKXL17Yo056tg.png" /></figure><p><em>ขอบคุณครับ ~ see you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2698a489e402" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>