<?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 Shiro Matsumoto on Medium]]></title>
        <description><![CDATA[Stories by Shiro Matsumoto on Medium]]></description>
        <link>https://medium.com/@shrmtmt?source=rss-33149ffe183c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fc825jxmA25wvH9BbC9UMQ.png</url>
            <title>Stories by Shiro Matsumoto on Medium</title>
            <link>https://medium.com/@shrmtmt?source=rss-33149ffe183c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:36:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shrmtmt/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[Understanding the Skewed Word Distribution in ChatGPT-Generated Texts]]></title>
            <link>https://shrmtmt.medium.com/understanding-the-skewed-word-distribution-in-chatgpt-generated-texts-41b5959fd599?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/41b5959fd599</guid>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[embedding]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 22:30:02 GMT</pubDate>
            <atom:updated>2024-07-18T19:19:58.627Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article explores a thought experiment to understand why words in documents generated by ChatGPT show a skewed distribution. No definitive answers are provided, but two hypotheses are considered.</h4><h3>Word Appearance Skewness by ChatGPT</h3><p>Documents generated by ChatGPT exhibit several peculiarities, one of which is a skewed selection of words. Some examples and further readings include:</p><ul><li><a href="https://medium.com/@jordan_gibbs/which-words-does-chatgpt-use-the-most-7c9ff02416a8">Which words does ChatGPT use the most?</a></li><li><a href="https://arxiv.org/html/2404.08627v1">Is ChatGPT Transforming Academics’ Writing Style?</a></li><li><a href="https://www.medrxiv.org/content/10.1101/2024.05.14.24307373v1">Delving into PubMed Records: Some Terms in Medical Writing Have Drastically Changed after the Arrival of ChatGPT</a></li></ul><h4>Hypotheses</h4><ol><li><strong>Hypothesis 1: frequently occurring words are tokenized as a single word by tokenization*¹</strong></li><li><strong>Hypothesis 2: The Voronoi hypervolume*² in embedding frequent words is large.</strong></li></ol><p>We will examine these hypotheses by exploring the concepts of tokens and embeddings.</p><h3>Tokens and embedding</h3><h4>Overview of ChatGPT’s Execution</h4><p>The following is an overview of ChatGPT’s execution.</p><ol><li>Receiving Input:<br>When a user provides input, the text is sent to the model.</li><li>Tokenization*¹:<br>The input text is split into “tokens”, which can be words, sub-words, or even individual letters. (examples later)</li><li>Encoding:<br>The tokenized input is converted into numerical vectors (embeddings) that the model can process. (examples later)</li><li>Transformer model processing:<br>The encoded input is processed by the transformer’s layers, which use attention mechanisms to generate appropriate responses.</li><li>Decoding:<br>The final layer’s output generates a probability distribution for the next token, from which the model selects the most probable token.</li><li>Text generation:<br>The selected tokens are combined to form natural language sentences.</li><li>Output Reply:<br>The generated text is presented to the user as a response.</li></ol><h3>Tokenization Examples</h3><p>Let’s examine how ChatGPT tokenizes some frequently used words. The following examples show the tokenization results for the `o200k_base` tokenizer used in ChatGPT-4 and the `cl100k_base` tokenizer used in ChatGPT-4 and ChatGPT-3.5turbo. (The 25 words up to “kaleidoscopic” are the words listed in <a href="https://medium.com/@jordan_gibbs/which-words-does-chatgpt-use-the-most-7c9ff02416a8">the article</a>, and the 10 words after “realm” are the words listed in <a href="https://www.medrxiv.org/content/10.1101/2024.05.14.24307373v1">the preprint paper</a>.)</p><h4>Tokenizer: “o200k<em>_base” in </em>ChatGPT4o</h4><pre>&#39; reimagined&#39; is split into tokens: [&#39; re&#39;, &#39;imag&#39;, &#39;ined&#39;]<br>&#39; reimagine&#39; is split into tokens: [&#39; re&#39;, &#39;im&#39;, &#39;agine&#39;]<br>&#39; bioluminescent&#39; is split into tokens: [&#39; bi&#39;, &#39;ol&#39;, &#39;um&#39;, &#39;ines&#39;, &#39;cent&#39;]<br>&#39; verdant&#39; is split into tokens: [&#39; verd&#39;, &#39;ant&#39;]<br>&#39; graphene&#39; is split into tokens: [&#39; graphene&#39;]<br>&#39; bustling&#39; is split into tokens: [&#39; bustling&#39;]<br>&#39; cannot&#39; is split into tokens: [&#39; cannot&#39;]<br>&#39; delved&#39; is split into tokens: [&#39; del&#39;, &#39;ved&#39;]<br>&#39; twinkled&#39; is split into tokens: [&#39; tw&#39;, &#39;ink&#39;, &#39;led&#39;]<br>&#39; tirelessly&#39; is split into tokens: [&#39; tirelessly&#39;]<br>&#39; intertwines&#39; is split into tokens: [&#39; intertw&#39;, &#39;ines&#39;]<br>&#39; transcended&#39; is split into tokens: [&#39; transc&#39;, &#39;ended&#39;]<br>&#39; repurposed&#39; is split into tokens: [&#39; rep&#39;, &#39;ur&#39;, &#39;posed&#39;]<br>&#39; thrived&#39; is split into tokens: [&#39; thr&#39;, &#39;ived&#39;]<br>&#39; marveled&#39; is split into tokens: [&#39; mar&#39;, &#39;ve&#39;, &#39;led&#39;]<br>&#39; subtlest&#39; is split into tokens: [&#39; sub&#39;, &#39;tl&#39;, &#39;est&#39;]<br>&#39; interconnectedness&#39; is split into tokens: [&#39; interconnected&#39;, &#39;ness&#39;]<br>&#39; intertwine&#39; is split into tokens: [&#39; intertw&#39;, &#39;ine&#39;]<br>&#39; inclusivity&#39; is split into tokens: [&#39; inclus&#39;, &#39;ivity&#39;]<br>&#39; orchestrates&#39; is split into tokens: [&#39; orchestr&#39;, &#39;ates&#39;]<br>&#39; revolutionized&#39; is split into tokens: [&#39; revolution&#39;, &#39;ized&#39;]<br>&#39; intricate&#39; is split into tokens: [&#39; intricate&#39;]<br>&#39; tapestry&#39; is split into tokens: [&#39; tapestry&#39;]<br>&#39; expanse&#39; is split into tokens: [&#39; exp&#39;, &#39;anse&#39;]<br>&#39; kaleidoscopic&#39; is split into tokens: [&#39; kale&#39;, &#39;idos&#39;, &#39;c&#39;, &#39;opic&#39;]<br>---------------------------------------------------------------------------<br>&#39; realm&#39; is split into tokens: [&#39; realm&#39;]<br>&#39; impressively&#39; is split into tokens: [&#39; impress&#39;, &#39;ively&#39;]<br>&#39; symphony&#39; is split into tokens: [&#39; sym&#39;, &#39;phony&#39;]<br>&#39; tapestry&#39; is split into tokens: [&#39; tapestry&#39;]<br>&#39; intricate&#39; is split into tokens: [&#39; intricate&#39;]<br>&#39; showcase&#39; is split into tokens: [&#39; showcase&#39;]<br>&#39; commendable&#39; is split into tokens: [&#39; commend&#39;, &#39;able&#39;]<br>&#39; meticulous&#39; is split into tokens: [&#39; meticulous&#39;]<br>&#39; underscore&#39; is split into tokens: [&#39; underscore&#39;]<br>&#39; delve&#39; is split into tokens: [&#39; delve&#39;]</pre><h4>Tokenizer: “cl100k_base” in ChatGPT-4 and ChatGPT-3.5turbo,</h4><pre>&#39; reimagined&#39; is split into tokens: [&#39; re&#39;, &#39;imag&#39;, &#39;ined&#39;]<br>&#39; reimagine&#39; is split into tokens: [&#39; reim&#39;, &#39;agine&#39;]<br>&#39; bioluminescent&#39; is split into tokens: [&#39; bi&#39;, &#39;olum&#39;, &#39;ines&#39;, &#39;cent&#39;]<br>&#39; verdant&#39; is split into tokens: [&#39; verd&#39;, &#39;ant&#39;]<br>&#39; graphene&#39; is split into tokens: [&#39; graphene&#39;]<br>&#39; bustling&#39; is split into tokens: [&#39; bustling&#39;]<br>&#39; cannot&#39; is split into tokens: [&#39; cannot&#39;]<br>&#39; delved&#39; is split into tokens: [&#39; del&#39;, &#39;ved&#39;]<br>&#39; twinkled&#39; is split into tokens: [&#39; twink&#39;, &#39;led&#39;]<br>&#39; tirelessly&#39; is split into tokens: [&#39; tirelessly&#39;]<br>&#39; intertwines&#39; is split into tokens: [&#39; intertw&#39;, &#39;ines&#39;]<br>&#39; transcended&#39; is split into tokens: [&#39; transc&#39;, &#39;ended&#39;]<br>&#39; repurposed&#39; is split into tokens: [&#39; rep&#39;, &#39;ur&#39;, &#39;posed&#39;]<br>&#39; thrived&#39; is split into tokens: [&#39; thr&#39;, &#39;ived&#39;]<br>&#39; marveled&#39; is split into tokens: [&#39; mar&#39;, &#39;veled&#39;]<br>&#39; subtlest&#39; is split into tokens: [&#39; subtle&#39;, &#39;st&#39;]<br>&#39; interconnectedness&#39; is split into tokens: [&#39; interconnected&#39;, &#39;ness&#39;]<br>&#39; intertwine&#39; is split into tokens: [&#39; intertw&#39;, &#39;ine&#39;]<br>&#39; inclusivity&#39; is split into tokens: [&#39; inclus&#39;, &#39;ivity&#39;]<br>&#39; orchestrates&#39; is split into tokens: [&#39; orchestr&#39;, &#39;ates&#39;]<br>&#39; revolutionized&#39; is split into tokens: [&#39; revolution&#39;, &#39;ized&#39;]<br>&#39; intricate&#39; is split into tokens: [&#39; intricate&#39;]<br>&#39; tapestry&#39; is split into tokens: [&#39; tape&#39;, &#39;stry&#39;]<br>&#39; expanse&#39; is split into tokens: [&#39; ex&#39;, &#39;panse&#39;]<br>&#39; kaleidoscopic&#39; is split into tokens: [&#39; kale&#39;, &#39;idos&#39;, &#39;c&#39;, &#39;opic&#39;]<br>---------------------------------------------------------------------------<br>&#39; realm&#39; is split into tokens: [&#39; realm&#39;]<br>&#39; impressively&#39; is split into tokens: [&#39; impress&#39;, &#39;ively&#39;]<br>&#39; symphony&#39; is split into tokens: [&#39; sym&#39;, &#39;phony&#39;]<br>&#39; tapestry&#39; is split into tokens: [&#39; tape&#39;, &#39;stry&#39;]<br>&#39; intricate&#39; is split into tokens: [&#39; intricate&#39;]<br>&#39; showcase&#39; is split into tokens: [&#39; showcase&#39;]<br>&#39; commendable&#39; is split into tokens: [&#39; commend&#39;, &#39;able&#39;]<br>&#39; meticulous&#39; is split into tokens: [&#39; meticulous&#39;]<br>&#39; underscore&#39; is split into tokens: [&#39; underscore&#39;]<br>&#39; delve&#39; is split into tokens: [&#39; delve&#39;]</pre><h4>Analysis of Tokenization Results</h4><p>Contrary to the initial hypothesis, many frequently used words are split into two or more tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*F5Rin7jjKbrG4MtKnrRA7w.png" /><figcaption>Number of words represented by a single token (by author)</figcaption></figure><h3>Voronoi Hypervolume<strong>*²</strong> and GPT-2 Embedding Distribution</h3><h4>Voronoi partitioning</h4><p>A Voronoi partition is a geometric construction that divides a space based on a set of points. Each region (Voronoi cell) contains all locations closest to a specific point. The boundaries of these cells are defined by perpendicular bisectors between points.</p><h4>Embedded distribution of GPT-2</h4><p>Although embeddings for ChatGPT-3.5 and ChatGPT-4 are not publicly available, we can use <a href="https://github.com/openai/gpt-2/tree/master">GPT-2 embeddings</a> for discussion. GPT-2 uses about 50,000 tokens, each embedded in a 768-dimensional vector. By examining the scatter plot of the first and second dimensions, we can see a normally distributed pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*OYelMPG0OA3jMvvlxLOFQA.png" /></figure><p>It just so happens that the first and second dimensions appear to be normally distributed and independent of each other.</p><p>First of all, we will restrict our discussion to the range of 0 to 0.01 for the first and second dimensions. The following figure shows a scatter plot of the first and second dimensions in the range of 0 to 0.01.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YX7YWAurG56ALTQxmGM8hA.png" /></figure><p>If we perform the Voronoi partitioning on this figure, we get this. The convex polygon composed of orange lines drawn around each token is a Voronoi cell. The nearest token from each point in the Voronoi cell is the token shown in the cell. The number of tokens = the number of Voronoi cells.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Hw-5aLySAkLibRTu3vePxg.png" /></figure><p>The area occupied by each Voronoi cell is added. This area is called the Voronoi area (Voronoi volume, or Voronoi hypervolume.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*oQd9zo6TFcrm1F9ooUBAnw.png" /></figure><p>As you can see from this figure, there is a difference in the area of each token as its nearest neighbor. Hypothesis 2 was that the larger this area, the greater the probability of selection of a token (Step 5 decoding in the overview of ChatGPT execution). In the actual decoding step, tokens are not necessarily selected for nearest neighbor, and tokens are selected under randomness due to temperature parameters, but the tendency for tokens with larger areas to be selected more frequently should hold even after taking randomness into account.</p><h3>Monte Carlo Method for Estimating Hypervolume</h3><p>Since calculating the Voronoi hypervolume in 768-dimensional space is computationally infeasible, we use the Monte Carlo method. By generating random coordinates with the same mean, variance, and covariance as the 50k tokens, we approximate the hypervolume.</p><p>First, we check to see if we have successfully generated random coordinates with the same mean, variance, and covariance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQGYkt-PXkUE9xF-Jn3v5w.png" /><figcaption>Means of 50k tokens and randomly generated coordinates in each dimension</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyGQ9c6WXKY34arvl3-fXg.png" /><figcaption>Standard deviations of 50k tokens and randomly generated coordinates in each dimension</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgO5LeO4l6AghAAU49onfQ.png" /><figcaption>Distribution of the difference between the inter-dimensional correlation of 50k tokens and the inter-dimensional correlation of the randomly generated coordinates</figcaption></figure><p>It seems to have been generated successfully, generate 1,000 random coordinates and count up the number of nearest neighbor tokens, and repeat this 1,000 times to generate a total of 1 million Monte Carlo samples to find the volume of the nearest neighbor hyperspace for each token in a pseudo manner.</p><p>The result is shown in the figure below. The upper 100 tokens with the largest hypervolume. (The red dotted line is the expected frequency if the hypervolume of each token were identical.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GH0NdowO20kRp2Mq4f3V1w.png" /></figure><p>Many of the tokens with large hypervolumes are divided into sub-words, but “promoter, disco, shaman, agents, rely, intra, cricket, loosen, aura, Elect” can be read as tokens that can be formed into words even with a single token.</p><p>The lower 100 tokens with the smallest hypervolume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFnDzPfTIbvD6I-J3tiDKg.png" /></figure><p>The words “Fundamental, iodine, retaliate, CHECK, Forth, Logged, sorely, Diver, toddlers, GPIO, toolbar, PRESIDENT, SHALL, hotly, scoreboard, snipers” were never chosen as nearest neighbor tokens in the total Monte Carlo sample of one million.</p><h3>Conclusion</h3><p>The second hypothesis, that the Voronoi hypervolume of frequent words in embeddings is large, appears valid for GPT-2. While independent random sampling cannot approximate the model’s token selection process, this experiment helps understand the tendency in word occurrence. Further research could involve analyzing the embedding distributions of newer models like ChatGPT-3.5 and ChatGPT-4, should their embeddings become available. Additionally, exploring other factors that contribute to word selection in generated texts, such as syntactic and semantic coherence, could provide a more comprehensive understanding of the model’s behavior. I hope this article provides some insights into the nuances of word distribution in AI-generated texts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41b5959fd599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Monte Carlo Dropout]]></title>
            <link>https://shrmtmt.medium.com/beyond-average-predictions-embracing-variability-with-heteroscedastic-loss-in-deep-learning-f098244cad6f?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f098244cad6f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[dropout]]></category>
            <category><![CDATA[heteroscedasticity]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[uncertainty]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 22:11:37 GMT</pubDate>
            <atom:updated>2024-03-24T17:30:01.761Z</atom:updated>
            <content:encoded><![CDATA[<h4>Advancing Uncertainty Estimation</h4><h3>Dropout as Uncertainty Estimation</h3><p>Monte Carlo Dropout is one of the methods used in deep learning to estimate model uncertainty. Normal dropout is used to prevent overlearning and improve the generalization performance of a model by randomly disabling (“dropping out”) some neurons during neural network training.</p><p>In Monte Carlo dropout, this dropout technique is also applied during the inference (testing) phase. Specifically, multiple inferences are performed, each using a different dropout pattern. Each inference corresponds to a sample in the Monte Carlo method, and the uncertainty of the model&#39;s predictions is evaluated through statistical analysis of these inference results (e.g., calculation of means and variances).</p><p>This technique is particularly useful for quantifying the level of confidence in the predictions output by a deep learning model and helps to understand how confident the model is in its predictions. Monte Carlo dropout, also interpreted as a form of Bayesian approximation, has attracted attention as a means of effectively estimating model uncertainty.</p><p>This approach allows us to represent uncertainty in deep learning without incurring much computational cost or sacrificing accuracy. However, applying dropout in inference as well, simply treating multiple inferences as Monte Carlo samples and treating estimates as probability distributions rather than point estimates, may fall short of what is being sought. Another way to cover the insufficiency is to adopt Heteroscedastic loss. Let’s see what exactly this means below.</p><h4>Simple Implementation with simple toy data</h4><p>Some examples. The code will be shown together later, but the common outline is</p><ul><li>2 hidden layers, 100 nodes each</li><li>Dropout rate of 0.2 for each layers</li><li>1000 epochs</li><li>1000 training data</li><li>Loss function is MSE</li><li>Dropout rate at inference is 0.2</li><li>Inference obtains the mean and variance of 50 trials</li></ul><p>First, if the training data is a sine function with an open center and uniform noise, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*2j_VC84JxCtDP2UFkPkxPQ.png" /></figure><p>Uncertainty is greater in open centers, but the difference is small.</p><p>Next, an example of adding a uniform random of 1-abs(x) on the line y=x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*fHV-jX_3Qjmh6u7xP8g9zg.png" /></figure><p>Uncertainty is not increasing near 0.</p><p>Next to that, if an open center is near 0 in the above example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*F6znMWcm-cC18uD6XtpAYA.png" /></figure><p>As in the previous example, uncertainty does not increase near zero.</p><p>As a final example, with open centers with a uniform random number of width 4(abs(x)-0.5) added to the line y=x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*v3IKW3Y0pFbUWdlxu3wzew.png" /></figure><p>As in the previous two examples, uncertainty does not increase near zero.</p><p>The uncertainty obtained here appears to be closer to the <strong>confidence interval</strong> (the range of values estimated to contain the true value of the parameter) in frequentist terms than to the <strong>prediction interval</strong> (the range of values estimated to contain the observed sample values) in frequentist terms. So how can we get something closer to a prediction interval?</p><h4>Epistemic uncertainty, Aleatoric uncertainty</h4><p>In statistics, various concepts describe and quantify uncertainty and variability in data and models. Among these, <strong>confidence intervals</strong>, <strong>prediction intervals</strong>, <strong>credible intervals</strong>, <strong>aleatoric uncertainty</strong>, and <strong>epistemic uncertainty</strong> are key terms with distinct meanings and applications. To be sure, let me summarize them.</p><p>A <strong>confidence interval</strong>, a concept from frequentist statistics, provides a range of values within which we expect a certain parameter (like a population mean) to fall. This range is constructed so that if the same data collection and analysis were repeated many times, the true parameter value would be within this interval in a specified percentage of these replications (e.g., 95%). Confidence intervals thus reflect the reliability of the estimation process rather than the probability of a specific parameter value.</p><p><strong>Prediction intervals</strong>, also rooted in frequentist statistics, offer a range where future observations or data points are likely to occur. Unlike confidence intervals that focus on parameter estimates, prediction intervals account for the variability in individual data points, providing a more direct sense of the expected spread of future observations.</p><p>In Bayesian statistics, the <strong>credible interval</strong> is analogous to the <strong>confidence interval</strong>. However, it represents the range within which a parameter lies with a certain probability based on the posterior distribution. This interval directly interprets the probability of the parameter values, reflecting the Bayesian approach’s inherent probabilistic nature.</p><p><strong>Epistemic uncertainty</strong> arises from a lack of knowledge or information about the system being modeled. It’s the uncertainty in the model parameters or structure reflecting our ignorance or the imperfection of our understanding. In Bayesian terms, this is often represented by the spread in the posterior distribution of parameters and can be reduced with more data or improved modeling. In brief, the <strong>credit interval</strong> can be interpreted as a quantitative expression of <strong>epistemic uncertainty</strong>. The wider the credit interval, the greater the uncertainty about that parameter.</p><p><strong>Aleatoric uncertainty</strong>, often discussed in the context of machine learning and Bayesian statistics, pertains to the inherent randomness or variability in a system or process. This uncertainty embedded in the data (like the noise in measurements) is irreducible and often quantified using probabilistic models.</p><p>In light of these terms, it can be reiterated that what is desirable is a method or approach that allows us to know not only <strong>epistemic uncertainty</strong> but also <strong>aleatoric uncertainty</strong>. This is made possible by applying <strong>Heteroscedastic loss</strong> to MC Dropout.</p><p><strong>(Confidence intervals</strong> and <strong>epistemic uncertainty</strong>, and <strong>predictive intervals</strong> and <strong>alethic uncertainty,</strong> are concepts that are sometimes related, but they do not correspond directly to each other. Each is a concept used to capture a different kind of uncertainty or statistical characteristic.)</p><h4>Heteroscedasticity and Heteroscedastic loss</h4><p>Heteroscedastic loss is a function used for data with heterogeneous (heteroscedastic) variance. Heteroscedastic variance means that the errors (or noise) at different points in the data set are different. This concept applies when all data points do not have the same amount of uncertainty or noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9UV_zbtPY-x_bNMRyEBkQ.png" /></figure><p>In ordinary regression problems, we assume uniform (homoscedastic) variance and assume that the error is the same at all data points. However, in many real-world problems, the uncertainty of the output for different input values may differ. Heteroscedastic loss is used in such cases. Specifically, the heteroscedastic loss function considers both the mean (mean) of the model’s output prediction and the uncertainty (variance or standard deviation) of that prediction. This loss function evaluates how close the forecast&#39;s mean is to the true value and how appropriate the uncertainty of the forecast is.</p><p>The general form of the loss calculation is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*euE8CIi99njFKasdhpef0g.png" /></figure><p>Here, the first term is the forecast error normalized by the variance, and the second term is used to penalize the forecast uncertainty. When the variance is large (i.e., when uncertainty is high), the first term is smaller, but at the same time, the penalty in the second term increases. This balance ensures that the model properly accounts for forecast accuracy and uncertainty.</p><p>Heteroscedastic loss is especially useful when forecast uncertainty needs to be modeled and when different noise levels are present at different data points.</p><h3>Applying Heteroscedastic loss using the same toy data</h3><p>The method will be explained later, but here are the results of an experiment on the same toy data to see what kind of results can be obtained by using heteroscedastic loss.</p><p>First, if the training data is a sine function with an open center and uniform noise, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*A0uM2EtrONWKqL3fJnybuw.png" /></figure><p>Uncertainty is decomposed into <strong>epistemic </strong>and <strong>aleatoric uncertainty</strong>, with aleatoric uncertainty being larger in the range of x = -0.5 to 0.5, where there is no sample.</p><p>Next, an example of adding a uniform random of 1-abs(x) on the line y=x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*P7xZccAOMq_LqPYvGaTtTQ.png" /></figure><p>The closer x is to 0, the larger the aleatoric uncertainty is, corresponding to the larger sample variance.</p><p>Next to that, if an open center is near 0 in the above example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*gfg9p4iwh5KPt98odNiV6A.png" /></figure><p>As in the previous example, the closer x is to 0, the greater the aleatoric uncertainty. However, in this case, there are no samples in the range of x = -0.5 to 0.5. It seems that the aleatoric uncertainty for x = -0.5 to 0.5 can be estimated by capturing the tendency for the sample variance to increase as x approaches -1.0 to -0.5 and x approaches 1.0 to 0.5.</p><p>As a final example, with open centers with a uniform random number of width 4(abs(x)-0.5) added to the line y=x</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*u2pEhu1EOSz8m3m9ycZeDg.png" /></figure><p>Unlike the previous example, the aleatoric uncertainty is smaller in the range of x = -0.5 to 0.5, where no sample exists. It seems that the aleatoric uncertainty for x = -0.5 to 0.5 can be estimated by capturing the tendency for the sample variance to decrease as x approaches -1.0 to -0.5 and x approaches 1.0 to 0.5.</p><p>Let’s look at how this is possible, along with the code.</p><h4>Implementation of Heteroscedastic loss</h4><blockquote>The following code was created with reference to <a href="https://github.com/LukasRinder/bayesian-neural-networks/blob/main/toy_regression_mc_dropout.py">toy_regression_mc_dropout.py by Lukas Rinder</a>. The original code uses tensorflow, but I rewrote it to work with pytorch. I am responsible for any mistakes in the code, but I cannot be held responsible for any damage caused by using this code.</blockquote><p>First, the core, MonteCarloDropoutModel class, and the code for the function heteroscedastic_loss are shown.</p><pre>import numpy as np<br>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br>import matplotlib.pyplot as plt<br>from torch.optim import Adam<br><br>class MonteCarloDropoutModel(nn.Module):<br>    def __init__(self, loss_type=&quot;heteroscedastic&quot;):<br>        super(MonteCarloDropoutModel, self).__init__()<br>        self.loss_type = loss_type<br><br>        self.fc1 = nn.Linear(1, 100)<br>        self.dropout1 = nn.Dropout(p=0.2)<br>        self.fc2 = nn.Linear(100, 100)<br>        self.dropout2 = nn.Dropout(p=0.2)<br><br>        self.mean_layer = nn.Linear(100, 1)<br>        if loss_type == &quot;heteroscedastic&quot;:<br>            self.var_layer = nn.Linear(100, 1)<br><br>    def forward(self, x):<br>        x = F.relu(self.fc1(x))<br>        x = self.dropout1(x)<br>        x = F.relu(self.fc2(x))<br>        x = self.dropout2(x)<br><br>        mean = self.mean_layer(x)<br>        if self.loss_type == &quot;heteroscedastic&quot;:<br>            log_var = self.var_layer(x)<br>            return mean, log_var<br><br>        return mean<br><br>def mse_loss(model, x, y_true):<br>    y_pred = model(x)<br>    mse = F.mse_loss(y_pred, y_true)<br>    return mse<br><br>def heteroscedastic_loss(model, x, y_true):<br>    mean, log_var = model(x)<br>    precision = torch.exp(-log_var)<br>    mse = torch.mean(0.5 * precision * (y_true - mean)**2 + log_var)<br>    return mse</pre><p>To calculate heteroscedastic loss, an output layer has been added to the MonteCarloDropoutModel class that outputs log_var. The code for the function heteroscedastic_loss is implemented as described above.</p><p>Next are the data generation, training, and execution sections. There is nothing special that needs explanation.</p><pre>def generate_data(data_type):<br>    if data_type == 0:<br>        x = np.concatenate([np.linspace(-1, -.5, 500), np.linspace(.5, 1, 500)])<br>        noise = np.random.uniform(-1., 1., size=x.shape)<br>        y = np.sin(x * np.pi) + noise * .25<br>    elif data_type == 1:<br>        x = np.linspace(-1., 1., 1000)<br>        noise = np.random.uniform(-1., 1., size=x.shape)<br>        y = x + 2 * (1. - np.abs(x)) * noise<br>    elif data_type == 2:<br>        x = np.concatenate([np.linspace(-1, -.5, 500), np.linspace(.5, 1, 500)])<br>        noise = np.random.uniform(-1., 1., size=x.shape)<br>        y = x + 2 * (1. - np.abs(x)) * noise<br>    elif data_type == 3:<br>        x = np.concatenate([np.linspace(-1, -.5, 500), np.linspace(.5, 1, 500)])<br>        noise = np.random.uniform(-1., 1., size=x.shape)<br>        y = x + 2 * (np.abs(x) - .5) * noise<br>    else:<br>        raise ValueError(f&quot;Undefined data type: {data_type}&quot;)<br><br>    return torch.tensor(x.reshape(-1, 1), dtype=torch.float32), <br>           torch.tensor(y.reshape(-1, 1), dtype=torch.float32)<br><br>def fit_model(model, x_train, y_train, epochs, learning_rate, loss_type):<br>    optimizer = Adam(model.parameters(), lr=learning_rate)<br>    for epoch in range(epochs):<br>        model.train()<br>        optimizer.zero_grad()<br><br>        if loss_type == &quot;mse&quot;:<br>            loss = mse_loss(model, x_train, y_train)<br>        elif loss_type == &quot;heteroscedastic&quot;:<br>            loss = heteroscedastic_loss(model, x_train, y_train)<br><br>        loss.backward()<br>        optimizer.step()<br><br>        if epoch % 100 == 0:<br>            print(f&quot;Epoch {epoch}, Loss: {loss.item()}&quot;)<br><br># Execute<br># data_type should be 0 to 3<br>data_type = 0<br>x_train, y_train = generate_data(data_type)<br><br># Choose either one<br>#loss_type=&quot;mse&quot;<br>loss_type=&quot;heteroscedastic&quot;<br>  <br>model = MonteCarloDropoutModel(loss_type)<br>fit_model(model, x_train, y_train, epochs=1000, learning_rate=1e-3, loss_type=loss_type)</pre><p>The next section is the graph plotting section. When applying heteroscedastic loss, the values are obtained as follows, respectively.</p><ul><li><strong>Estimated value</strong> = Monte Carlo sample mean of the estimated value</li><li><strong>Epistemic uncertainty</strong> = Standard deviation of the Monte Carlo sample of estimated value</li><li><strong>Aleatoric uncertainty</strong> = Square root of the mean of the Monte Carlo sample of variance estimates</li></ul><pre>def plot_predictions(model, x_train, y_train, x_lim, y_lim):<br>    # model.eval()<br>    x_test = torch.linspace(-x_lim, x_lim, 500).reshape(-1, 1)<br><br>    preds_mean = []<br>    preds_var = []<br>    n_repeats = 50<br>    for _ in range(n_repeats):<br>        with torch.no_grad():<br>            if model.loss_type == &quot;mse&quot;:<br>                preds_mean.append(model(x_test).numpy())<br>            elif model.loss_type == &quot;heteroscedastic&quot;:<br>                mean, log_var = model(x_test)<br>                preds_mean.append(mean.numpy())<br>                preds_var.append(log_var.exp().numpy())<br><br>    # plt.figure(figsize=[12, 4])<br>    fig, ax1 = plt.subplots(figsize=[8, 6])<br><br>    if model.loss_type == &quot;heteroscedastic&quot;:<br>        preds_mean = np.array(preds_mean).reshape(n_repeats, -1)<br>        preds_var = np.array(preds_var).reshape(n_repeats, -1)<br>        preds_mean_mean = preds_mean.mean(axis=0)<br>        preds_mean_std = preds_mean.std(axis=0)<br>        preds_var_mean = preds_var.mean(axis=0)<br><br>        ax1.plot(x_test.numpy(), preds_mean_mean, color=&#39;b&#39;, label=&#39;Predict Mean&#39;)<br>        ax1.fill_between(x_test.numpy().reshape(-1), preds_mean_mean - 2 * preds_mean_std, preds_mean_mean + 2 * preds_mean_std, alpha=0.25, color=&#39;b&#39;, label=&quot;Mean ± 2σ&quot;)<br>        ax1.scatter(x_train.numpy(), y_train.numpy(), c=&quot;r&quot;, label=&#39;Training data&#39;, alpha=0.1)<br>        ax1.set_ylim(-y_lim, y_lim)<br>        ax1.set_ylabel(&#39;Samples, Prediction&#39;, color=&#39;b&#39;)<br>        ax1.legend(loc=&#39;upper left&#39;)<br><br>        ax2 = ax1.twinx()<br>        ax2.plot(x_test.numpy(), preds_mean_std, color=&#39;m&#39;, label=&quot;Epistemic uncertainty&quot;)<br>        ax2.plot(x_test.numpy(), np.sqrt(preds_var_mean), color=&quot;g&quot;, label=&quot;Aleatoric uncertainty&quot;)<br>        ax2.set_ylim(0, y_lim/2)<br>        ax2.set_ylabel(&#39;Epistemic / Aleatoric uncertainty&#39;, color=&#39;k&#39;)<br>        ax2.legend(loc=&#39;upper right&#39;)<br><br>    elif model.loss_type == &quot;mse&quot;:<br>        preds_mean = np.array(preds_mean).reshape(n_repeats, -1)<br>        preds_mean_mean = preds_mean.mean(axis=0)<br>        preds_mean_std = preds_mean.std(axis=0)<br><br>        ax1.plot(x_test.numpy(), preds_mean_mean, color=&#39;b&#39;, label=&#39;Predict Mean&#39;)<br>        ax1.fill_between(x_test.numpy().reshape(-1), preds_mean_mean - 2 * preds_mean_std, preds_mean_mean + 2 * preds_mean_std, alpha=0.25, color=&#39;b&#39;, label=&quot;Mean ± 2σ&quot;)<br><br>        ax1.scatter(x_train.numpy(), y_train.numpy(), c=&quot;r&quot;, label=&#39;Training data&#39;, alpha=0.1)<br>        ax1.set_ylim(-y_lim, y_lim)<br>        ax1.set_ylabel(&#39;Samples, Prediction&#39;, color=&#39;b&#39;)<br>        ax1.legend(loc=&#39;upper left&#39;)<br><br>        ax2 = ax1.twinx()<br>        ax2.plot(x_test.numpy(), preds_mean_std, color=&#39;m&#39;, label=&quot;Uncertainty(σ)&quot;)<br>        ax2.set_ylim(0, y_lim/2)<br>        ax2.set_ylabel(&#39;Uncertainty&#39;, color=&#39;m&#39;)<br>        ax2.legend(loc=&#39;upper right&#39;)<br><br>        plt.legend()<br><br>    plt.tight_layout()<br><br>    plt.show()<br><br># Plot<br>plot_predictions(model, x_train, y_train, x_lim=1.5, y_lim=2.0)</pre><h3>Summary</h3><p>This article described a method to separate and estimate aleatoric and epistemic uncertainty by employing the Heteroscedastic loss as a loss function for Monte Carlo dropout. I hope this will be helpful in your estimation of uncertainty.</p><h3>References</h3><ul><li><a href="https://arxiv.org/pdf/1506.02142.pdf"><em>Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning</em></a></li><li><a href="https://www.cs.ox.ac.uk/people/yarin.gal/website/PDFs/Dropout_as_a_Bayesian_approximation.pdf"><em>Dropout as a Bayesian Approximation: Insights and Applications</em></a></li><li><a href="https://github.com/LukasRinder/bayesian-neural-networks/"><em>Uncertainty Estimation in the Context of Efficient Exploration</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f098244cad6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two OODs, Out of Domain and Out of Distribution]]></title>
            <link>https://shrmtmt.medium.com/the-difference-between-out-of-domain-and-out-of-distribution-f9c0f47a30b2?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9c0f47a30b2</guid>
            <category><![CDATA[generalizability]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 03:38:48 GMT</pubDate>
            <atom:updated>2024-02-07T14:16:48.336Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two concepts that are often confused</h4><p>In machine learning papers, the terms <strong>Out of Distribution</strong> and <strong>Out of Domain</strong> appear in uncertainty estimation or generalization discussions. Do these mean the same thing? Actually, they are different concepts under my understanding.</p><p>In the context of machine learning, <strong>Out of Domain</strong> is a concept paired with <strong>Applicable Domain,</strong> and <strong>Out of Distribution</strong> is a concept paired with <strong>In Distribution</strong>.</p><ol><li><strong>Applicable Domain</strong> and <strong>Out of Domain</strong><br> — <strong>Applicable Domain</strong><br>This term refers to the range or domain of data for which the model performs adequately for its intended purpose. This term broadly implies the characteristics and conditions of the data under which the model will function properly.<br> — <strong>Out of Domain</strong><br> This term refers to data outside the original domain or range for which the model was designed or trained. This could include different characteristics or different types of data, not just different distributions.</li><li><strong>In Distribution</strong> and <strong>Out of Distribution</strong><br> — <strong>In Distribution</strong><br> This term refers to data from the same distribution as the data set used when the model was trained. In other words, data with the types and characteristics of data that the model is familiar with.<br> — <strong>Out of Distribution</strong><br>This term refers to data from a distribution that is different from the distribution of the data the model saw during training. This means data that is unknown or anomalous to the model.</li></ol><p>In short, <strong>Out of Distribution</strong> and <strong>Out of Domain</strong> have in common that they refer to unusual data for which the model may not function properly. However, when the unusual data is “data outside the domain of the training data,” it is <strong>Out of Domain</strong>, and when it is “data outside the distribution of the training data,” it is <strong>Out of Distribution</strong>.</p><p>Let me elaborate on this a bit more. Within the <strong>Applicable Domain</strong>, there may be <strong>Out of Distribution</strong> samples. <strong>Applicable Domain</strong> refers to the intended applicability domain in which the model was designed or trained. However, not all data within this domain will have the same distribution as the model’s training data. Data that follow this different distribution are <strong>Out of Distribution</strong>. On the other hand, it is rare to find <strong>In Distribution</strong> data within an <strong>Out of Domain</strong>, and most of the time it will be <strong>Out of Distribution</strong> data.</p><p>Consider the case of model training with English text data. If the model is trained on an extremely large amount of English text, most of the English texts will be <strong>Applicable Domain</strong> and <strong>In Distribution</strong>. However, if you forgot to include contractions that are used only by a subset of the population (e.g., young people, gamers, etc.) in the training data set, those contractions will be <strong>Applicable Domain</strong> and <strong>Out of Domain</strong>. Also, since the training data is English text only, Japanese text must be <strong>Out of Domain</strong>. In addition, since the distributional characteristics of most Japanese texts are different from those of English texts, most Japanese texts are <strong>Out of Distribution</strong>.</p><p>As another example, a simple regression problem is shown as an image. Assuming that a regression line is obtained using the blue dots as training data, the center of the figure (light blue background) is the <strong>Applicable Domain</strong>, and the left and right sides are the <strong>Out of Domain</strong>. Some of the test (production) data are <strong>In Distribution</strong> and some are <strong>Out of Distribution</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*FoRz6g2SOQaRvolvnMGDaw.png" /></figure><p>When abbreviated as <strong>OOD</strong>, it is likely to mean <strong>Out of Distribution</strong>, but in some papers, it means <strong>Out of Domain</strong>. It is necessary to be careful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9c0f47a30b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quantile Loss in Neural Networks]]></title>
            <link>https://shrmtmt.medium.com/quantile-loss-in-neural-networks-6ea215fcee99?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea215fcee99</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[demand-forecasting]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Fri, 29 Dec 2023 16:04:40 GMT</pubDate>
            <atom:updated>2024-03-15T12:56:50.678Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementation, results tendency, and handling</h4><h3>The usefulness of quantile loss in demand forecasting</h3><p>When building a prediction model using machine learning in business, there are situations where you do not simply want to know “the predicted value (point prediction)” but rather “how likely the predicted value is to fall within a certain range (interval prediction).” The best example of this is demand forecasting. When demand forecasting is required, business needs cannot be met simply by forecasting the quantity most likely to sell. It is necessary to predict how much will sell when demand swings upwards and prepare inventory to meet that demand. For example, if you stock only the most likely amount of the demand forecast, you will be out of stock (roughly) one out of every two times and miss the opportunity to make a sale. If you have an inventory at the 95th percentile of the forecast (the value at which there is a 95% probability that demand will be less than or equal to this value), you can reduce the number of shortages to approximately once in 20 times.</p><p>Machine learning methods for obtaining such percentile values include <strong>quantile regression</strong> and various <strong>GBDT libraries</strong>.</p><p><strong>Quantile Regression</strong>:</p><ul><li>statsmodels:<a href="https://www.statsmodels.org/dev/generated/statsmodels.regression.quantile_regression.QuantReg.html">statsmodels.regression.quantile_regression.QuantReg</a>()</li></ul><p><strong>GBDT libraries</strong>:</p><ul><li>scikit-learn:<a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html">GradientBoostingRegressor</a>(loss=&#39;quantile, alpha=alpha)</li><li>LightGBM: <a href="https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html">LGBMRegressor</a>(objective=&#39;quantile&#39;, alpha=alpha)</li><li>XGBoost: <a href="https://xgboost.readthedocs.io/en/latest/python/examples/quantile_regression.html">XGBoostRegressor</a>(objective=&#39;reg:quantileerror&#39;, quantile_alpha=alpha) (version 2.0~)</li></ul><p>This article explains how to apply quantile loss on neural networks by defining it as a custom loss function and documenting its use.</p><h3>Why does a quantile loss provide a quantile?</h3><p>Before getting to the main topic, a simple example will be given of why quantile loss gives a quantile point. Those who understand these points may skip this section. Rather than rigorous proof, the discussion here will be intuitive, restricting to a few examples. The least squares method finds a for the data x₁, …, xₙ that minimizes the squared loss function <em>Σ(xᵢ — a)²</em>. In contrast, the quantile loss defines a check function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*FZzj4tpddKxVM0o1NEjKXg.png" /></figure><p>And uses it to find a way that minimizes the quantile loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*27rfAg8YpBqswn2WwH4xyQ.png" /></figure><p>First, I show that <em>a,</em> which minimizes quantile loss when τ=0.5, is the median value of x₁, …, xₙ. The following can be obtained from the definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*koWDj7GZFOe1rU9Uj5P2qg.png" /></figure><p>The absolute function cannot be differentiated at the point where it becomes 0, but by ignoring the possibility that |<em>xᵢ — a|</em>=0, it can be differentiated at other points by dividing the case as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*gtuLHYyhYtw4PjKZAVtyxg.png" /></figure><p>From this, the result of differentiating quantile loss by <em>a</em> is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*jSk8UhxCyxne4sQuDC38Hg.png" /></figure><p>Since the point of minimum quantile loss is the point at which the derivative is zero, the point at which “the number of <em>xᵢ</em> with <em>xᵢ&lt;a”</em> equals “the number of <em>xᵢ</em> with <em>xᵢ&gt;a,”</em> i.e., the median, would be the minimum point of quantile loss.</p><p>Next, let us look at the case where τ = 0.25 in the same way. The following can be obtained from the definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*J1JxEi1uJyZReO8cyH-Ieg.png" /></figure><p>Similarly, the differentiation can be obtained by separating the cases, and the following equation can be obtained in the same way as above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*lfzQVVDuS_7M__6zoUK4Qw.png" /></figure><p>The derivative of quantile point loss will be zero when the value of <em>a</em> satisfies “the number of <em>xᵢ</em> with <em>xᵢ&lt;a”</em>: “the number of <em>xᵢ</em> with <em>xᵢ&gt;a”</em> = 1:3. This means that <em>a</em> is the first quartile point (25th percentile point) of x₁, …, xₙ.</p><h3>Implementation of quantile loss with Pytorch</h3><p>Here is an example of defining quantile loss as a custom loss function using Pytorch.</p><pre>import torch<br># Define quantile loss function<br>def quantile_loss(preds, target, quantile):<br>    assert 0 &lt; quantile &lt; 1, &quot;Quantile should be in (0, 1) range&quot;<br>    errors = target - preds<br>    loss = torch.max((quantile - 1) * errors, quantile * errors)<br>    return torch.abs(loss).mean()</pre><p>An example of training with this custom loss function is shown below.</p><pre># Train model<br>for epoch in range(num_epochs):<br>    for batch_x, batch_y in dataloader:<br>        optimizer.zero_grad()<br>        outputs = model(batch_x)<br>        loss = quantile_loss(outputs, batch_y, quantile)<br>        loss.backward()<br>        optimizer.step()</pre><p>Let’s see if this defined custom loss function works as expected.</p><h3>Execution of quantile loss with Pytorch</h3><p>First, try generating a uniform random distribution (-5~5) for x and a normal random distribution for y proportional to the exponent of x, and see if you can predict the quantile point of y from x.</p><pre># Generate dummy data<br>num_samples = 10000<br>shape = (num_samples, 1)<br>torch.manual_seed(0)<br><br># x is uniform random from -5 to 5<br># y is random normal distribution * exp(scaled x)<br>x_tensor = torch.rand(shape) * 10 - 5<br>x_scaled = x_tensor / 5<br>y_tensor = torch.randn(shape) * torch.exp(x_scaled)<br><br># Convert values to NumPy array (for graphs)<br>x = x_tensor.numpy()<br>y = y_tensor.numpy()</pre><p>The network structure is simple: 64 nodes in the two intermediate layers + ReLUs in each layer. 100 epochs are used without any regularization or early-stoppping. The quartiles (percentile values) to be predicted are [0.500, 0.700, 0.950, 0.990, 0.995] in columns and [1, 4, 16, 64, 256] in rows for the batch size, for a total of 25 predictions. The ratio of instances below the predicted output value (red) out of 10,000 training data instances (blue) is noted in the figure as the “Actual” value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZ6gFWAzQl9ElAtadtGblg.png" /><figcaption>Image by author</figcaption></figure><p>The percentage of samples below the specified percentile value is generally close to the specified value, and the shape of the output quantile predictions is straightforward. If we can get results like this, we will likely get what we want.</p><p>Next, consider a slightly complex example where <strong>y=clip(x, -2, 2) + randn</strong>. Where <strong>clip(x, -2, 2)</strong> is the clip function (that restricts a value to a specified range. When a number is outside the given range, the function “clips” it to the nearest bounder; if you set the range as -2 to 2 and provide an input value of -5, the function will return -2; if you provide 10, it will return 2), and <strong>randn</strong> is a random number that follows a normal distribution. The network structure and other settings are the same as in the previous case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHTeqA9o143B_L49uM73wQ.png" /><figcaption>Image by author</figcaption></figure><p>As in the previous case, the percentages of the samples below the specified percentile value are generally close to the given value. However, the lower right of the 5x5 figure, the closer the given percentile value is to 1; the larger the batch size, the more the shape of the quantile predictions deviates from the shape of the training sample. The desirable shape of quantile predictions is always the shape of the red line in the upper left figure. It should move parallel upward as the specified percentile increases. However, as we move to the lower right of the figure, the red line of predictions has taken on a more linear shape, which is not a preferable result. The tendency to produce flat forecasts that do not follow demand fluctuations is hereafter referred to as <strong>flatten, flattened, </strong>or <strong>flattening</strong>. It should be noted that even in the bottom right figure, the percentage of the samples below the specified percentile value is 0.996, which is close to the given value of 0.995.</p><p>Let’s check it with a more complex shape for a better understanding. Here, we target <strong>y=2sin(x) + randn</strong>. Other settings are identical as in the preceding case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYDUmaetjJxv1cR3s3ufQQ.png" /><figcaption>Image by author</figcaption></figure><p>Again, the percentages of samples below the specified percentile values are generally close to the specified values. However, the shape of the quantile predictions deviates from the sinusoidal shape as one moves toward the lower right of the 5x5 figure. The red line of the predicted values becomes more linear in the lower right of the figure.</p><h4>Remark</h4><p>If the above demand fluctuations were weekly cycles, and if the product procurement cycle were also weekly, the flattening of the above figure would cause no problem at first glance. However, when the input data is not toy data but high-dimensional data used in practice, as in this case, it is difficult to predict in advance the nature of the irreducible errors (errors that occur even when the model is sufficiently generalized), and this flattening tendency is treated as undesirable.</p><h3>Detection, avoidance, and mitigation methods</h3><p>A summary of what we have seen so far is</p><ul><li>In neural networks, Quantile Loss can be defined as a custom loss function, which can be trained to minimize Quantile Loss.</li><li>If the set percentile values are close to 0 or 1, the training results do not follow the trend of the training data and are relatively flat.</li><li>This “flat training result” is noticeable when the batch size is large and is not seen when the batch size is small.</li></ul><p>In these toy data, input x was one-dimensional, and the relationship between input x and output y was clear in advance, so it was possible to determine whether the results obtained were <strong>flattened</strong> or not. Then, when the input x is high-dimensional, and the relationship between input x and output y is unknown, how can we determine whether the results obtained using Quantile Loss are “flattened” or not, and how can we “avoid flattening”?</p><h4>Detection Methods for “Flattening”</h4><p>One of the approaches to detect “flattening” is to calculate the 50th, 68th, and 95th percentile values together and check the relationship between these values, even if the final value to be obtained is the 99.5th percentile value. If the sample distribution follows a normal distribution with <em>μ</em> as the mean and <em>σ</em> as the standard deviation, the percentile values corresponding to 1<em>σ</em>, 2<em>σ</em>, and 3<em>σ</em> are obtained as follows, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*ddC4JYZ5a7oesDOO4e7FIg.png" /><figcaption>Image by author</figcaption></figure><p>Using this, if the ratios of the (84.13 percentile value - 50.00 percentile value), (97.72 percentile value - 50.00 percentile value), and (99.87 percentile value - 50.00 percentile value) deviate significantly from 1:2:3, we can determine that the deviating percentile values have <strong>flattened</strong>.</p><h4>Avoidance method for <strong>Flattening</strong></h4><p>The first approach of avoidance is to reduce the batch size, as seen in the experiment above. Large batch size will produce results where the ratio of samples below and above the prediction within one batch will balance to a specified percentile value, even with flat predictions. Smaller batch sizes avoid this problem and are less likely to produce flat predictions. On the other hand, reducing the batch size has disadvantages, such as unstable convergence and increased training time, making this option difficult to adopt.</p><p>The second approach of avoidance is to collect similar samples in the same batch instead of generating batches randomly. This avoids “balancing the ratio of samples below and above the predicted value within a batch to a specified percentile value. However, in the case of this toy sample, it is easy to collect similar samples because x is one-dimensional, but when x is a higher dimension, it is computationally expensive to define what a similar sample is appropriately and to collect similar samples.</p><h4>Mitigation method for “Flattening”</h4><p>On the other hand, a flattening mitigation method can be considered an extension of the flattening detection method. The following symbols are used in the following equation.</p><ul><li>p0: 50.00 percentile value</li><li>p1: 84.13 percentile value</li><li>p2: 97.72 percentile value</li><li>p3: 99.87 percentile value</li></ul><p>Using the above variables, an appropriate 99.87 percentile value can be obtained using the following flowchart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*Uwd7AgXv0OQrGDP7a2_tDA.png" /><figcaption>Image by author</figcaption></figure><h3>Simple Implementation for multiple quantile estimates</h3><p>In the previous example code for the custom loss function, a single percentile value was given, and the quantile loss was returned, but quantile value estimations corresponding to multiple percentile values are needed to implement detection and mitigation methods. To handle this, a single neural network is used to estimate multiple percentile values simultaneously, and the custom loss function is also changed to a function that returns the sum of quantile losses corresponding to the given multiple percentile values.</p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>import matplotlib.pyplot as plt<br>from torch.utils.data import TensorDataset, DataLoader<br><br>def multi_quantile_loss(preds, target, quantiles):<br>    assert isinstance(preds, torch.Tensor), &quot;Predictions must be a torch.Tensor&quot;<br>    assert isinstance(target, torch.Tensor), &quot;Target must be a torch.Tensor&quot;<br>    assert isinstance(quantiles, (list, torch.Tensor)), &quot;Quantiles must be a list or torch.Tensor&quot;<br>    assert len(preds.shape) == 2, &quot;Predictions must have 2 dimensions (batch_size, num_quantiles)&quot;<br>    assert preds.shape[1] == len(quantiles), f&quot;Number of predictions ({preds.shape[1]}) must match the number of quantiles ({len(quantiles)})&quot;<br>    assert preds.shape == target.shape, &quot;Shape of predictions must match shape of target&quot;<br><br>    if isinstance(quantiles, list):<br>        assert all(0 &lt; q &lt; 1 for q in quantiles), &quot;Quantiles should be in (0, 1) range&quot;<br>    else:<br>        assert torch.all((0 &lt; quantiles) &amp; (quantiles &lt; 1)), &quot;Quantiles should be in (0, 1) range&quot;<br><br>    # Convert quantiles to a tensor if it&#39;s a list<br>    if isinstance(quantiles, list):<br>        quantiles_tensor = torch.tensor(quantiles, device=preds.device).view(1, -1)<br>    else:<br>        quantiles_tensor = quantiles.view(1, -1)<br><br>    # Calculate errors<br>    errors = target - preds<br><br>    # Calculate losses for each quantile<br>    losses = torch.max((quantiles_tensor - 1) * errors, quantiles_tensor * errors)<br><br>    # Sum the losses and take the mean<br>    loss = torch.mean(torch.sum(losses, dim=1))<br><br>    return loss</pre><p>The structure of the neural network is also changed so that the number of nodes in the output layer can be specified.</p><pre># Define a simple neural network architecture<br>class QuantileNet(nn.Module):<br>    def __init__(self, output_size):<br>        super(QuantileNet, self).__init__()<br>        self.fc1 = nn.Linear(1, 64)  # Assuming input features are 1-dimensional<br>        self.relu1 = nn.ReLU()<br>        self.fc2 = nn.Linear(64, 64)<br>        self.relu2 = nn.ReLU()<br>        self.fc3 = nn.Linear(64, output_size)  # Output layer with output_size nodes<br><br>    def forward(self, x):<br>        x = self.relu1(self.fc1(x))<br>        x = self.relu2(self.fc2(x))<br>        x = self.fc3(x)<br>        return x</pre><p>The code for generating dummy data is almost the same.</p><pre># const<br>NUM_SAMPLES = 10000<br>SHAPE = (NUM_SAMPLES, 1)<br>QUANTILES = [0.5000, 0.8413, 0.9772, 0.9987]<br><br># Generate random tensor with values in the range -10 to 10<br>x_tensor = torch.rand(SHAPE) * 10 - 5<br>x_train = x_tensor / 5 # Fixed Scaling<br><br># Generating y values using torch operations instead of numpy<br>y = torch.sin(x_tensor) * 2 + torch.randn(NUM_SAMPLES, 1) * 1<br>y_train = y.type(torch.float32)<br>y_train_expanded = y_train.expand(-1, 4)</pre><p>The training part is almost the same. The batch size is 256.</p><pre># Instantiate the model for batch training<br>model = QuantileNet(output_size=len(QUANTILES))<br><br># Define optimizer for batch training<br>optimizer = optim.Adam(model.parameters(), lr=0.001)<br><br># Training parameters<br>epochs = 101<br>batch_size = 256<br><br># Convert the training data into a PyTorch Dataset<br>dataset = TensorDataset(x_train, y_train_expanded)<br><br># Create a DataLoader to handle batching and shuffling<br>dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)<br><br># Training loop with DataLoader<br>model.train()<br>for epoch in range(epochs):<br>    for x_batch, y_batch in dataloader:<br>        optimizer.zero_grad()<br>        preds = model(x_batch)<br>        loss = multi_quantile_loss(preds, y_batch, QUANTILES)<br>        loss.backward()<br>        optimizer.step()<br><br>    if epoch % 10 == 0:<br>        print(f&#39;Epoch {epoch}, Loss: {loss.item()}&#39;)</pre><p>Plot the results in a graph.</p><pre># Set the model to evaluation mode<br>model.eval()<br><br># Predict the quantiles<br>with torch.no_grad():<br>    predictions = model(x_train)<br><br># Convert the predictions and x_train to numpy for plotting<br>x_train_np = x_tensor.numpy().flatten()<br>y_train_np = y_train.numpy().flatten()<br>predictions_np = predictions.numpy()<br><br># Plotting<br>plt.figure(figsize=(12, 6))<br>plt.scatter(x_train_np, y_train_np, label=&#39;Actual Data&#39;, color=&#39;blue&#39;, marker=&#39;.&#39;, alpha=0.1)<br>plt.scatter(x_train_np, predictions_np[:, 0], label=f&#39;{QUANTILES[0]:.4f} Percentile&#39;, color=&#39;green&#39;, marker=&#39;.&#39;, alpha=0.1)<br>plt.scatter(x_train_np, predictions_np[:, 1], label=f&#39;{QUANTILES[1]:.4f} Percentile&#39;, color=&#39;red&#39;, marker=&#39;.&#39;, alpha=0.1)<br>plt.scatter(x_train_np, predictions_np[:, 2], label=f&#39;{QUANTILES[2]:.4f} Percentile&#39;, color=&#39;purple&#39;, marker=&#39;.&#39;, alpha=0.1)<br>plt.scatter(x_train_np, predictions_np[:, 3], label=f&#39;{QUANTILES[3]:.4f} Percentile&#39;, color=&#39;orange&#39;, marker=&#39;.&#39;, alpha=0.1)<br>plt.title(&#39;Predicted Quantiles vs. Actual Data&#39;)<br>plt.xlabel(&#39;x_train&#39;)<br>plt.ylabel(&#39;y_train and Predicted Quantiles&#39;)<br>plt.legend()<br>plt.show()</pre><p>Here is the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*5v9fH_MzbsKP1YjUB0AFRw.png" /><figcaption>Image by author</figcaption></figure><p>Whoa, this is unexpectedly good! What a nice surprise! The flattening of the 2σ and 3σ estimates has been suppressed. Why did this happen? Each percentile estimate was obtained simultaneously to detect and mitigate the flattening in a later step. However, this resulted in stopping the flattening of the 2σ and 3σ estimates. This is a pleasant byproduct of simultaneous estimation in a single network. Just to be sure, we also check the ratio of each forecast.</p><pre># Plot Differences <br>plt.figure(figsize=(12, 6))<br>plt.scatter(x_train_np, predictions_np[:, 3] - predictions_np[:, 0], label=f&#39;{QUANTILES[3]:.4f} Percentile - {QUANTILES[0]:.4f} Percentile&#39;, color=&#39;green&#39;, marker=&#39;.&#39;, alpha=0.5)<br>plt.scatter(x_train_np, predictions_np[:, 2] - predictions_np[:, 0], label=f&#39;{QUANTILES[2]:.4f} Percentile - {QUANTILES[0]:.4f} Percentile&#39;, color=&#39;red&#39;, marker=&#39;.&#39;, alpha=0.5)<br>plt.scatter(x_train_np, predictions_np[:, 1] - predictions_np[:, 0], label=f&#39;{QUANTILES[1]:.4f} Percentile - {QUANTILES[0]:.4f} Percentile&#39;, color=&#39;purple&#39;, marker=&#39;.&#39;, alpha=0.5)<br>plt.title(&#39;Differences in percentile estimates&#39;)<br>plt.xlabel(&#39;x_train&#39;)<br>plt.ylabel(&#39;differences&#39;)<br>plt.legend()<br>plt.show()</pre><p>Let see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*KwgOsATumPFp9HP8VgQ_wg.png" /><figcaption>Image by author</figcaption></figure><p>Each percentile estimate differences are close to 1, 2, and 3. It seems unnecessary to correct this by following the flowchart shown in the “Mitigation method for the Flattening” section. It should be noted, however, that <strong>calculating multiple quantile estimates simultaneously on a single network does not ensure that flattening will not occur.</strong> It is recommended to check whether or not flattening has occurred. If flattening has occurred, it should be assessed whether or not irreducible errors follow a normal distribution, and if they do, mitigation methods should be considered.</p><h3>Summary</h3><p>This article described quantile loss as a custom loss used in training neural networks, the tendency for predictions to flatten, and its detection and mitigation. It also described the custom loss function when multiple quantile estimates are estimated simultaneously in a single network and the pleasant byproducts of simultaneous estimation. I hope this article will help implement demand forecasting with neural networks.</p><p>In addition, I wrote <a href="https://medium.com/p/f098244cad6f">an article on how to estimate uncertainty in neural networks with Monte Carlo dropout</a>. I am sure you will enjoy this one as well.</p><p>Did you enjoy this? Click 👏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea215fcee99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Modern Factor Analysis]]></title>
            <link>https://shrmtmt.medium.com/mastering-modern-factor-analysis-17350e4e5f8d?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/17350e4e5f8d</guid>
            <category><![CDATA[factor-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[practical]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 04:46:32 GMT</pubDate>
            <atom:updated>2024-01-18T01:04:01.617Z</atom:updated>
            <content:encoded><![CDATA[<h4>Avoid being misled by the default settings of analysis software</h4><h3>Factor Analysis in Modern practice</h3><p>Factor analysis is an analysis method with a history of nearly 100 years, and there are many books and web articles dealing with it. As a result, old information and new information are mixed together, making it difficult to know what is the best practice at the present time. While there are many options for analysis, such as factor rotation methods, one of the difficulties in understanding the process is that it is unclear how to select each option. This article provides one guideline for how to proceed with the factor analysis. This article is <strong>not an introductory article</strong> to factor analysis. This is a reference document for those who have gained an image of factor analysis from the introductory article, but do not know how to proceed with the analysis.</p><h3>TL;DR</h3><h4>Determining the number of factors</h4><ul><li><strong>Don’t :</strong> Kaiser criterion (eigenvalue 1 or greater)</li><li><strong>Don’t : </strong>Scree criteria (visual inspection of scree plot)</li><li><strong>Don’t</strong> : Judging by cumulative contribution ratio</li><li><strong>Try</strong> : MAP criteria</li><li><strong>Try</strong> : Parallel analysis</li></ul><h4>Factor Extraction Methods (Estimation of Commonality)</h4><ul><li><strong>Don’t :</strong> PA (principal axes)</li><li><strong>Try 1st</strong> : ML (maximum likelihood)</li><li><strong>Try next</strong> : minres (minimum residual)</li></ul><h4>Factor Rotation Methods</h4><ul><li><strong>Don’t</strong> : Promax, Varimax</li><li><strong>Try</strong> : Independent Cluster Rotation, oblimin, geomin</li></ul><h3>Overall procedure for factor analysis</h3><p>A typical factor analysis procedure can be summarized as follows. In the following sections, I will discuss this step-by-step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*5TXIywxeggQZFt-iywJWbA.png" /><figcaption>Factor Analysis Procedure</figcaption></figure><h4>1. Data Ingestion and Proprocessing</h4><p>It seems that R is still more complete than Python for factor analysis. Here we use the <a href="https://cran.r-project.org/web/packages/psych/"><strong>psych</strong> library of R</a>.</p><pre># Install required packages<br>install.packages(&quot;psych&quot;)<br>install.packages(&quot;ggplot2&quot;)<br>install.packages(&quot;corrplot&quot;)<br><br># Load necessary libraries<br>library(psych)<br>library(ggplot2)<br>library(corrplot)<br><br># Load the dataset from the specified file path<br>data &lt;- read.csv(&quot;data.csv&quot;, header=TRUE, row.names=1)<br><br># histogram<br>par(mfrow = c(5, 5))<br>for (i in 1:ncol(data)) {<br>  hist(data[, i], main=colnames(data)[i], xlim=c(1, 10), xlab=NA, breaks=seq(1, 10, by=1), col=&quot;lightblue&quot;, border=&quot;black&quot;)<br>}<br>par(mfrow = c(1, 1))<br><br># correlation matrix<br>correlation_matrix &lt;- cor(data)<br>corrplot(correlation_matrix, method = &quot;color&quot;, is.corr = FALSE, tl.col = &quot;black&quot;, addCoef.col = &quot;black&quot;)</pre><p>The data to be used is <a href="https://statmodeling.stat.columbia.edu/2008/01/21/the_speeddating_1/">“The speed-dating data.”</a> However, we do not use the responses from speed dating itself, but only the results of the 10-point scale for interest in each hobby activity and self-assessment, respectively. Although the original data had multiple lines per person, this paper analyzes the intensity of interest in 17 leisure-like activities and self-assessment from five perspectives, for a total of 22 items, reorganized into one line of data per person, and samples with partially missing data were also excluded.<br>Each of the questions in the original questionnaire asked, “How interested are you in the following activities, on a scale of 1–10?”, “How do you think you measure up? Please rate your opinion of your own attributes, on a scale of 1–10 (be honest!)”<br>The data after exclusion is <a href="https://github.com/shrmtmt/step_by_step_EFA/blob/main/data.csv">here</a>.</p><p>Let’s check the distribution and correlation of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEh9bdokEuSy90Zabqrv3g.png" /><figcaption>Histogram of each variable</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYJqPKuuS2cZTz2S4bQkOg.png" /><figcaption>Correlation matrix</figcaption></figure><p>There are a few items that cannot be considered normally distributed, but we will proceed with the analysis here.</p><p>The Kaiser-Meyer-Olkin measure of sample validity (KMO measure) is a criterion for determining whether data are appropriate for using factor analysis and whether meaningful factors are likely to be found in the data.<br>The KMO measure can be calculated using the KMO() function in the psych package.</p><p>First, check the value of the <strong>Overall MSA</strong>. If it is generally 0.6 or higher, it is appropriate to apply factor analysis. If the value of <strong>Overall MSA</strong> is below 0.5 or 0.6, exclude the variables with smaller values of <strong>MSA for each item</strong> from the analysis and check KMO again.</p><pre>&gt; KMO(data)<br>Kaiser-Meyer-Olkin factor adequacy<br>Call: KMO(r = data)<br>Overall MSA =  0.73<br>MSA for each item = <br>     sports    tvsports    exercise      dining     museums         art <br>       0.64        0.59        0.67        0.85        0.71        0.73 <br>     hiking      gaming    clubbing     reading          tv     theater <br>       0.59        0.60        0.68        0.82        0.56        0.86 <br>     movies    concerts       music    shopping        yoga  Attractive <br>       0.80        0.72        0.69        0.72        0.83        0.75 <br>    Sincere Intelligent         Fun   Ambitious <br>       0.77        0.79        0.68        0.80 </pre><p>On the other hand, there is also Bartlett’s sphericity test. This tests whether the correlation matrix can be regarded as a unitary matrix. If you are writing a paper, you should also show this value, but since we have already confirmed that there is a correlation between variables in the correlation matrix, we can skip this step.</p><h4>2. Determining the number of factors</h4><p><strong>1) MAP</strong><br>MAP (Minimum Average Partial (correlation)) means the smallest average partial correlation. If the factor analysis is appropriate, the partial correlation between items approaches 0. If there are too few or too many factors, the partial correlation will be higher. The idea of MAP is to use this to select the number of factors with the smallest mean partial correlation.</p><p>In R, this can be done with the VSS() function in the psych library.</p><pre>&gt; VSS(data, use=&quot;complete.obs&quot;)<br><br>Very Simple Structure<br>Call: vss(x = x, n = n, rotate = rotate, diagonal = diagonal, fm = fm, <br>    n.obs = n.obs, plot = plot, title = title, use = use, cor = cor)<br>VSS complexity 1 achieves a maximimum of 0.51  with  2  factors<br>VSS complexity 2 achieves a maximimum of 0.66  with  4  factors<br><br>The Velicer MAP achieves a minimum of 0.02  with  2  factors <br>BIC achieves a minimum of  -369.8  with  7  factors<br>Sample Size adjusted BIC achieves a minimum of  -72.79  with  8  factors<br><br>Statistics by number of factors <br>  vss1 vss2   map dof chisq     prob sqresid  fit RMSEA  BIC  SABIC complex eChisq  SRMR eCRMS eBIC<br>1 0.43 0.00 0.024 209  2010 2.0e-291    22.4 0.43 0.128  699 1362.7     1.0   3241 0.115 0.121 1930<br>2 0.51 0.58 0.021 188  1469 4.1e-197    16.4 0.58 0.113  290  886.5     1.3   1667 0.083 0.092  488<br>3 0.48 0.62 0.022 168  1073 1.0e-131    13.5 0.65 0.101   20  552.9     1.6   1072 0.066 0.078   18<br>4 0.50 0.66 0.022 149   817  1.2e-92    11.2 0.71 0.092 -118  355.3     1.7    631 0.051 0.063 -303<br>5 0.50 0.65 0.026 131   474  2.6e-40    10.0 0.74 0.070 -348   68.0     1.8    405 0.041 0.054 -417<br>6 0.49 0.65 0.027 114   358  5.8e-27     8.7 0.78 0.064 -357    4.7     1.9    253 0.032 0.046 -462<br>7 0.50 0.66 0.032  98   245  1.5e-14     7.7 0.80 0.053 -370  -58.8     1.9    168 0.026 0.040 -446<br>8 0.51 0.66 0.035  83   184  1.2e-09     6.9 0.82 0.048 -336  -72.8     1.9     96 0.020 0.033 -425</pre><p>The message “The Velicer MAP achieves a minimum of 0.02 with 2 factors” is obtained. The values of the MAP in the third column of the table below the output also shows that the MAP minimum is achieved with 2 factors.</p><p>The number of factors is also determined based on BIC and other information criteria, and the results are also output. 7 factors are proposed for the minimum BIC and 8 factors for the sample size-adjusted BIC, but these numbers seem too large since the original was 22 variables. (I will show the confirmed results later.)</p><p><strong>2) Parallel Analysis<br></strong>In parallel analysis, the eigenvalues of the correlation matrix are calculated to help determine the number of factors. The eigenvalues in factor analysis mean the “information content” of the extracted factors, so to say.<br>The Guttman criterion is that factors with eigenvalues of 1 or more are adopted, and this criterion has often been used due to its simplicity. However, there is a problem with this method. If we generate as many random values without any information as the number of respondents multiplied by the number of questions, will all the correlations for each question be clean and uncorrelated? There is a possibility that the correlation is obtained by chance and the eigenvalue is more than 1. This possibility increases with the number of questions and the number of respondents. The idea underlying Parallel Analysis is that we want the eigenvalues of the adopted factors to exceed the eigenvalues that could occur by chance, even with this random number. Parallel analysis can be performed with fa.parallel(). The following figure is obtained when executed.</p><pre>&gt; fa.parallel(data, main=&quot;Parallel Analysis&quot;, n.iter=100, fa=&quot;pc&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*Fhdvs6osqVW8rlVyh5reIw.png" /></figure><p>The solid black line at height 1 corresponds to the conventional Kaiser criterion (eigenvalue = 1). The eigenvalues of the real data exceed those of the randomly generated data up to the sixth factor. This is in contrast to the Kaise criterion, which adopts up to the eighth factor. The ambiguity of the scree criterion can also be seen in this figure. Following the scree plot of the actual data from right to left, it is unclear whether it is Factor 8, Factor 6, or Factor 4 that has the most significant scree.</p><p><strong>3) Summary of Determining the number of factors</strong><br>The following is a summary of the study to these points</p><ul><li>MAP : Number of factors = 2</li><li>BIC : Number of factors = 7</li><li>Parallel Analysis : Number of factors = 6</li><li>Kaiser criterion : Number of factors = 8</li><li>Scree criterion : Number of factors = 4, 6, or 8</li></ul><p>2 for MAP, 6 for PA, and 7 for BIC. This is not limited to the present data. MAP ≤ PA ≤ BIC is the tendency observed in many cases. In this case, the difference between the number of factors by MAP and the number of factors by PA is large. However, it is advisable to proceed with factor analysis in the range of MAP to PA first, and if the desired results are not obtained, increase the search range to the number of factors by BIC.</p><h4>3. Choose a factor extraction method</h4><p>There are several options for the method of computing factor loadings (factor extraction method). If the sample size is large, the maximum likelihood method should be used; otherwise, the minimum residual method should be used. Principal Component Analysis has problems and should be eliminated from the selection. <br>In R, the <strong>fm</strong> argument in the following code specifies the factor extraction method.</p><pre>fa_result &lt;- fa(data, nfactors=5, fm=&quot;ml&quot;, rotate=&quot;cluster&quot;)<br>print(fa_result, digits=4)</pre><p>Typical options mean the following</p><ul><li>“ml” for maximum likelihood method. This is the first option to try.</li><li>“minres” for minimum residual method. If the maximum likelihood method results in an unsuitable solution, this is the next option. This may be valid for small sample sizes. However, it may be more appropriate to exclude variables that are unsuitable.</li><li>“pa” for (iterated) principal factor method. If minres also yields an unsuitable solution, the next option is this. If the default of 50 iterations does not converge, max.iter should be increased to 100–200.</li></ul><h4><strong>4. Choose a factor rotation method</strong></h4><p>As for the factor rotation method, the first choice would be to choose among independent <strong>cluster</strong> rotation, <strong>oblimin</strong> rotation, or <strong>geominQ</strong> rotation. (Bold part is the parameter name) Which of these you choose depends on the output you seek. In any case, <strong>promax</strong> rotation has the advantage of being quicker to calculate, but it does not always give good solutions. Also, orthogonal rotations such as <strong>varimax</strong> rotation should be used only after it has been confirmed that the inter-factor correlations are negligibly small after trying diagonal rotations.<br>We will see next how changing the rotation method changes the results of the analysis.</p><h4>5. Execute Factor Analysis</h4><p>A factor analysis in the psych library of R provides the following output. The figure below shows the results of a two-factor independent cluster rotation. The first thing to check is the yellow area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*gbswIKcfYN3QuZtAKWgvFQ.png" /><figcaption>Factor analysis output results for two-factor cluster rotation</figcaption></figure><p>In above, <strong>h2</strong> is commonality, which represents the proportion of variance explained by the factor. <strong>u2</strong> is unique variance, which represents the proportion of variance not explained by the common factor. The sum of the two is equal to 1. Both h2 and u2 should take values between 0 and 1 by definition. If the calculation fails, the value of h2 or u2 may be negative or greater than 1. This is called an unsuitable solution and should not be adopted as it is; the factor extraction method should be changed or the variables should be reduced and the factor analysis should be performed again.</p><p>There are multiple places to look next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*pGEfipPqhFF1N5yi6dTUYQ.png" /><figcaption>Factor analysis output results for two-factor cluster rotation</figcaption></figure><p>The yellow part represents the factor loadings. It shows what each factor means. Some of these values are close to 1 or -1, while others are closer to 0, meaning that they have a well-defined factor structure.</p><p>The orange part <strong>com</strong> means complexity, and the closer to 1, the closer to a simple structure (the observed item is explained by only one factor).</p><p>The green part is in order,</p><ul><li>SS loadings: The extent to which each factor explains the variability of the observed variable. The sum of the squares of the factor loadings for each factor.</li><li>Proportion Var: the factor contribution of each factor divided by the number of observed items.</li><li>Cumulative Var: The factor contributions are cumulated from the largest to the smallest. It is difficult to interpret in an oblique rotation.</li><li>Proportion Explained: Proportion Var divided by the maximum Cumulative Var.</li><li>Cumulative Proportion: Cumulative sum of Proportion Explained.</li></ul><p>The red area represents the inter-factor correlations. After a well-ordered structure of factors has been obtained, an orthogonal rotation may be attempted if the inter-factor correlations are close to the unit matrix. Conversely, if there are significant correlations among the off-diagonal elements of the factor correlation matrix, orthogonal rotation will not give a simple structure. The red area assumes that there is no correlation between the factors in the orthogonal rotation, so the factor correlations are not displayed.</p><p>The blue part is the goodness-of-fit index. Since there is no universal indicator, check it as a reference.</p><h4><strong>Is it a aporopriate solution? Is it a simple structure?</strong></h4><p>The results of the two-factor independent cluster rotation show that it is not an unsuitable solution, but the factor loadings, especially for the second factor, are not crisp and it is difficult to interpret what the factor represents. Therefore, we will increase the number of factors and try again.</p><p>The results for factors 3 through 6 are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*Bc8C-Dco8Dduk12Ze7XYOQ.png" /><figcaption>Factor loadings for cluster rotation with 3 factors</figcaption></figure><p>The three-factor model seems to lack clarity as same as the two-factor model with ML3 and ML2 loading thinly on many items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*yzh-QInQbjDzo87lnXA58w.png" /><figcaption>Factor loadings for cluster rotation with 4 factors</figcaption></figure><p>In the four-factor model, the factor loadings for ML4 have negative values, which may be difficult to handle. Of course, as confirmed by the correlation matrix at the beginning of the article, on the whole, those who are more interested in shopping, TV, and movies tend to be less interested in sports and hiking. On the other hand, if we adopt this four-factor model, we would not be able to represent those who are strongly interested in both shopping, TV, movies, sports, and hiking, and those who are weakly interested in both. Let do reject the four-factor model as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*0qU_IWpONGhFWD648qhISA.png" /><figcaption>Factor loadings for cluster rotation with 5 factors</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*M_8VTW832FktnY9zi-Mgfg.png" /><figcaption>Factor loadings for cluster rotation with 6 factors</figcaption></figure><p>The fact that dining and shopping are loaded onto two factors in the five-factor and six-factor models, respectively, is a concern, but both yield factor structures that are close to the simple structure. Here, the five-factor model is adopted in favor of simplicity. For reference, the correlation between factors is shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*bE5MpNG_iQFwh5pLNHP33w.png" /><figcaption>Inter-factor correlations for cluster rotation with 5 factors</figcaption></figure><p>Let’s keep the number of factors at 5 and change the rotation method to GeominQ. The following figure shows the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*JIsOzZjq7YMFN8AZZqSquw.png" /><figcaption>Factor loadings for geominQ rotation with 5 factors</figcaption></figure><p>It seems to approach a simpler structure than cluster rotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*_lPOhhfussZLjhteZZMFvg.png" /><figcaption>Inter-factor correlations for geominQ rotation with 5 factors</figcaption></figure><p>Inter-factor correlations were smaller than cluster rotations.</p><p>Let’s try Oblimin rotation just to be sure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*arkmnkoJP5WH917bezjJYg.png" /><figcaption>Factor loadings for oblimin rotation with 5 factors</figcaption></figure><p>A simple structure was obtained as in geominQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*EtVIFCu3yNBfutBGBP98Hg.png" /><figcaption>Inter-factor correlations for oblimin rotation with 5 factors</figcaption></figure><p>Inter-factor correlations were also similar to geominQ.</p><h4>6. Factor Interpretation &amp; 7. Application of results</h4><p>If we are actually careful, we should not end the factor analysis here, but exclude the items with low loadings and conduct the factor analysis again. However, here we will move on to the interpretation of the factors.</p><p>One misinterpretation that I see occasionally, though not often, is that “respondents are divided into those who are interested in museums, art, who are interested in concerts, music, who are interested in sports, tvsports, and who are interested in tvsports.” Such grouping of respondents cannot be done from factor analysis. This is not the case, the grouping of respondents becomes possible only when the factor scores of respondents are multiplied by cluster analysis. For example, in the context of marketing science, the factors can be analyzed in relation to consumer behavior with the consumer factors obtained, or in relation to preferences.</p><h3>Conclusion</h3><p>Although quite lengthy, I was able to note much about the order in which the options were considered in proceeding with the factor analysis, and where to review what happened. Although some trial and error is inevitable in factor analysis, it should be possible to reduce the amount of meaningless trial and error by proceeding in a systematic manner.</p><p>These days, the analysis of actual behavior data is the main focus, and opportunities for questionnaire-based consumer behavior analysis may be rare. However, to understand consumers from multiple perspectives, a combination of both approaches will remain effective. This article is a bit detailed, but if you would like to try different approaches, please refer to it.</p><p>Did you enjoy this? Click 👏<br>All figures are by the author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17350e4e5f8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use R on Google colaboratory]]></title>
            <link>https://shrmtmt.medium.com/how-to-use-r-on-google-colaboratory-9f49f81973c8?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f49f81973c8</guid>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[google-colaboratory]]></category>
            <category><![CDATA[r]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 04:26:58 GMT</pubDate>
            <atom:updated>2024-03-15T12:48:58.632Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use R on Google Colab without extensions</h3><h4>Any installation is not required</h4><p>There are already a few instructions on how to use R on Google Collaboratory on Medium. Still, I will show you how to use R on Google Collaboratory without installing anything.</p><h3>1. Create a New notebook</h3><p>On the Google colaboratory page, select Create a <strong>+ New notebook</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hWx2QwrxV2MZ5QSjvlpjJg.png" /><figcaption>Picture by author</figcaption></figure><h3>2. Download .ipynb</h3><p>From the <strong>File</strong> menu, select <strong>Download →</strong> <strong>Download .ipynb</strong> to download the notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mWuE2dNMWXxpDrkjJtHvw.png" /><figcaption>Picture by author</figcaption></figure><h3>3. Edit Notebook</h3><p>Edit the downloaded ipynb file using Notepad or other applications.<br>The following two sections are to be rewritten.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AX0fDM8fiHMgBlAt5JV4aQ.png" /><figcaption>Picture by author</figcaption></figure><h3>4. Upload notebook file</h3><p>Select <strong>Upload notebook</strong> from the <strong>File</strong> menu and upload the notebook file you edited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOMOmO72aLVlTco4QFDqHQ.png" /><figcaption>Picture by author</figcaption></figure><h3>5. Check runtime</h3><p>Select <strong>Change runtime type</strong> from the <strong>Runtime</strong> menu to display the currently selected runtime. If the <strong>Runtime type</strong> is set to <strong>R</strong>, confirmation is complete. R will run in this notebook.</p><p><strong>Once you have completed setting up the R runtime, you only need to create a new notebook and select R as the runtime the next time. There is no need to repeat the above procedures 1–4.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5iGZG5pSVZCDP2e9m__BQ.png" /><figcaption>Picture by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1PV22jLb9g4D-BE4VnAUw.png" /><figcaption>Picture by author</figcaption></figure><h3>6. R version</h3><p>At the time of writing, the version of R is R4.3.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*c_AR9BV9zb5WXOTaJVhgqQ.png" /><figcaption>Picture by author</figcaption></figure><h3>7. Installed libraries</h3><p>The notebook already has several libraries installed, as can be seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*fp4Z8zIeiTdfAVlJ1_qJtg.png" /><figcaption>Picture by author</figcaption></figure><h3>8. Inconvenience compared with python</h3><p>With the Python 3 runtime, the list of variables can be displayed from the left pane, but the list of variables cannot be displayed with the R runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*n7gWhtnvwFkIFqW8YLADwQ.png" /><figcaption>Picture by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*uXH6t4WvfJ9znizbE1-wDg.png" /><figcaption>Picture by author</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f49f81973c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand the capabilities of cyclic encoding]]></title>
            <link>https://shrmtmt.medium.com/understand-the-capabilities-of-cyclic-encoding-5b68f831387e?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b68f831387e</guid>
            <category><![CDATA[time-series-data]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Wed, 18 Oct 2023 02:23:07 GMT</pubDate>
            <atom:updated>2024-01-18T01:03:34.482Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s not only represent cyclic proximity, but also represent every waveforms</h4><h3>What is Cyclic encoding?</h3><p>Cyclic encoding (cyclical representative, cyclical embedding) is a technique for inputting the components of periodicity (hour, week, year, etc.) into a machine learning model such as a neural network when the target variable is considered to have periodicity.</p><p>For example, when constructing a model to predict data that would have a periodicity of 24 hours per day, if the value of time n is given as it is as a numerical value from 0–23, the relationship that 0:00 comes right after 23:59 cannot be expressed. Instead, we can express the proximity of 23:59 and 0:00 by giving sine and cosine values as numerical values, which correspond to the position of the hands of a clock that make a round in 24 hours.</p><p>The specific steps are as follows</p><ol><li>Conversion to radian angles<br>Convert periodicity data into radian angles.<br>For example, to represent a 24-hour periodicity, multiply 2π by x hours divided by 24 to convert the range of values from 0 to 2π. 0 o’clock is converted to (0/24)2π, 1 o’clock to (1/24)2π, 2 o’clock to (2/24)2π, and 23 o’clock to (23/24)2π, respectively. (If the model handles not only hours but also minutes and seconds, find the radian angles corresponding to the hours, minutes, and seconds that circle around in 24 hours.)</li><li>Conversion to sine and cosine<br>Find the sine and cosine of the radian angles obtained in step 1 and make the two obtained values into features</li></ol><p>This is how cyclic encoding is realized and implemented. But what capabilities does this Cyclic encoding have? The key to understanding this is <strong>the universal approximation theorem</strong> and <strong>Fourier decomposition</strong>.</p><h4><strong>What is the universal approximation theorem?</strong></h4><p><strong>The Universal Approximation Theorem</strong> of Neural Networks is the theorem that <strong>any continuous function can be approximated</strong> with arbitrary accuracy by a neural network with a sufficiently large hidden layer (intermediate layer). In other words, a properly designed multi-layered neural network can theoretically approximate any complex function.</p><p>The main point of this theorem is that with proper structure and parameter tuning, neural networks can represent even very complex nonlinear functions. But in practice, finding a suitable network structure and learning algorithm is difficult and depends on the training data, so a practical approximation is not always guaranteed.</p><h4>What is the fourier decomposition?</h4><p>Fourier Decomposition (Fourier Series Expansion is almost synonymous) is a technique for decomposing an arbitrary periodic function into a sum of multiple sine and cosine waves. By performing Fourier decomposition, arbitrarily complex periodic functions can be expressed as a combination of simple sine and cosine waves.</p><h3>The combination of cyclic encoding and neural networks can theoretically generate all waveforms</h3><p>In cyclic encoding, only unit oscillating waves with period 2π are embedded. However, the neural network generates high-frequency oscillation waves from the unit oscillation wave, such as double-angle, triple-angle, and so on. Furthermore, the neural network generates arbitrary waveforms by adding combinations of high frequencies such as unit vibration waves, doubling vibration waves, and tripling vibration waves with appropriate weighting.</p><h3>Experiments with cyclic encoding by code</h3><p>To make the above explanation intuitive, I will illustrate it with an actual example. Although a bit verbose, here is the complete code to make it easier to understand what we are about to do.<br>Note that <strong>the purpose of this experiment is to demonstrate the representational capabilities of cyclic encoding</strong>. Therefore, the training and validation data are not split, and there is no noise on the objective variable. Note that no regularization or early stopping was performed to avoid the risk of overtraining.</p><pre>import numpy as np<br>import tensorflow as tf<br>from tensorflow.keras.models import Model<br>from tensorflow.keras.layers import Input, Dense<br>from tensorflow.keras.optimizers import Adam<br>import matplotlib.pyplot as plt<br><br># NeuralNetwork classes, passing the number of hidden layers and their number of nodes as list arguments<br>class NeuralNetwork:<br>    def __init__(self, input_dim, hidden_units):<br>        self.input_dim = input_dim<br>        self.hidden_units = hidden_units<br>        self._build_model()<br><br>    def _build_model(self):<br>        input_layer = Input(shape=(self.input_dim,))<br>        x = input_layer<br>        for units in self.hidden_units:<br>            x = Dense(units, activation=&#39;relu&#39;)(x)<br>        output_layer = Dense(1)(x)<br>        self.model = Model(inputs=input_layer, outputs=output_layer)<br>        self.model.compile(loss=&#39;mean_squared_error&#39;, optimizer=Adam())<br><br>    def train(self, input_data, output_data, epochs=1000, batch_size=32, verbose=1):<br>        self.model.fit(input_data, output_data, epochs=epochs, batch_size=batch_size, verbose=verbose)<br><br>    def predict(self, input_data):<br>        return self.model.predict(input_data)<br><br># The only input values are the cyclic encodings sin and cos.<br>def create_input_data(x):<br>    sin_x = np.sin(x)<br>    cos_x = np.cos(x)<br>    return np.column_stack((sin_x, cos_x))<br><br># Objective variable we want to train (we&#39;ll see it later in the graphs)<br>def create_target_data(x, func):<br>    if func == &#39;sin(x)&#39;:<br>        return np.sin(x)<br>    elif func == &#39;sin(2x)&#39;:<br>        return np.sin(2*x)<br>    elif func == &#39;sin(5x)&#39;:<br>        return np.sin(5*x)<br>    elif func == &#39;sawtooth&#39;:<br>        return x % (2 * np.pi)<br>    elif func == &#39;step&#39;:<br>        return np.floor(x % (2 * np.pi))<br>    elif func == &#39;jigzag_step&#39;:<br>        return ((np.floor(x % (2 * np.pi)))*2) % 5<br>    elif func == &#39;x&#39;:<br>        return x<br>    else:<br>        raise ValueError(&quot;Invalid function&quot;)<br><br># Drawing Graph<br>def plot_results(test_x, true_values, predictions, func_name, hidden_units):<br>    plt.figure(figsize=(16, 6))<br>    plt.scatter(test_x, true_values, label=&#39;True Values&#39;, color=&#39;salmon&#39;)<br>    plt.plot(test_x, predictions, label=&#39;Predictions&#39;, linestyle=&#39;dashed&#39;, color=&#39;darkcyan&#39;)<br>    plt.xlabel(&#39;x&#39;)<br>    plt.ylabel(func_name)<br>    plt.title(f&#39;Function: {func_name}, Hidden Units: {hidden_units}&#39;)<br>    plt.legend()<br>    plt.xticks([-2*np.pi, -1.5*np.pi, -np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi, 1.5*np.pi, 2*np.pi],<br>               [&#39;-2π&#39;, &#39;-1.5π&#39;, &#39;-π&#39;, &#39;-0.5π&#39;, &#39;0&#39;, &#39;0.5π&#39;, &#39;π&#39;, &#39;1.5π&#39;, &#39;2π&#39;])<br>    plt.show()<br><br># Neural Network Training and Drawing<br>def train_and_plot(func_name, hidden_units, epochs):<br>    # Data generation<br>    x = np.linspace(-2*np.pi, 2*np.pi, 100)<br>    <br>    # Instantiating the neural network<br>    input_dim = 2<br>    nn = NeuralNetwork(input_dim, hidden_units)<br>    <br>    # Choosing the target variable<br>    output_data = create_target_data(x, func_name)<br>    <br>    # Training<br>    input_data = create_input_data(x)<br>    nn.train(input_data, output_data, epochs=epochs, verbose=0)<br>    <br>    # Predictions for the test data<br>    test_x = np.linspace(-2*np.pi, 2*np.pi, 100)<br>    test_input_data = create_input_data(test_x)<br>    predictions = nn.predict(test_input_data)<br>    <br>    # Plotting the results<br>    plot_results(test_x, output_data, predictions, func_name, hidden_units)</pre><h4>Unit sine wave</h4><p>Now you are ready for the experiment.<br>First, we will check the simplest form, the case where the objective variable was a unit sine wave. Since the explanatory variables are unit sine and unit cosine, it seems to be possible to explain it well without using a neural network.<br>Here we assume one hidden layer with four nodes.</p><pre>func_name = &#39;sin(x)&#39;<br>hidden_units = [4]<br>epochs = 1000<br>train_and_plot(func_name, hidden_units, epochs)</pre><p>And here is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa1WbJoEXd9YwLl_AB6B2g.png" /><figcaption>Figure 1 (by author)</figcaption></figure><p>Not surprisingly, the model is able to train the unit sine wave well.</p><h4>Sin(2x)</h4><p>Then, let’s see if the model can learn sin(2x), where the frequency is doubled. The number of nodes in the hidden layer is 16.</p><pre>func_name = &#39;sin(2x)&#39;<br>hidden_units = [16]<br>epochs = 1000<br>train_and_plot(func_name, hidden_units, epochs)</pre><p>And here is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ogy-rywilS__fw83xVNTEA.png" /><figcaption>Figure 2 (by author)</figcaption></figure><p>Worked. The model is also learning sin(2x). That is, by repeatedly adding constants to sin(x) and cos(x), multiplying by a constant, and applying Relu, we found that sin(2x) can be obtained.</p><h4>Sin(5x)</h4><p>Just to be sure, let’s also look at sin(5x).</p><pre>func_name = &#39;sin(5x)&#39;<br>hidden_units = [16]<br>epochs = 1000<br>train_and_plot(func_name, hidden_units, epochs)</pre><p>And here is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FxRlpiyyzGFd29ww3bO0w.png" /><figcaption>Figure 3 (by author)</figcaption></figure><p>Oh, what a disappointing result…<br>Actually, this is because the assumption of the universal approximation theorem, “neural network with a <strong>sufficiently large hidden layer</strong>,” was not satisfied.</p><p>To make it sufficiently large, either increasing the number of layers or increasing the number of nodes in the layers is theoretically possible, but in this case, increasing the number of layers is more efficient, so we retried with 2 hidden layers and 16 nodes each.</p><pre>func_name = &#39;sin(5x)&#39;<br>hidden_units = [16, 16]<br>epochs = 1000<br>train_and_plot(func_name, hidden_units, epochs)</pre><p>Here is the result this time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvDyPth3rirn4aQ3RLcCow.png" /><figcaption>Figure 4 (by author)</figcaption></figure><p>Even high frequencies such as sin(5x) could be generated from sin(x) and cos(x).</p><h4>Sawtooth wave</h4><p>Now what if it is a sawtooth wave instead of a sine or cosine wave?</p><pre>func_name = &#39;sawtooth&#39;<br>hidden_units = [32, 32]<br>epochs = 1000<br>train_and_plot(func_name, hidden_units, epochs)</pre><p>This is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUOn4G34IzNSKdQHZRzpIw.png" /><figcaption>Figure 5 (by author)</figcaption></figure><p>In fact, such a worsening of the approximation at discontinuities is also observed in Fourier decomposition and is known as the Gibbs phenomenon. However, in Gibbs phenomenon, the approximation behaves as if it overshoots outward at discontinuities. This result differs in that point.</p><h4>Staircase wave</h4><p>What would a staircase function with many discontinuities look like?</p><pre>func_name = &#39;step&#39;<br>hidden_units = [64, 64, 64]<br>epochs = 1000<br>train_and_plot(func_name, hidden_units, epochs)</pre><p>Here is the outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQceeZBCY6pCOEe22L3SEQ.png" /><figcaption>Figure 6 (by author)</figcaption></figure><p>Although the approximation is not very good in some places, the true values are generally reproduced.</p><h4>Zigzag Staircase</h4><p>Finally, what if it were a more complex staircase shape?</p><pre>func_name = &#39;jigzag_step&#39;<br>hidden_units = [64, 64, 64]<br>epochs = 3000<br>train_and_plot(func_name, hidden_units, epochs)</pre><p>Here is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4dn6unPF5z5-C3WLrjRwg.png" /><figcaption>Figure 7 (by author)</figcaption></figure><p>It is still able to reproduce the true value even with complex discontinuous functions.</p><h4>To be sure, the acyclic function</h4><p>What we have checked is “Can a neural network with sin(x) and cos(x) as input values approximate a function with arbitrary period 2π? Of course, any function other than periodic functions cannot be approximated by a neural network with sin(x) and cos(x) as input values.</p><pre>func_name = &#39;x&#39;<br>hidden_units = [64]<br>epochs = 1000<br>train_and_plot(func_name, hidden_units, epochs)</pre><p>It goes like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUvkOrFu3NjrSRCBesVRvw.png" /><figcaption>Figure 8 (by author)</figcaption></figure><p>It doesn’t work at all, to be sure.</p><h3>Summary of Experiment</h3><p>As we have seen, we have confirmed that we can approximate arbitrary periodic functions by using two inputs, sin(x) and cos(x), and a neural network of appropriate complexity. This indicates the possibility of reproducing the periodicity of arbitrary shapes by adding sin(x) and cos(x) to the features of the model when the objective variable is considered to have periodicity. If the objective variable is considered to have periodicity by time of day, by week or day of week, and by year, then we can add sin(x) and cos(x) corresponding to the time of day, sin(x) and cos(x) corresponding to the week or day of week, and sin(x) and cos(x) corresponding to the annual period.</p><h3>Implications for model building</h3><p>Based on the considerations we have seen so far, if we want periodicity in the model, should we use cyclic encoding and not need one-hot encoding for dates, days of the week, or time of day? Or would it rather cause harm?</p><p>I think it depends on what you are modeling.</p><h4>In the case of modeling for natural sciences</h4><p>Basically, only cyclic encoding should be used, and one-hot encoding corresponding to the month, day of the week, day of the week, and time will often be unnecessary. For example, if one is trying to predict river flow based on precipitation, it would be sufficient to use two inputs as cyclic encoding corresponding to the annual cycle. Another example, predicting solar power generation from weather satellite images, would work well with only cyclic encoding for the annual cycle and cyclic encoding for the daily cycle.</p><h4>The case of social science modeling</h4><p>In the case of social science subjects, such as the economy, social activities, marketing, and other phenomena that depend on human behavior, one should actively consider using one-hot encoding in addition to cyclic encoding because human activity depends on time of day, day of the week, and date.</p><p>When modeling traffic and transit passenger population, it is likely to have features and trends that are strongly dependent on the day of the week and time of day, and sometimes peaky. If only cyclic encoding is used, a large number of nodes will be consumed to express such peaky features and trends. Although cyclic encoding can also capture complex trends such as Figure 6 and Figure 7 mentioned above, this requires a larger amount of resources (nodes) in the neural network. If we want to obtain the same representation capability, it will often be more efficient and robust to add one-hot encoding of the day of the week and time of day, and keep the number of nodes in the hidden layer small, rather than greatly increasing the number of nodes in the hidden layer without one-hot encoding of the day of the week and time of day.</p><p>On the other hand, it is sometimes better to avoid simple one-hot encodings when the sample size is small or when the number of samples for some one-hot encodings is small. It is necessary to check by EDA whether there are enough samples corresponding to each one-hot encoding.</p><h3>Summary</h3><p>This experiment was performed on toy samples without noise. In actual modeling, a battle against noise and overlearning awaits. The feature design policy will change depending on whether the sample size is large enough or not so large. I hope this article will help you in your modeling feature design.</p><p>Did you enjoy this? Click 👏 <br>All codes are below.</p><p><a href="https://github.com/shrmtmt/cyclic_encoding_experiment">https://github.com/shrmtmt/cyclic_encoding_experiment</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b68f831387e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multicollinearity understood with the simplest example]]></title>
            <link>https://shrmtmt.medium.com/multicollinearity-understood-with-the-simplest-example-b4a2a182a064?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4a2a182a064</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[multicollinearity]]></category>
            <category><![CDATA[regression-analysis]]></category>
            <category><![CDATA[simple-example]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 02:48:02 GMT</pubDate>
            <atom:updated>2023-10-03T02:58:41.125Z</atom:updated>
            <content:encoded><![CDATA[<h4>Visual simple example of multicollinearity</h4><p>What is multicolinearity?<br>In regression analysis, multicolinearity is a phenomenon in which two or more independent variables are highly correlated. There are already many good articles on medium that provide detailed explanations in text. Here, I will use as simple an example as possible to help you understand multicolinearity.</p><p>Let us consider a simple example with two independent variables, one dependent variable, and a sample size of 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*bEHALs50NF6GpfSEHId3pg.png" /><figcaption>Sample data (by author)</figcaption></figure><p>These data could be the price of a house(<strong>y</strong>), given an area of land(<strong>x1</strong>) and a total floor area(<strong>x2</strong>), or the cost of developing a system(<strong>y</strong>), given the number of screens(<strong>x1</strong>) and the number of forms(<strong>x2</strong>). Anyway, let us assume a situation where we want to explain <strong>y</strong> using <strong>x1</strong> and <strong>x2</strong>.</p><p>Let’s first see if we can explain <strong>y</strong> using <strong>x1</strong>. At the same time, let’s see if we can explain <strong>y</strong> using <strong>x2</strong>. Yes, it is. Single regression analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xj7xLwoHgBtmCpAlq40hmg.png" /><figcaption>Figure 1 Single regression analysis on sample data (by author)</figcaption></figure><p><em>Just to be sure, the diagonal solid line is the regression equation resulting from the regression analysis; the length of the dotted line parallel to the y-axis corresponds to the difference between the regression equation and the sample, and the sum of the squares of the lengths of the dotted lines is the residual sum of squares. Conversely, the straight line drawn so that the residual sum of squares is the smallest is the regression line.</em></p><p>Since <strong>y</strong> increases as <strong>x1</strong> increases, the attempt to predict <strong>y</strong> using <strong>x1</strong> seems to work. Similarly, using <strong>x2</strong> to predict <strong>y</strong> seems to work well.</p><p>But there is information that does not appear in <strong>x1</strong> but is included in <strong>x2</strong>, while there is information that is not included in <strong>x2</strong> but is included in <strong>x1</strong>. In the example of the price of a property, the price of a property is likely to be if the total floor area is larger even area of land are same, and the price of a property is likely to be higher if the total floor area is the same, but the land area is larger. Conversely, a property with the same price may have a small building on a large lot, or a large building on a smaller lot. In that way, it would seem to better explain <strong>y</strong> using <strong>x1</strong> and <strong>x2</strong> at the same time.</p><p>This is where multiple regression analysis comes in. So let’s get started. This time, it must be three-dimensional to show the relationship between the three variables: two explanatory variables and one objective variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*BFG-6aegv-aFAHXGieCQfw.gif" /><figcaption>Figure 2 Multiple regression analysis of sample data (by the author)</figcaption></figure><p>Compared to the results of the single regression analysis, the residual sum of squares is smaller at 11678, so it appears that the results have a smaller error margin. (In the single regression analysis, they were 12011 and 28752, respectively.)</p><p>However, the regression equation obtained is a bit strange.</p><blockquote>regression equation: y=1.265 x1 - 0.153 x2 + 136.637</blockquote><p>This equation shows the relationship where <strong>y</strong> becomes larger as <strong>x1 </strong>increases, but y becomes smaller as <strong>x2</strong> increases. This result differs from the results of the single regression analysis we performed earlier, and in the example of property prices, it goes against intuition. Why does this occur? This is an example of multicollinearity. In fact, the correlation coefficient between <strong>x1</strong> and <strong>x2</strong> is as large as 0.90. This high correlation among explanatory variables is likely to produce multicollinearity, which can produce results that are contrary to the expected trend and difficult to interpret.</p><p>Since there were only two explanatory variables here, it was easy to easily check whether multicollinearity was occurring or not. On the other hand, as the number of explanatory variables increases, it becomes increasingly difficult to check whether or not multicollinearity is occurring. When multicollinearity is found to occur, there are several ways to alleviate it.</p><ul><li>Although this article gave an obvious example of the sign of regression coefficients changing between single and multiple regression analysis, but not all multicollinearity will reverse the sign.</li><li>The effect of multicollinearity often weakens as the sample size increases, but the effect does not disappear</li></ul><p>The following articles may be helpful in identifying whether multicollinearity exists and how to mitigate it if it does.</p><h3>References</h3><h4>detect multicollinearity</h4><p><a href="https://universidadedosdados.medium.com/multicollinearity-is-not-correlation-38014cbfc710">Multicollinearity is not correlation</a></p><h4>mitigate multicollinearity</h4><p>There are several ways to mitigate the effects of multicollinearity, including variable selection, principal component analysis, and the adoption of regularization terms such as lasso regression and ridge regression. I couldn’t find an article explaining all of these together, so I will give you the articles that seem to be good individually.</p><ul><li><a href="https://summer-hu-92978.medium.com/complete-feature-selection-techniques-4-1-statistical-test-analysis-611ede242fa0">Complete Feature Selection Techniques 4 - 1 Statistical Test &amp; Analysis</a></li><li><a href="https://towardsdatascience.com/principal-component-regression-clearly-explained-and-implemented-608471530a2f">Principal Component Regression — Clearly Explained and Implemented</a></li><li><a href="https://medium.com/@seshu8hachi/lasso-and-ridge-regression-regularization-techniques-explained-for-beginners-be568ac6c0a3">Lasso and Ridge Regression — Regularization Techniques Explained for Beginners</a></li></ul><p>I’m glad to receive you comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4a2a182a064" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotani’s Ant Problem: Simple but counterintuitive mystery]]></title>
            <link>https://shrmtmt.medium.com/kotanis-ant-problem-29868cc5a939?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/29868cc5a939</guid>
            <category><![CDATA[math-puzzles]]></category>
            <category><![CDATA[counterintuitive]]></category>
            <category><![CDATA[paradox]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 02:27:54 GMT</pubDate>
            <atom:updated>2024-01-18T01:02:58.142Z</atom:updated>
            <content:encoded><![CDATA[<h4>Where is the farthest point on the surface of a cuboid?</h4><p>Consider a unit cube. Where is the farthest point starting from a certain vertex and moving over the cube’s surface? This is easy. Intuitively, the opposite vertex is the furthest away. Just to be sure, let’s draw a figure to confirm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QyusuHihLDosqVO-gC1_6Q.gif" /><figcaption>Surface distance point on unit cube from origin (by author)</figcaption></figure><p>So what if we consider a 1×1×2 rectangle with two unit cubes stacked on each other? Would the farthest point from the origin (0,0,0) be (1,1,2)?</p><p>Are you sure you think of it? You have a chance to reconsider.<br>Let’s check by drawing a figure in the same way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UyRZJ1-ODp6RPtvhTbg2mA.gif" /><figcaption>Surface distance points from the origin on a 1×1×2 cuboid (by author)</figcaption></figure><p>Hmm? Wasn’t something different from what you expected at the last moment? Let’s look at it more slowly, using only the top view to get a clearer picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ysjnH07S48R5GSmugiE4Dg.gif" /><figcaption>Surface distance points from the origin on a 1×1×2 cuboid, top surface only (by author)</figcaption></figure><p>The animation might be ambiguous. Let’s use the development to figure out how far we can reach with 2√2, the distance along the plane from (0,0,0) to (1,1,2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0TkSmSmsDCBdWG749iGyQ.gif" /><figcaption>The area that is reachable within a distance of 2√2 on a 1x1x2 rectangular surface</figcaption></figure><p>The development shows that parts of the rectangle’s top surface cannot be reached within a distance of 2√2. This indicates that the farthest point that can be reached from (0,0,0) by traversing over the surface of the rectangle is <strong>not </strong>(1,1,2).</p><p>Let’s look at a 1×1×10 cube as an extreme example to see why this happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*xQ22xZ_S4fsAsQZi4BNltA.gif" /><figcaption>Surface distance points from the origin on a 1×1×10 cuboid (by author)</figcaption></figure><p>In this way, it is easy to understand. The distance from the origin to (0,0,10) is 10, while the distance from the origin (0,0,0) to (1,0,10) is √101=10.0499, and the surface distance from the origin (0,0,0) to (1,1,10) is √104=10.1980, so the difference between these distances is slight. Since these differences (0.0499 and 0.1980) are relatively small compared to the distance from the edge of the top surface to the center of the top surface (0.5), the farthest point from the origin is near the center of the top surface.</p><p>Let’s look at this one, too, using only the top view to be sure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XeaoO-JetarS_mpMQST8ow.gif" /><figcaption>Surface distance points from the origin on a 1×1×10 cuboid, top surface only (by author)</figcaption></figure><p>This seemingly counterintuitive problem is called <strong>“Kotani’s ant problem,”</strong> a mathematical puzzle problem invented by Yoshiyuki Kotani, a computer scientist and puzzle enthusiast.</p><p>This article does not show how to find the coordinates of the farthest point. However, if you are interested, try it.</p><p>Did you enjoy this? Click 👏</p><h4>References</h4><p>https://ja.wikipedia.org/wiki/%E5%B0%8F%E8%B0%B7%E3%81%AE%E8%9F%BB%E3%81%AE%E5%95%8F%E9%A1%8C</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29868cc5a939" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common Misuses of Statistical Hypothesis Testing: Part 3]]></title>
            <link>https://shrmtmt.medium.com/common-misuses-of-statistical-hypothesis-testing-part-3-5a549e6f96a2?source=rss-33149ffe183c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a549e6f96a2</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[statistical-test]]></category>
            <category><![CDATA[statistical-thinking]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shiro Matsumoto]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 20:26:24 GMT</pubDate>
            <atom:updated>2024-10-22T19:26:10.830Z</atom:updated>
            <content:encoded><![CDATA[<h4>Does a small p-value indicate a higher importance?</h4><p>In the previous two articles, I discussed misuses of statistical hypothesis testing that we should be aware of. Here, I will explain one last common misuse. The p-value should only be used for comparison to a predetermined significance level, such as 0.05 or 0.01. Have you ever seen a report that compares the p-values of different tests to each other and discusses something? Actually, it does not make sense to compare the p-values of different tests. Let me explain why it is meaningless with an example.</p><h3>Preparation for the experiment</h3><p>Again, I will conduct a numerical experiment and explain the results of this experiment. First, as before, I define a function that generates a specified number of samples with a specified mean and standard deviation. Instead of simply generating random samples, we standardize the return value so that it exactly matches the mean and standard deviation of the argument.</p><pre>def generate_samples(mean=100, stddev=10, samplesize=1000):<br>  import numpy as np<br><br>  # Generate samples that follow a normal distribution<br>  samples = np.random.normal(1, 1, samplesize)<br><br>  # Calculate the mean and standard deviation of the generated sample<br>  sample_mean = np.mean(samples)<br>  sample_std = np.std(samples)<br><br>  # Match the mean and standard deviation of the generated sample to the argument<br>  samples = (samples - sample_mean) * stddev / sample_std + mean<br><br>  return samples</pre><p>Below is a function that performs a statistical test using the above function. The code is different from that of part 2, as the experiment is performed differently. Given the mean, standard deviation, and number of samples for samples A and B as arguments, a graph showing their distribution and the results of the t-test are output.</p><pre>def experiment(meanA, stddevA, samplesizeA, meanB, stddevB, samplesizeB):<br>  import numpy as np<br>  import matplotlib.pyplot as plt<br>  from scipy.stats import norm, ttest_ind, gaussian_kde<br><br>  # Generate random samples with given mean and standard deviation<br>  sampleA = generate_samples(meanA, stddevA, samplesizeA)<br>  sampleB = generate_samples(meanB, stddevB, samplesizeB)<br><br>  # Prepare graph<br>  plt.figure(figsize=(12, 6))<br>  plt.xlim(60, 150)<br>  plt.ylim(-0.005, 0.045)<br><br>  # Kernel density estimation for sample A<br>  kde1 = gaussian_kde(sampleA)<br>  x1 = np.linspace(60, 150, 1000)<br>  y1 = kde1(x1)<br>  plt.plot(x1, y1, label=f&#39;KDE of Sample A (mean={meanA}, stddev={stddevA}, n={samplesizeA})&#39;, c=&#39;blue&#39;)<br><br>  # Kernel density estimation for Sample B<br>  kde2 = gaussian_kde(sampleB)<br>  x2 = np.linspace(60, 150, 1000)<br>  y2 = kde2(x2)<br>  plt.plot(x2, y2, label=f&#39;KDE of sample B (mean={meanB}, stddev={stddevB}, n={samplesizeB})&#39;, c=&#39;red&#39;)<br><br>  # Small dots indicating samples 1 (with jitter)<br>  jitter1 = np.random.normal(0, 0.001, len(sampleA))<br>  plt.scatter(sampleA, jitter1, c=&#39;blue&#39;, alpha=1/(samplesizeA**.5), label=f&#39;Plots of sample A&#39;)<br><br>  # Small dots indicating samples 2 (with jitter)<br>  jitter2 = np.random.normal(0, 0.001, len(sampleB))<br>  plt.scatter(sampleB, jitter2, c=&#39;red&#39;, alpha=1/(samplesizeB**.5), label=f&#39;Plots of sample B&#39;)<br><br>  plt.title(&#39;Distribution of sample A and sample B&#39;)<br>  plt.xlabel(&#39;Value&#39;)<br>  plt.ylabel(&#39;Density&#39;)<br><br>  # Run a t-test<br>  t_stat, p_value = ttest_ind(sampleB, sampleA)<br>  plt.text(60, -0.014, f&#39;t-statistic: {t_stat:.4f}&#39;, fontsize=12)<br>  plt.text(60, -0.016, f&#39;p-value: {p_value:.4f}&#39;, fontsize=12)<br><br>  # Set significance level<br>  alpha = 0.05<br><br>  # Evaluate results using p-value<br>  if p_value &lt; alpha:<br>      plt.text(60, -0.018, &#39;There is a statistically significant difference (p &lt; 0.05)&#39;, fontsize=12)<br>  else:<br>      plt.text(60, -0.018, &#39;No statistically significant difference (p &gt;= 0.05)&#39;, fontsize=12)<br><br>  plt.legend()<br>  plt.grid(True)<br>  plt.show()</pre><h3>Experiments</h3><p>Let’s try the first experiment with this code.</p><ul><li>Sample A: Mean=100, Standard deviation=10, Number of samples=10</li><li>Sample B: Mean=110, Standard deviation=10, Number of samples=10</li></ul><p>Let’s check the difference between the two groups. You can perform the experiment with the following code.</p><pre>experiment(100, 10, 10, 110, 10, 10)</pre><p>Here is an example of the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*8ZRj4ax2N-mSuxgevrAX6A.png" /><figcaption>Figure 1 (by author)</figcaption></figure><p>P-value = 0.0480 with significant difference. Phew!</p><p>Next, let’s change the conditions a little and conduct a second experiment.</p><ul><li>Sample A: Mean=100, Standard deviation=10, Number of samples=<strong>100</strong></li><li>Sample B: Mean=<strong>103</strong>, Standard deviation=10, Number of samples=<strong>100</strong></li></ul><p>What about the difference between the two groups? The bolded text is where the conditions differ from those in the first experiment.</p><p>You can perform the experiment with the following code</p><pre>experiment(100, 10, 100, 103, 10, 100)</pre><p>Here is an example of the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*7QWe7fATb_HFULmuu83sHA.png" /><figcaption>Figure 2 (by author)</figcaption></figure><p>P-value = 0.0361 with a significant difference. Yoo-hoo!</p><p>We are in good shape. Now let’s move on, to the third experiment.</p><ul><li>Sample A: Mean=100, Standard deviation=10, Number of samples=<strong>1000</strong></li><li>Sample B: Mean=<strong>101</strong>, Standard deviation=10, Number of samples=<strong>1000</strong></li></ul><p>What is the difference between the two groups? The bolded part is where the conditions are different from the previous one.</p><p>You can perform the experiment with the following code.</p><pre>experiment(100, 10, 1000, 101, 10, 1000)</pre><p>Here is an example of the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*FlIG-Sr229lpyMMHyg0wsQ.png" /></figure><p>P-value = 0.0255, with a significant difference. Bravo!</p><p>Let’s summarize the main points of these three experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*aa8vKmr9qenmY4jVFyD5aA.png" /><figcaption>Figure 4 (by author)</figcaption></figure><p>If the p-value is less than the significance level ( assuming 0.05 this time), you would consider that a “statistically significant difference” was obtained, while if the p-value is greater than the significance level, you would conclude that a “statistically significant difference” was not obtained. So, is it correct to understand that experiment 2 with a p-value of 0.0361 has a “<strong>more</strong> statistically significant result” than experiment 1 with a p-value of 0.0480? Does experiment 3 with a p-value of 0.0255 have an even “<strong>more</strong> statistically significant difference” than experiment 2 with a p-value of 0.0361? On the other hand, the difference between the means of the two groups in experiment 1 (=10) is bigger than the difference between the means of the two groups in experiment 2 (=3). Similarly, the difference between the two groups in experiment 2 (=3) is bigger than the difference between the two groups in experiment 3 (=1)). What exactly is a “statistically significant difference?”</p><h3>What does the statistical hypothesis test confirm?</h3><p>In statistical hypothesis testing, the inference is that “sampling surveys are inevitably biased, but extreme bias rarely occurs many times in a row, so if we observe something that rarely happens, we should assume that a difference actually exists rather than sampling bias. In the process of inference, a “statistically significant difference” is an indicator of “the degree that something rarely happens.” Although it is named “significant difference,” it does not indicate whether the difference is important or not, but rather whether there is a significant difference considering the difference in means, standard deviation, and the number of samples taken as a whole. “Statistically significant different” does not mean importance, meaningfulness, or severity of difference.</p><h3>Summary</h3><ul><li>Statistical significance does not mean importance, meaningfulness, or substantial</li><li>Statistical significance should be compared with the significance level. It does not make sense to compare p-values of multiple tests with each other</li></ul><h3>Related articles</h3><p><a href="https://shrmtmt.medium.com/common-misuses-of-statistical-hypothesis-testing-part-1-dd575d6332d6">Part 1 is here</a>. And <a href="https://shrmtmt.medium.com/common-misuses-of-statistical-hypothesis-testing-part-2-73120deb8cbc">Part 2 is here</a>.</p><h3>At the end of a three-part series</h3><p>I showed three examples of how statistical hypothesis testing could be deceptive. Such erroneous analysis may be done both by the analyst to gain credibility by claiming that there is a statistically significant difference or that statistical methods are used, and by the analyst himself/herself unintentionally due to lack of understanding.</p><p>While there are many things that should not be done or that do not make sense to do in statistical hypothesis testing, we rarely see articles on why they should not be done or do not make sense. In these three articles, I aimed to give concrete examples of why these things should not be done and do not make sense to do, so that you can understand them as images. Once you understand these things, you will be able to better understand the usefulness of more advanced topics, such as <strong>effect size</strong> and <strong>power of test</strong>. If you are interested, try searching for the keywords “<strong>effect size</strong>” and “<strong>power of test</strong>”. Many good articles about them already exist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a549e6f96a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>