<?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 Ece Işık Polat on Medium]]></title>
        <description><![CDATA[Stories by Ece Işık Polat on Medium]]></description>
        <link>https://medium.com/@eceisikpolat?source=rss-bcbbbd72e7d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a7qjSPHcg1b_o3Larjfz4w.jpeg</url>
            <title>Stories by Ece Işık Polat on Medium</title>
            <link>https://medium.com/@eceisikpolat?source=rss-bcbbbd72e7d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 06:54:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eceisikpolat/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[Plot and customize multiple confusion matrices with matplotlib]]></title>
            <link>https://medium.com/@eceisikpolat/plot-and-customize-multiple-confusion-matrices-with-matplotlib-a19ed00ca16c?source=rss-bcbbbd72e7d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19ed00ca16c</guid>
            <category><![CDATA[confusion-matrix]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ece Işık Polat]]></dc:creator>
            <pubDate>Tue, 02 May 2023 07:29:18 GMT</pubDate>
            <atom:updated>2023-05-02T13:44:30.150Z</atom:updated>
            <content:encoded><![CDATA[<p>A confusion matrix is a valuable tool used in machine learning and statistics for evaluating the performance of classification algorithms. It visually represents a classification model&#39;s actual and predicted outcomes, helping to identify the model&#39;s accuracy, precision, recall, and F1 score.</p><p>The importance of a confusion matrix lies in its ability to summarize the performance of a classifier by showing the distribution of correct and incorrect predictions. This information can be used to identify specific areas where the classification model might be struggling, such as false positives or false negatives. Researchers and data scientists can fine-tune the model to improve its performance by understanding these problem areas.</p><p>In addition to its diagnostic capabilities, a confusion matrix can help compare different classification models, making choosing the best one for a given task easier. Moreover, it can be used to determine the trade-offs between other performance metrics, such as balancing the sensitivity and specificity of a model, depending on the problem&#39;s requirements.</p><p>In summary, a confusion matrix is an essential tool for understanding the performance of classification models. It provides valuable insights into the performance metrics and effectiveness of a model, helping researchers and data scientists identify areas for improvement and make informed decisions when selecting the most suitable model for a specific task.</p><p>In this post, I will share a code to generate and customize multiple confusion matrices. This will allow us to visualize and compare the performance of different classification models simultaneously. By examining these matrices, we can gain insights into each model&#39;s strengths and weaknesses, ultimately selecting the most suitable one for our specific task.</p><p>With this code, you can:</p><ul><li>Display multiple confusion matrices in a single figure.</li><li>Assign different titles to each subplot.</li><li>Set the font size of the labels and values.</li><li>Change the color of the confusion matrix.</li><li>Decide how many decimals to display for the values.</li><li>Adjust the x and y-axis labels and tick options to avoid repeating label names.</li><li>Add a main title to your plot.</li><li>Save your plot as a pdf. (Especially in reports using LaTeX, saving the plot as a PDF provides high resolution.)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78a6449bd9171ebc148782c02493b2fc/href">https://medium.com/media/78a6449bd9171ebc148782c02493b2fc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*JFFlLGygX1uwAx7fiMp3TA.png" /><figcaption>Multiple Confusion Matrices (Image by author)</figcaption></figure><p>You can access the entire code from <a href="https://github.com/eceisik/eip/blob/main/plot_multiple_confusion_matrices.ipynb">https://github.com/eceisik/eip/blob/main/plot_multiple_confusion_matrices.ipynb</a>. If you find this helpful, please don&#39;t hesitate to give it a clap or star.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19ed00ca16c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hypothesis Testing with Python: Step by step hands-on tutorial with practical examples]]></title>
            <link>https://medium.com/data-science/hypothesis-testing-with-python-step-by-step-hands-on-tutorial-with-practical-examples-e805975ea96e?source=rss-bcbbbd72e7d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e805975ea96e</guid>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ece Işık Polat]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 15:06:52 GMT</pubDate>
            <atom:updated>2022-02-22T19:27:15.196Z</atom:updated>
            <content:encoded><![CDATA[<p>Hypotheses are claims, and we can use statistics to prove or disprove them. At this point, <em>hypothesis testing</em> structures the problems so that we can use statistical evidence to test these claims. So we can check whether or not the claim is valid.</p><p>In this article, I want to show hypothesis testing with Python on several questions step-by-step. But before, let me explain the hypothesis testing process briefly. If you wish, you can move to the questions directly.</p><h4>1. Defining Hypotheses</h4><p>First of all, we should understand which scientific question we are looking for an answer to, and it should be formulated in the form of the <em>Null Hypothesis (H₀)</em> and the <em>Alternative Hypothesis (H₁ or Hₐ). </em>Please remember that H₀ and H₁ must be mutually exclusive, and H<em>₁</em> shouldn’t contain equality:</p><ul><li><strong>H₀:</strong> μ=x, <strong>H₁:</strong> μ≠x</li><li><strong>H₀:</strong> μ≤x, <strong>H₁:</strong> μ&gt;x</li><li><strong>H₀:</strong> μ≥x, <strong>H₁:</strong> μ&lt;x</li></ul><h4>2. Assumption Check</h4><p>To decide whether to use the <strong>parametric </strong>or <strong>nonparametric </strong>version of the test, we should check the specific requirements listed below:</p><ul><li>Observations in each sample are independent and identically distributed (IID).</li><li>Observations in each sample are normally distributed.</li><li>Observations in each sample have the same variance.</li></ul><h4>3. Selecting the Proper Test</h4><p>Then we select the appropriate test to be used. When choosing the proper test, it is essential to analyze how many groups are being compared and whether the data are paired or not. To determine whether the data is matched, it is necessary to consider whether the data was collected from the same individuals. Accordingly, you can decide on the appropriate test using the chart below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*LYkUpSAgFPuxlLFjGAUMbA.png" /><figcaption>Image by the author.</figcaption></figure><h4>4. Decision and Conclusion</h4><p>After performing the hypothesis testing, we obtain a related <strong><em>p</em>-value</strong> that shows the significance of the test.</p><p>If the <em>p</em>-value is smaller than the alpha (the significance level), in other words, there is enough evidence to prove H₀ is not valid; you can reject H₀. Otherwise, you fail to reject H₀. Please remember that rejecting H₀ validates H₁. However, failing to reject H₀ does not mean H₀ is valid, nor does it mean H₁ is wrong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*ymeVu_txMNAyT7wQvZqVYQ.png" /><figcaption>Image by the author.</figcaption></figure><p>Now we are ready to start the code part.</p><p>You can visit <a href="https://github.com/eceisik/eip/blob/main/hypothesis_testing_examples.ipynb">https://github.com/eceisik/eip/blob/main/hypothesis_testing_examples.ipynb</a> to see the full implementation.</p><h3>Q1. t-test independent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yjvyzPiURK1upTdK" /><figcaption>Photo by <a href="https://unsplash.com/@comparefibre?utm_source=medium&amp;utm_medium=referral">Compare Fibre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A university professor gave online lectures instead of face-to-face classes due to Covid-19. Later, he uploaded recorded lectures to the cloud for students who followed the course asynchronously (those who did not attend the lesson but later watched the records). However, he believes that the students who attend class at the class time and participate in the process are more successful. Therefore, he recorded the average grades of the students at the end of the semester. The data is below.</p><p><strong>synchronous</strong> = [94. , 84.9, 82.6, 69.5, 80.1, 79.6, 81.4, 77.8, 81.7, 78.8, 73.2, 87.9, 87.9, 93.5, 82.3, 79.3, 78.3, 71.6, 88.6, 74.6, 74.1, 80.6]<br><strong>asynchronous</strong> = [77.1, 71.7, 91. , 72.2, 74.8, 85.1, 67.6, 69.9, 75.3, 71.7, 65.7, 72.6, 71.5, 78.2]</p><p>Conduct the hypothesis testing to check whether the professor’s belief is statistically significant by using a 0.05 significance level to evaluate the null and alternative hypotheses. Before doing hypothesis testing, check the related assumptions. Comment on the results.</p><h4>1. Defining Hypothesis</h4><p>Since the grades are obtained from the different individuals, the data is unpaired.</p><p><strong>H₀:</strong> μₛ≤μₐ <br><strong>H₁</strong>: μₛ&gt;μₐ</p><h4>2. Assumption Check</h4><p><strong>H₀:</strong> The data is normally distributed.<br><strong>H₁:</strong> The data is not normally distributed.<br>Assume that α=0.05. If the <em>p</em>-value is &gt;0.05, it can be said that data is normally distributed.</p><p>For checking normality, I used Shapiro-Wilk’s W test which is generally preferred for smaller samples however there are other options like Kolmogorov-Smirnov and D’Agostino and Pearson’s test. Please visit <a href="https://docs.scipy.org/doc/scipy/reference/stats.html">https://docs.scipy.org/doc/scipy/reference/stats.html</a> for more information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25742f1972fa9e72f3556f049fc3fd08/href">https://medium.com/media/25742f1972fa9e72f3556f049fc3fd08/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbfc0fae3b69ef58ee878a1207fab253/href">https://medium.com/media/cbfc0fae3b69ef58ee878a1207fab253/href</a></iframe><pre>p value:0.6556<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.0803<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed</pre><p><strong>H₀:</strong> The variances of the samples are the same. <br><strong>H₁:</strong> The variances of the samples are different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f47ae157a24c76704829972a49e824/href">https://medium.com/media/83f47ae157a24c76704829972a49e824/href</a></iframe><p>It tests the null hypothesis that the population variances are equal (called homogeneity of variance or homoscedasticity). Suppose the resulting <em>p</em>-value of Levene’s test is less than the significance level (typically 0.05). In that case, the obtained differences in sample variances are unlikely to have occurred based on random sampling from a population with equal variances.</p><p>For checking variance homogeneity, I preferred Levene’s test but you can also check Bartlett’s test from here: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bartlett.html#scipy.stats.bartlett">https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.bartlett.html#scipy.stats.bartlett</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab24bed829373fa0a97462cbbeb05bbb/href">https://medium.com/media/ab24bed829373fa0a97462cbbeb05bbb/href</a></iframe><pre>p value:0.8149<br>Fail to reject null hypothesis &gt;&gt; The variances of the samples the are same.</pre><h4>3. Selecting the Proper Test</h4><p>Since assumptions are satisfied, we can perform the parametric version of the test for 2 groups and unpaired data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/875de85dea1a28c505e442d94f7356e8/href">https://medium.com/media/875de85dea1a28c505e442d94f7356e8/href</a></iframe><pre>p value:0.00753598<br>since the hypothesis is one sided &gt;&gt; use p_value/2 &gt;&gt; p_value_one_sided:0.0038<br>Reject null hypothesis</pre><h4>4. Decision and Conclusion</h4><p><strong><em>At this significance level, there is enough evidence to conclude that the average grade of the students who follow the course synchronously is higher than the students who follow the course asynchronously.</em></strong></p><h3>Q2. ANOVA</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t9HwuURNT0EVx1nf" /><figcaption>Photo by <a href="https://unsplash.com/@chrishcush?utm_source=medium&amp;utm_medium=referral">Christian Bowen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A pediatrician wants to see the effect of formula consumption on the average monthly weight gain (in gr) of babies. For this reason, she collected data from three different groups. The first group is exclusively breastfed children (receives only breast milk), the second group is children who are fed with only formula and the last group is both formula and breastfed children. These data are as below.</p><p><strong>only_breast</strong>=[794.1, 716.9, 993. , 724.7, 760.9, 908.2, 659.3 , 690.8, 768.7, 717.3 , 630.7, 729.5, 714.1, 810.3, 583.5, 679.9, 865.1]</p><p><strong>only_formula</strong>=[ 898.8, 881.2, 940.2, 966.2, 957.5, 1061.7, 1046.2, 980.4, 895.6, 919.7, 1074.1, 952.5, 796.3, 859.6, 871.1 , 1047.5, 919.1 , 1160.5, 996.9]</p><p><strong>both</strong>=[976.4, 656.4, 861.2, 706.8, 718.5, 717.1, 759.8, 894.6, 867.6, 805.6, 765.4, 800.3, 789.9, 875.3, 740. , 799.4, 790.3, 795.2 , 823.6, 818.7, 926.8, 791.7, 948.3]</p><p>According to this information, conduct the hypothesis testing to check whether there is a difference between the average monthly gain of these three groups by using a 0.05 significance level. If there is a significant difference, perform further analysis to find what caused the difference. Before doing hypothesis testing, check the related assumptions.</p><h4>1. Defining Hypothesis</h4><p><strong>H₀:</strong> μ₁=μ₂=μ₃ <strong>or</strong> The mean of the samples is the same.<br><strong>H₁:</strong> At least one of them is different.</p><h4>2. Assumption Check</h4><p><strong>H₀:</strong> The data is normally distributed.<br><strong>H₁:</strong> The data is not normally distributed.</p><p><strong>H₀:</strong> The variances of the samples are the same. <br><strong>H₁:</strong> The variances of the samples are different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f0739ae96cc8d09ad57568bcbda4809/href">https://medium.com/media/9f0739ae96cc8d09ad57568bcbda4809/href</a></iframe><pre>p value:0.4694<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.8879<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.7973<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.7673</pre><pre>Fail to reject null hypothesis &gt;&gt; The variances of the samples are same.</pre><h4>3. Selecting the Proper Test</h4><p>Since assumptions are satisfied, we can perform the parametric version of the test for more than 2 groups and unpaired data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9ed64014d40bc28e1f8f38c2e627659/href">https://medium.com/media/f9ed64014d40bc28e1f8f38c2e627659/href</a></iframe><pre>p value:0.000000<br>Reject null hypothesis</pre><h4>4. Decision and Conclusion</h4><p><strong><em>At this significance level, it can be concluded that at least one of the groups has a different average monthly weight gain.</em></strong> To find which group or groups cause the difference, we need to perform a posthoc test/pairwise comparison as below.</p><p><strong>Note:</strong> To avoid family-wise <em>p</em>-value inflation, I used Bonferroni adjustment. You can see your other alternative from here: <a href="https://scikit-posthocs.readthedocs.io/en/latest/generated/scikit_posthocs.posthoc_ttest/">https://scikit-posthocs.readthedocs.io/en/latest/generated/scikit_posthocs.posthoc_ttest/</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9396c7bc3d6c40088b8eb8e68cafaf93/href">https://medium.com/media/9396c7bc3d6c40088b8eb8e68cafaf93/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*uoPPsB15VAIUGoGCzLp6kw.png" /></figure><p>At this significance level, it can be concluded that:</p><p><strong>“only breast”</strong> is different than <strong>“only formula”</strong><br> <strong>“only formula”</strong> is different than both <strong>“only breast”</strong> and <strong>“both”</strong><br> <strong>“both”</strong> is different than <strong>“only formula”</strong></p><h3>Q3. Mann Whitney U</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TURN0ckdIuzoVks4" /><figcaption>Photo by <a href="https://unsplash.com/@frantic?utm_source=medium&amp;utm_medium=referral">Alex Kotliarskyi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A human resource specialist working in a technology company is interested in the overwork time of different teams. To investigate whether there is a difference between overtime of the software development team and the test team, she selected 17 employees randomly in each of the two teams and recorded their weekly average overwork time in terms of an hour. The data is below.</p><p><strong>test_team</strong>=[6.2, 7.1, 1.5, 2,3 , 2, 1.5, 6.1, 2.4, 2.3, 12.4, 1.8, 5.3, 3.1, 9.4, 2.3, 4.1]<br><strong>developer_team</strong>=[2.3, 2.1, 1.4, 2.0, 8.7, 2.2, 3.1, 4.2, 3.6, 2.5, 3.1, 6.2, 12.1, 3.9, 2.2, 1.2 ,3.4]</p><p>According to this information, conduct the hypothesis testing to check whether there is a difference between the overwork time of two teams by using a 0.05 significance level. Before doing hypothesis testing, check the related assumptions.</p><h4>1. Defining Hypothesis</h4><p><strong>H₀:</strong> μ₁≤μ₂ <br><strong>H₁</strong>: μ₁&gt;μ₂</p><h4>2. Assumption Check</h4><p><strong>H₀:</strong> The data is normally distributed.<br><strong>H₁:</strong> The data is not normally distributed.</p><p><strong>H₀:</strong> The variances of the samples are the same. <br><strong>H₁:</strong> The variances of the samples are different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e67b1779fb4972d9fa3b73f7ae2cf1b/href">https://medium.com/media/6e67b1779fb4972d9fa3b73f7ae2cf1b/href</a></iframe><pre>p value:0.0046<br>Reject null hypothesis &gt;&gt; The data is not normally distributed<br>p value:0.0005<br>Reject null hypothesis &gt;&gt; The data is not normally distributed<br>p value:0.5410<br>Fail to reject null hypothesis &gt;&gt; The variances of the samples are same.</pre><h4>3. Selecting the Proper Test</h4><p>There are two groups, and data is collected from different individuals, so it is not paired. However, the normality assumption is not satisfied; therefore, we need to use the nonparametric version of 2 group comparison for unpaired data: the Mann-Whitney U Test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c857f2f167661ecfc1ea40a56729f53d/href">https://medium.com/media/c857f2f167661ecfc1ea40a56729f53d/href</a></iframe><h4>4. Decision and Conclusion</h4><pre>p-value:0.8226<br>Fail to recejt null hypothesis</pre><p><strong><em>At this significance level,</em></strong><em> </em><strong><em>it can be said that there is no statistically significant difference between the average overwork time of the two teams.</em></strong></p><h3>Q4. Kruskal-Wallis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G_qEV8vSYJXV_Zv5" /><figcaption>Photo by <a href="https://unsplash.com/@paman0744?utm_source=medium&amp;utm_medium=referral">Aman Pal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>An e-commerce company regularly advertises on YouTube, Instagram, and Facebook for its campaigns. However, the new manager was curious about if there was any difference between the number of customers attracted by these platforms. Therefore, she started to use Adjust, an application that allows you to find out where your users come from. The daily numbers reported from Adjust for each platform are as below.</p><p><strong>Youtube</strong>=[1913, 1879, 1939, 2146, 2040, 2127, 2122, 2156, 2036, 1974, 1956, 2146, 2151, 1943, 2125]</p><p><strong>Instagram </strong>= [2305., 2355., 2203., 2231., 2185., 2420., 2386., 2410., 2340., 2349., 2241., 2396., 2244., 2267., 2281.]</p><p><strong>Facebook </strong>= [2133., 2522., 2124., 2551., 2293., 2367., 2460., 2311., 2178., 2113., 2048., 2443., 2265., 2095., 2528.]</p><p>According to this information, conduct the hypothesis testing to check whether there is a difference between the average customer acquisition of these three platforms using a 0.05 significance level. If there is a significant difference, perform further analysis to find that caused the difference. Before doing hypothesis testing, check the related assumptions.</p><h4>1. Defining Hypothesis</h4><p><strong>H₀:</strong> μ₁=μ₂=μ₃ <strong>or</strong> The mean of the samples is the same.<br><strong>H₁:</strong> At least one of them is different.</p><h4>2. Assumption Check</h4><p><strong>H₀:</strong> The data is normally distributed.<br><strong>H₁:</strong> The data is not normally distributed.</p><p><strong>H₀:</strong> The variances of the samples are the same. <br><strong>H₁:</strong> The variances of the samples are different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b7f6766943445d10370068fc4035561/href">https://medium.com/media/9b7f6766943445d10370068fc4035561/href</a></iframe><pre>p value:0.0285<br>Reject null hypothesis &gt;&gt; The data is not normally distributed<br>p value:0.4156<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.1716<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.0012<br>Reject null hypothesis &gt;&gt; The variances of the samples are different.</pre><h4>3. Selecting the Proper Test</h4><p>The normality and variance homogeneity assumptions are not satisfied, therefore we need to use the nonparametric version of ANOVA for unpaired data (the data is collected from different sources).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae4096a0e6786cc0e81d8356503b7b1d/href">https://medium.com/media/ae4096a0e6786cc0e81d8356503b7b1d/href</a></iframe><h4>4. Decision and Conclusion</h4><pre>p value:0.000015<br>Reject null hypothesis</pre><p><strong><em>At this significance level, at least one of the average customer acquisition number is different.</em></strong> <br><strong>Note:</strong> Since the data is not normal, the nonparametric version of posthoc test is used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb277faf412159a61d65011e955bd628/href">https://medium.com/media/bb277faf412159a61d65011e955bd628/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*i1lEBN2y0H0-eDdHfvBOpw.png" /></figure><p>The average number of customers coming from YouTube is different than the other (actually smaller than the others).</p><h3>Q5. t-test dependent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HGzeftp0fFa3MQzV" /><figcaption>Photo by <a href="https://unsplash.com/@brookelark?utm_source=medium&amp;utm_medium=referral">Brooke Lark</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The University Health Center diagnosed eighteen students with high cholesterol in the previous semester. Healthcare personnel told these patients about the dangers of high cholesterol and prescribed a diet program. One month later, the patients came for control, and their cholesterol level was reexamined. Test whether there is a difference in the cholesterol levels of the patients.</p><p>According to this information, conduct the hypothesis testing to check whether there is a decrease in the cholesterol levels of the patients after the diet by using a 0.05 significance level. Before doing hypothesis testing, check the related assumptions. Comment on the results</p><p><strong>test_results_before_diet</strong>=[224, 235, 223, 253, 253, 224, 244, 225, 259, 220, 242, 240, 239, 229, 276, 254, 237, 227]<br><strong>test_results_after_diet</strong>=[198, 195, 213, 190, 246, 206, 225, 199, 214, 210, 188, 205, 200, 220, 190, 199, 191, 218]</p><h4>1. Defining Hypothesis</h4><p><strong>H₀: </strong>μd&gt;=0 <strong>or</strong> The true mean difference is equal to or bigger than zero.<br><strong>H₁: </strong>μd&lt;0 <strong>or</strong> The true mean difference is smaller than zero.</p><h4>2. Assumption Check</h4><p>• The dependent variable must be continuous (interval/ratio) <br>• The observations are independent of one another.<br>• The dependent variable should be approximately normally distributed.</p><p><strong>H₀:</strong> The data is normally distributed.<br><strong>H₁:</strong> The data is not normally distributed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0da2d0eba454c2b182955c169399f95f/href">https://medium.com/media/0da2d0eba454c2b182955c169399f95f/href</a></iframe><pre>p value:0.1635<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.1003<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed</pre><h4>3. Selecting the Proper Test</h4><p>The data is paired since data is collected from the same individuals and assumptions are satisfied, then we can use the dependent t-test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3707de0301368daaeeb0ce5e8a869116/href">https://medium.com/media/3707de0301368daaeeb0ce5e8a869116/href</a></iframe><pre>p value:0.000008 one tailed p value:0.000004<br>Reject null hypothesis</pre><h4>4. Decision and Conclusion</h4><p><strong><em>At this significance level, there is enough evidence to conclude mean cholesterol level of patients has decreased after the diet.</em></strong></p><h3>Q6. Wilcoxon signed-rank test</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3osxYamKD88c6pXdfO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3osxYamKD88c6pXdfO%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3osxYamKD88c6pXdfO%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4e790479e2d026d0b2803ed30f7cdff/href">https://medium.com/media/a4e790479e2d026d0b2803ed30f7cdff/href</a></iframe><p>A venture capitalist wanted to invest in a startup that provides data compression without any loss in quality, but there are two competitors: PiedPiper and EndFrame. Initially, she believed the performance of the EndFrame could be better but still wanted to test it before the investment. Then, she gave the same files to each company to compress and recorded their performance scores. The data is below.</p><p><strong>piedpiper</strong>=[4.57, 4.55, 5.47, 4.67, 5.41, 5.55, 5.53, 5.63, 3.86, 3.97, 5.44, 3.93, 5.31, 5.17, 4.39, 4.28, 5.25]<br><strong>endframe</strong> = [4.27, 3.93, 4.01, 4.07, 3.87, 4. , 4. , 3.72, 4.16, 4.1 , 3.9 , 3.97, 4.08, 3.96, 3.96, 3.77, 4.09]</p><p>According to this information, conduct the related hypothesis testing by using a 0.05 significance level. Before doing hypothesis testing, check the related assumptions. Comment on the results.</p><h4>1. Defining Hypothesis</h4><p>Since the performance scores are obtained from the same files, the data is paired.</p><p><strong>H₀: </strong>μd&gt;=0 <strong>or</strong> The true mean difference is equal to or bigger than zero.<br><strong>H₁: </strong>μd&lt;0 <strong>or</strong> The true mean difference is smaller than zero.</p><h4>2. Assumption Check</h4><p>• The dependent variable must be continuous (interval/ratio) <br>• The observations are independent of one another.<br>• The dependent variable should be approximately normally distributed.</p><p><strong>H₀:</strong> The data is normally distributed.<br><strong>H₁:</strong> The data is not normally distributed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/059b4bb7dd3a35048f9a2165c2eb1431/href">https://medium.com/media/059b4bb7dd3a35048f9a2165c2eb1431/href</a></iframe><pre>p value:0.0304<br>Reject null hypothesis &gt;&gt; The data is not normally distributed<br>p value:0.9587<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed</pre><h4>3. Selecting the Proper Test</h4><p>The normality assumption is not satisfied; therefore, we need to use the nonparametric version of the paired test, namely the Wilcoxon Signed Rank test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b399374a465fa88ef341bebeaceac30b/href">https://medium.com/media/b399374a465fa88ef341bebeaceac30b/href</a></iframe><h4>4. Decision and Conclusion</h4><pre>p-value:0.000214 &gt;&gt; one_tailed_pval:0.000107<br>one sided pvalue:0.000107<br>Reject null hypothesis</pre><p><strong><em>At this significance level, there is enough evidence to conclude that the performance of the PiedPaper is better than the EndFrame.</em></strong></p><h3>Q7. Friedman Chi-Square</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xpdm6Bgi2oi0Kd5Y" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A researcher was curious about whether there is a difference between the methodology she developed, C, and baseline methods A and B in terms of performance. Therefore, she decided to design different experiments and recorded the achieved accuracy by each method. The below table shows the achieved accuracy on test sets by each method. Please note that the same train and test sets were used for each method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*TuethdK6nraRUZISpbEgHw.png" /></figure><p>According to this information, conduct the hypothesis testing to check whether there is a difference between the performance of the methods by using a 0.05 significance level. If there is a significant difference, perform further analysis to find which one caused the difference. Before doing hypothesis testing, check the related assumptions. Comment on the results.</p><h4>1. Defining Hypothesis</h4><p><strong>H₀:</strong> μ₁=μ₂=μ₃ <strong>or</strong> The mean of the samples is the same.<br><strong>H₁:</strong> At least one of them is different.</p><h4>2. Assumption Check</h4><p><strong>H₀:</strong> The data is normally distributed.<br><strong>H₁:</strong> The data is not normally distributed.</p><p><strong>H₀:</strong> The variances of the samples are the same. <br><strong>H₁:</strong> The variances of the samples are different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6daf13541ab260c28c206826acffedc/href">https://medium.com/media/f6daf13541ab260c28c206826acffedc/href</a></iframe><pre>p value:0.3076<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.0515<br>Fail to reject null hypothesis &gt;&gt; The data is normally distributed<br>p value:0.0016<br>Reject null hypothesis &gt;&gt; The data is not normally distributed<br>p value:0.1953<br>Fail to reject null hypothesis &gt;&gt; The variances of the samples are same.</pre><h4>3. Selecting the Proper Test</h4><p>There are three groups, but the normality assumption is violated. So, we need to use the nonparametric version of ANOVA for paired data since the accuracy scores are obtained from the same test sets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1400644afddb49ad63b7f15de45b8c99/href">https://medium.com/media/1400644afddb49ad63b7f15de45b8c99/href</a></iframe><h4>4. Decision and Conclusion</h4><pre>p value:0.0015<br>Reject null hypothesis<br>89.35 89.49 90.49</pre><p><strong><em>At this significance level, at least one of the methods has a different performance.</em></strong></p><p><strong>Note:</strong> Since the data is not normal, the nonparametric version of the posthoc test is used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5da398a1c71c48b690b4c302f35a3805/href">https://medium.com/media/5da398a1c71c48b690b4c302f35a3805/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*zskjBOZwFnDMxyMRE-5zcw.png" /></figure><p>Method C outperformed others and achieved better accuracy scores than the others.</p><h3>Q8. The goodness of Fit (Bonus :)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CfvO7sFggkGb3Z5O" /><figcaption>Photo by <a href="https://unsplash.com/@janilson123?utm_source=medium&amp;utm_medium=referral">janilson furtado</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>An analyst of a financial investment company is curious about the relationship between gender and risk appetite. A random sample was taken of 660 customers from the database. The customers in the sample were classified according to their gender and their risk appetite. The result is given in the following table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*a85Gb8oHPL_86KcsNwVdwQ.png" /></figure><p>Test the hypothesis that the risk appetite of the customers in this company is independent of their gender. Use <strong>α = 0.01</strong>.</p><h4>1. Defining Hypothesis</h4><p><strong>H₀:</strong> Gender and risk appetite are independent. <br><strong>H₁:</strong> Gender and risk appetite are dependent.</p><h4>2. Selecting the Proper Test and Assumption Check</h4><p>chi2 test should be used for this question. This test is known as the goodness-of-fit test. It implies that if the observed data are very close to the expected data. The assumption of this test every Ei ≥ 5 (in at least 80% of the cells) is satisfied.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25f1b288c2dbfb70e07b95025b469ba/href">https://medium.com/media/f25f1b288c2dbfb70e07b95025b469ba/href</a></iframe><pre>expected frequencies:<br>  [[ 43.21  24.74  28.23  32.41 101.41]<br> [ 80.79  46.26  52.77  60.59 189.59]]<br>degrees of freedom: 4<br>test stat :7.0942<br>p value:0.1310</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73d7ae163f96e3e7d9908e6f3f16636f/href">https://medium.com/media/73d7ae163f96e3e7d9908e6f3f16636f/href</a></iframe><h4>3. Decision and Conclusion</h4><pre>critical stat:13.2767</pre><p>Since the p-value is larger than α=0.01 ( or calculated statistic=7.14 is smaller than the critical statistic=13.28) → Fail to Reject H₀. At this significance level, it can be concluded that gender and risk appetite are independent.</p><p>You can visit <a href="https://github.com/eceisik/eip/blob/main/hypothesis_testing_examples.ipynb">https://github.com/eceisik/eip/blob/main/hypothesis_testing_examples.ipynb</a> to see the full implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e805975ea96e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/hypothesis-testing-with-python-step-by-step-hands-on-tutorial-with-practical-examples-e805975ea96e">Hypothesis Testing with Python: Step by step hands-on tutorial with practical examples</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why It is So Important to Understand the Missing Data Mechanisms]]></title>
            <link>https://medium.com/data-science/why-it-is-so-important-to-understand-the-missing-data-mechanisms-3d7d656ec7cc?source=rss-bcbbbd72e7d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d7d656ec7cc</guid>
            <category><![CDATA[missing-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[missing-data-mechanism]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ece Işık Polat]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 13:13:01 GMT</pubDate>
            <atom:updated>2020-12-30T09:16:01.263Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Is It So Important to Understand the Missing Data Mechanisms</h3><h4>Missing Data Mechanisms with Easily Understandable Examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X3Tq44cXj_ot7363" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In modern life, everything is going so fast. If you act slow, someone will come and do what you have to do. Therefore, sometimes we are rushed to produce results in data science problems both in academia and sector. Fit model and try to improve the required performance metric by changing model parameters. Building an appropriate model and hyperparameter tuning are essential, but we need first to understand the data itself.</p><p>One of the most common problems with dataset quality is missing values. Do we really know why these values are missing? How should we impute them? Should we really impute them? Should we drop or let them stay? Figure out the answer to these questions; we need to know more about the missing data mechanisms.</p><p>Let’s consider an example. You want to develop a model that predicts house prices from a dataset containing for sale home advertisements. Then, you notice that the building&#39;s construction year; in other words, building age is missing in some observations. Was it by chance, or is there an intention behind it? Should we delete observations whose construction year is missing, or should we use simple mean imputation and go our way? If you take these steps without fully understanding the reason behind the missingness, you can create a bias in your model. Because the advertiser may not have entered the building construction year information, thinking that people are less willing to see an old house and adjust their filtering settings according to it and the house will be sold more difficult. Now, if you dropped these observations, you would discard old houses.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fde4aRYwfD7T7q%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fde4aRYwfD7T7q&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZTc5MGM3ZTg0MGU2ZjE4MjA3ZjM5OWZjYWY5Njg0YmI2MjU2OGNjMCZjdD1n%2Fde4aRYwfD7T7q%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="240" frameborder="0" scrolling="no"><a href="https://medium.com/media/28bd98195b0754acf5514c3f64b73184/href">https://medium.com/media/28bd98195b0754acf5514c3f64b73184/href</a></iframe><p>There are three types of missingness mechanisms.</p><ol><li><strong>Missing Completely at Random (MCAR): </strong>Missingness of a variable is completely independent of itself and other variables. For example, missingness at the number of fireplaces is independent of itself or kitchen area information or exterior covering material on the house. As the name implies, missingness is completely random.</li><li><strong>Missing Not at Random (MNAR): </strong>Missingness of a variable is related to itself. If you are going to rent or buy a summer house, one of the important criteria may be the proximity to the sea because it is a great convenience to reach the sea by walking. Likewise building age example, if this information is not given in an advertisement, it may be because it is far from the sea.</li><li><strong>Missing at Random (MAR): </strong>Missingness of a variable is dependent on another variable. Let’s assume that with a regulation made in 2013, the seismic resistance certificate was made compulsory for new houses. For homes built before 2013, the information may appear as NA in your dataset. But that doesn’t mean that this house is not resistant to earthquakes. In other words, the missingness pattern is not MNAR. Or let’s think of variables that are more clearly related to each other. If a house does not have a garage, we cannot talk about the garage capacity or quality, and these variables will naturally be missing.</li></ol><p>I have created a toy missing data set to illustrate missing mechanisms visually. There are five attributes in this data set. They are, namely, x1, x2, x3,x4, and x5.</p><ul><li><strong>For MAR</strong>, x1 is missing if x2 is greater than 46.</li><li><strong>For MNAR, </strong>If x3 is greater than 67, x3 is missing.</li><li><strong>For MCAR</strong>, some of the observations of x4 were randomly deleted.</li></ul><p>Let’s scatter x1 and x2 with respect to the missing state of x1. Blue dots indicate x1 existence, and red dots indicate the absence of x1. As I manipulated the data, the relationship between x1 and x2 is clearly visible → when x2 is greater than 46, x1 is missing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*GTwSEyGG0I_Ov3wayKEA0Q.png" /><figcaption>Scatterplot of x1 vsx2 with respect to the absence state of x1 (Image by Author)</figcaption></figure><p>So, how do we observe the relationship of x1 with other variables or itself in this case? As you can see from the below graph, there is no specific pattern. It looks like blue and red dots scattered randomly. Therefore, it can be said that the missingness of x1 is not related to itself or x4?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCHxUa3YyWd4-rdAYELYkA.png" /><figcaption>Scatterplot of x1 vs x1 and x4 with respect to the absence state of x1 (Image by Author)</figcaption></figure><p>In the same manner, let’s check x3. The below visualization show the relationship between x3 with x1, itself, and x5, respectively. x3 is missing when x3 is greater than 67.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*l0LNxWPbnHrQw1YDCIXEew.png" /><figcaption>Scatterplot of x3 vs x1, x2, x3, and x5 with respect to the absence state of x3(Image by Author)</figcaption></figure><p>Finally, if we look at the x4, we cannot observe any pattern because I deleted observations randomly. So it can be said that the missingness mechanism is MCAR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*B5hHvx-OG3oTgUA-f_anhQ.png" /><figcaption>Scatterplot of x4 vs x2, x3, x4, and x5 with respect to the absence state of x4(Image by Author)</figcaption></figure><p>Please be aware that it is a toy example; you don’t know which values are really missing in real life (and you cannot visualize missingness in this way). If you are a domain expert, you may have an idea, but you cannot be sure 100%. Specifically, detecting the MNAR mechanism is very difficult if there is no prior information about the data set and don’t know the domain’s context. But luckily, there are some statistical tests for checking mechanisms, and I will give detailed examples with codes in my next post. Please stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d7d656ec7cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-it-is-so-important-to-understand-the-missing-data-mechanisms-3d7d656ec7cc">Why It is So Important to Understand the Missing Data Mechanisms</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Federated Learning: A Simple Implementation of FedAvg (Federated Averaging) with PyTorch]]></title>
            <link>https://medium.com/data-science/federated-learning-a-simple-implementation-of-fedavg-federated-averaging-with-pytorch-90187c9c9577?source=rss-bcbbbd72e7d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/90187c9c9577</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[federated-learning]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <dc:creator><![CDATA[Ece Işık Polat]]></dc:creator>
            <pubDate>Thu, 24 Sep 2020 17:47:43 GMT</pubDate>
            <atom:updated>2020-09-28T14:10:14.931Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-x6S44IhloUifMhqkpYMQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jdent?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jason Dent</a> on <a href="https://unsplash.com/s/photos/privacy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Mobile devices such as phones, tablets, and smartwatches are now primary computing devices and have become integral for many people. These devices host huge amounts of valuable and private data thanks to the combination of rich user interactions and powerful sensors. Models trained on such data could significantly improve the usability and power of intelligent applications. However, the sensitive nature of this data means there are also some risks and responsibilities [1]. At this point, the Federated Learning (FL) concept comes into play.</p><p>In FL, each client trains its model decentrally. In other words, the model training process is carried out separately for each client. Only learned model parameters are sent to a trusted center to combine and feed the aggregated main model. Then the trusted center sent back the aggregated main model back to these clients, and this process is circulated [2].</p><p>In this context, I prepared a simple implementation with IID (independent and identically distributed) data to show how the parameters of hundreds of different models that are running on different nodes can be combined with the FedAvg method and whether this model will give a reasonable result. This implementation was carried out on the MNIST Data set. The MNIST data set contains 28 * 28 pixel grayscale images of numbers from 0 to 9 [3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*7tRuEBQleYASpCUW8nns-w.png" /><figcaption>Handwritten Digits from the MNIST dataset (Image by Author*)</figcaption></figure><ul><li>The MNIST data set does not contain each label equally. Therefore, to fulfill the IID requirement, the dataset was grouped, shuffled, and then distributed so that each node contains an equal number of each label.</li><li>A simple 2-layer model was created for the classification process.</li><li>Functions to be used for FedAvg are defined.</li></ul><p>Here, an iteration is completed as follows.</p><ol><li>Since the parameters of the main model and parameters of all local models in the nodes are randomly initialized, all these parameters will be different from each other. For this reason, the main model sends its parameters to the nodes before the training of local models in the nodes begins.</li><li>Nodes start to train their local models over their own data by using these parameters.</li><li>Each node updates its parameters while training its own model. After the training process is completed, each node sends its parameters to the main model.</li><li>The main model takes the average of these parameters and sets them as its new weight parameters and passes them back to the nodes for the next iteration.</li></ol><p>The above flow is for one iteration. This iteration can be repeated over and over to improve the performance of the main model.</p><p><strong>Note:</strong> The purpose here is not to increase the performance of the classification algorithm, but to compare the performance of the model obtained with federated learning with a centralized model. If you wish, you can use more complicated models or adjust hyperparameters to improve performance.</p><p>And if you are ready, here we go!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUOwGdA2o7E4TPJICQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUOwGdA2o7E4TPJICQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxUOwGdA2o7E4TPJICQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a40c7da7556f1cb0e6c4d9089ab9c5c/href">https://medium.com/media/7a40c7da7556f1cb0e6c4d9089ab9c5c/href</a></iframe><h3>Function Explanations</h3><p><strong>Functions for data distribution</strong></p><ul><li><strong><em>split_and_shuffle_labels(y_data, seed, amount):</em> </strong>The data set does not contain an equal number of each label. In order to distribute the data to the nodes as IID, an equal number of them must be taken. This function groups them as much as the amount given from each label and shuffles the order within itself. Please be aware that, what shuffled here is the indexes of the data, we will use them when retrieving the data in the future. But these indexes need to be reset to avoid key errors. Therefore, a new column has been defined and shuffled indexes are kept there.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94714812d3ad33992534d313bde717e6/href">https://medium.com/media/94714812d3ad33992534d313bde717e6/href</a></iframe><ul><li><strong><em>get_iid_subsamples_indices(label_dict, number_of_samples, amount):</em></strong> This function divides the indexes in each node with an equal number of each label. (Here the indexes are still distributed, not data)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6568ce32ae512914d8debc785cd28f9/href">https://medium.com/media/d6568ce32ae512914d8debc785cd28f9/href</a></iframe><ul><li><strong><em>create_iid_subsamples(sample_dict, x_data, y_data, x_name, y_name):</em></strong> This function distributes x and y data to nodes in dictionary.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0f8fe30332c6d8086f83a408459a536/href">https://medium.com/media/e0f8fe30332c6d8086f83a408459a536/href</a></iframe><p><strong>Functions for FedAvg</strong></p><ul><li><strong><em>create_model_optimizer_criterion_dict(number_of_samples):</em></strong> This function creates a model, optimizer and loss function for each node.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/beaa1d730209e86e9171261d14fbc531/href">https://medium.com/media/beaa1d730209e86e9171261d14fbc531/href</a></iframe><ul><li><strong><em>get_averaged_weights(model_dict, number_of_samples):</em></strong> This function takes the average of the weights in individual nodes.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0c58d6c564ec689ace13d591f460602/href">https://medium.com/media/d0c58d6c564ec689ace13d591f460602/href</a></iframe><ul><li><strong><em>set_averaged_weights_as_main_model_weights_and_update_main_model(main_model,model_dict, number_of_samples):</em></strong> This function sends the averaged weights of individual nodes to the main model and sets them as the new weights of the main model. ( calls def get_averaged_weights(model_dict, number_of_samples))</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f9f9f792931da422461d8fbdb5196fa/href">https://medium.com/media/1f9f9f792931da422461d8fbdb5196fa/href</a></iframe><ul><li><strong><em>compare_local_and_merged_model_performance(number_of_samples:</em></strong> This function compares the accuracy of the main model and the local model running on each node.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf5544f5ad996de9e0edf5a21f558c56/href">https://medium.com/media/bf5544f5ad996de9e0edf5a21f558c56/href</a></iframe><ul><li><strong><em>send_main_model_to_nodes_and_update_model_dict(main_model, model_dict, number_of_samples):</em> </strong>This function sends the parameters of the main model to the nodes.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1656466b8f96fdb904c25dc62ccd116/href">https://medium.com/media/a1656466b8f96fdb904c25dc62ccd116/href</a></iframe><ul><li><strong><em>start_train_end_node_process_without_print():</em></strong> This function trains individual local models in nodes.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb3ac75b5f0635f428e017bb08274e4b/href">https://medium.com/media/cb3ac75b5f0635f428e017bb08274e4b/href</a></iframe><h3>What would the performance of a centralized model that is based on all training data be?</h3><p>First, let’s examine what would the performance of the centralized model be if the data were not distributed to nodes at all?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64bb3f2dd4b76c6bd52db9ad7980104a/href">https://medium.com/media/64bb3f2dd4b76c6bd52db9ad7980104a/href</a></iframe><pre> — — — Centralized Model — — — <br>epoch: 1 | train accuracy: 0.8743 | test accuracy: 0.9437<br>epoch: 2 | train accuracy: 0.9567 | test accuracy: 0.9654<br>epoch: 3 | train accuracy: 0.9712 | test accuracy: 0.9701<br>epoch: 4 | train accuracy: 0.9785 | test accuracy: 0.9738<br>epoch: 5 | train accuracy: 0.9834 | test accuracy: 0.9713<br>epoch: 6 | train accuracy: 0.9864 | test accuracy: 0.9768<br>epoch: 7 | train accuracy: 0.9898 | test accuracy: 0.9763<br>epoch: 8 | train accuracy: 0.9923 | test accuracy: 0.9804<br>epoch: 9 | train accuracy: 0.9941 | test accuracy: 0.9784<br>epoch: 10 | train accuracy: 0.9959 | test accuracy: 0.9792<br> — — — Training finished — — -</pre><p>The model used in this example is very simple, different improvements can be performed to increase model performance, such as using more complex models, increasing epoch or hyperparameter tuning. However, the purpose here is to compare the performance of the main model that is formed by combining the parameters of the local models trained on their own data with a centralized model that trained on all training data. In this way, we can gain insight into the capacity of federated learning.</p><p>Then, start our first iteration</p><p><strong>Data is distributed to nodes</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ff272cbfe882a4b048339f8b2ac687c/href">https://medium.com/media/7ff272cbfe882a4b048339f8b2ac687c/href</a></iframe><p><strong>The main model is created</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1680ef490849e1f4208a49d52f7fc385/href">https://medium.com/media/1680ef490849e1f4208a49d52f7fc385/href</a></iframe><p><strong>Models, optimizers, and loss functions in nodes are defined</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7ea6184d9b8b19a0be17da450b525a4/href">https://medium.com/media/b7ea6184d9b8b19a0be17da450b525a4/href</a></iframe><p><strong>Keys of dicts are being made iterable</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7340f8ca65e0ce2869c7f7ec8efa8744/href">https://medium.com/media/7340f8ca65e0ce2869c7f7ec8efa8744/href</a></iframe><p><strong>Parameters of the main model are sent to nodes</strong><br>Since the parameters of the main model and parameters of all local models in the nodes are randomly initialized, all these parameters will be different from each other. For this reason, the main model sends its parameters to the nodes before the training of local models in the nodes begins. You can check the weights below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c848334d1abeb30b3a6c87a364d56eb8/href">https://medium.com/media/c848334d1abeb30b3a6c87a364d56eb8/href</a></iframe><p><strong>Models in the nodes are trained</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc255e329d7e92b23ce9480846f32add/href">https://medium.com/media/bc255e329d7e92b23ce9480846f32add/href</a></iframe><h3>Let’s compare the performance of the federated main model and centralized model</h3><p><strong>Federated main model vs centralized model before 1st iteration (on all test data)</strong><br>Since the main model is randomly initialized and no action taken on it yet, before first iteration its performance is very poor. After first iteration, the accuracy of main model increased to %85.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a024896c70c12dcd3dcf7b4bf55481e7/href">https://medium.com/media/a024896c70c12dcd3dcf7b4bf55481e7/href</a></iframe><pre>Before 1st iteration main model accuracy on all test data: 0.1180<br>After 1st iteration main model accuracy on all test data: 0.8529<br>Centralized model accuracy on all test data: 0.9790</pre><p>This is a single iteration, we can send the parameters of the main model back to the nodes and repeat the above steps. Now let’s check how the performance of the main model improves when we repeat the iteration 10 more times.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0f3cca7a889c96ce3ef56cd0c06b029/href">https://medium.com/media/d0f3cca7a889c96ce3ef56cd0c06b029/href</a></iframe><pre>Iteration 2 : main_model accuracy on all test data:  0.8928<br>Iteration 3 : main_model accuracy on all test data:  0.9073<br>Iteration 4 : main_model accuracy on all test data:  0.9150<br>Iteration 5 : main_model accuracy on all test data:  0.9209<br>Iteration 6 : main_model accuracy on all test data:  0.9273<br>Iteration 7 : main_model accuracy on all test data:  0.9321<br>Iteration 8 : main_model accuracy on all test data:  0.9358<br>Iteration 9 : main_model accuracy on all test data:  0.9382<br>Iteration 10 : main_model accuracy on all test data:  0.9411<br>Iteration 11 : main_model accuracy on all test data:  0.9431</pre><p>The accuracy of the centralized model was calculated as approximately 98%. The accuracy of the main model obtained by FedAvg method started from 85% and improved to 94%. In this case, we can say that although the main model obtained by FedAvg method was trained without seeing the data, its performance cannot be underestimated.</p><p>You can visit the <a href="https://github.com/eceisik/fl_public/blob/master/fedavg_mnist_iid.ipynb">https://github.com/eceisik/fl_public/blob/master/fedavg_mnist_iid.ipynb</a> to see the full implementation.</p><p>*You can visit the github page.</p><blockquote>[1] J. Konečný, H. B. McMahan, D. Ramage, and P. Richtárik, “Federated Optimization: Distributed Machine Learning for On-Device Intelligence,” pp. 1–38, 2016.</blockquote><blockquote>[2] H. B. Mcmahan and D. Ramage, “Communication-Efficient Learning of Deep Networks from Decentralized Data,” vol. 54, 2017.</blockquote><blockquote>[3] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. “Gradient-based learning applied to document recognition.” Proceedings of the IEEE, 86(11):2278–2324, November 1998.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90187c9c9577" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/federated-learning-a-simple-implementation-of-fedavg-federated-averaging-with-pytorch-90187c9c9577">Federated Learning: A Simple Implementation of FedAvg (Federated Averaging) with PyTorch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>