<?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 Rajeshneupane on Medium]]></title>
        <description><![CDATA[Stories by Rajeshneupane on Medium]]></description>
        <link>https://medium.com/@rajeshneupane7?source=rss-f77dddad14a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_DfC3PNai_Y_ljOj</url>
            <title>Stories by Rajeshneupane on Medium</title>
            <link>https://medium.com/@rajeshneupane7?source=rss-f77dddad14a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:26:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajeshneupane7/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[Why Using AI Without Understanding It Is Like Driving a Car Without Knowing What’s Under the Hood]]></title>
            <link>https://medium.com/@rajeshneupane7/why-using-ai-without-understanding-it-is-like-driving-a-car-without-knowing-whats-under-the-hood-cb22318634d0?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb22318634d0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cars]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 15:57:51 GMT</pubDate>
            <atom:updated>2025-04-21T15:57:51.271Z</atom:updated>
            <content:encoded><![CDATA[<p>Rajesh Neupane</p><p>Disclaimer : Some parts are generated using LLM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SbUHfdLJ884KySYQBPUz2A.png" /><figcaption>ChatGPT generated Image</figcaption></figure><p>Imagine this: you’re driving a sleek, modern car. You push a button, and it starts. You turn the wheel, press the accelerator, and voila — you’re cruising down the highway. You don’t need to be a mechanic to drive it. In fact, millions of people drive every day without ever thinking about how an internal combustion engine works, or how software coordinates dozens of sensors to keep the car on the road.</p><p>Now, let’s shift gears — quite literally — and think about AI, particularly <strong>Large Language Models (LLMs)</strong> like ChatGPT. Many people interact with these systems daily, asking questions, generating content, summarizing long documents, or even writing code. It’s fast, intuitive, and, on the surface, almost magical. Much like the modern car, AI just seems to “work.”</p><p>But here’s the rub: while you <strong>can</strong> use both without deep knowledge, if you truly want to unlock their potential — or understand their limitations — you need to <strong>look under the hood</strong>.</p><h3>LLMs Are Like Self-Driving Cars for Language</h3><p>To continue the analogy, think of an LLM as a <strong>self-driving car</strong> for text and language. It sees your prompt like a GPS destination, calculates the best route using its training, and then generates a response word by word — or more precisely, <em>token by token</em>. A token might be a word, part of a word, or even just a character, depending on the language and context.</p><p>This process, while invisible to the user, is <em>incredibly complex</em>. But not understanding it means you’re essentially driving with your eyes closed to how the engine works — and that has consequences.</p><h3>Why “Plug-and-Play” Isn’t Always Enough</h3><p>The temptation is understandable: LLMs promise usability without prerequisites. But the danger of <strong>pure plug-and-play</strong> is that users may misuse them, misinterpret results, or fail to understand what the model can and cannot do.</p><p>Consider someone who drives a car but doesn’t understand the importance of tire pressure, oil changes, or brake maintenance. Eventually, that lack of knowledge catches up — either through inefficiency or, worse, breakdown.</p><p>Similarly, users of AI should <strong>learn at least the basics</strong>:</p><ul><li>What is a token?</li><li>How does the model generate responses?</li><li>Why can hallucinations (fabricated answers) happen?</li><li>What are temperature and top-k sampling in generation settings?</li></ul><p>These aren’t just academic curiosities. They directly affect how accurate, reliable, and safe your interaction with AI will be</p><h3>When Things Break — And They Will</h3><p>Every car, no matter how advanced, faces wear and tear. And so does every AI deployment. Prompts may stop working as expected. Models may behave unpredictably. Latency might spike. Costs can balloon. Without a working knowledge of the system, you’ll be left calling for help — or worse, you might not even know there’s a problem.</p><p>In business, academia, healthcare, and public services, blind trust in AI tools is a liability. Knowing how LLMs work — even <strong>just at a conceptual level</strong> — empowers you to make smarter decisions, detect anomalies, and use the tools with precision.</p><h3>You Don’t Need to Be a Mechanic — But You Should Know Where the Gas Cap Is</h3><p>You don’t need to write your own LLM from scratch. But knowing <strong>how a model processes a prompt</strong>, <strong>why longer inputs may be more expensive</strong>, or <strong>how to use system prompts to guide behavior</strong> can dramatically improve your results.</p><p>Much like a savvy driver knows to ease off the gas on a steep hill or switch to snow tires in winter, a thoughtful AI user knows how to structure prompts, interpret outputs critically, and adapt the tool to the task.</p><h3>Final Thoughts: A Call to Responsible AI Use</h3><p>We are at a turning point in technology adoption. AI is no longer a distant tool of research labs — it’s a daily assistant, a creative partner, and a decision-making tool. But with that power comes a responsibility: to not be a passive consumer of its output, but an <em>informed user</em> of its capabilities.</p><p>Learn the basics. Ask questions. Be curious about how your AI “car” works. You’ll drive further — and more safely — if you do.</p><p>Curious where to start? Begin by learning what a “token” is, why models like ChatGPT have context limits, and how transformer architectures work at a high level. Trust me, it’ll make your AI journey a lot smoother.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb22318634d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Repeated Measure ANOVA in Python from Scratch]]></title>
            <link>https://medium.com/@rajeshneupane7/repeated-measure-anova-in-python-from-scratch-6f469f8703e2?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f469f8703e2</guid>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Wed, 11 Dec 2024 00:02:27 GMT</pubDate>
            <atom:updated>2024-12-11T00:02:27.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ddByklDlTijqa0YE" /><figcaption>Photo by <a href="https://unsplash.com/@bkaraivanov?utm_source=medium&amp;utm_medium=referral">Bozhin Karaivanov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I created this code to generate a random dataset for analyzing the effect of dietary supplements on milk yield in cows. First, I defined the parameters, including the number of cows, types of supplements, measurement dates, and times of day. I then used nested loops to simulate the data, where each cow is assigned a supplement, and milk yield measurements are taken twice daily (morning and evening) over a 2-month period. Random milk yield values were generated between 10 and 30 liters for each combination. Finally, I stored the data in a flat pandas DataFrame with columns for cow ID, supplement, date, time, and milk yield</p><pre>## Data Generation<br>import pandas as pd<br>import numpy as np<br><br># Set random seed for reproducibility<br>np.random.seed(42)<br><br># Define parameters<br>num_cows = 20<br>supplements = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]<br>days = pd.date_range(start=&quot;2024-01-01&quot;, end=&quot;2024-02-29&quot;, freq=&quot;D&quot;)<br>time_of_day = [&#39;Morning&#39;, &#39;Evening&#39;]<br><br># Create a flat dataset<br>data = []<br>for cow_id in range(1, num_cows + 1):<br>    for supplement in supplements:<br>        for day in days:<br>            for time in time_of_day:<br>                milk_yield = np.random.uniform(10, 30)  # Generate random milk yield<br>                data.append([cow_id, supplement, day, time, milk_yield])<br><br># Convert the data to a DataFrame<br>milk_yield_df = pd.DataFrame(data, columns=[&#39;Cow_ID&#39;, &#39;Supplement&#39;, &#39;Date&#39;, &#39;Time&#39;, &#39;Milk_Yield&#39;])<br><br># Display the first few rows of the dataset<br>print(milk_yield_df.head())</pre><p><strong>Purpose of Repeated Measures ANOVA for Milk Yield Dataset:</strong><br> In this analysis, repeated measures ANOVA is used to evaluate the effects of different dietary supplements on milk yield. The dataset includes measurements taken twice daily (morning and evening) for 20 cows over a two-month period. Specifically, the analysis will:</p><ol><li>Assess changes in milk yield across different times of the day (morning vs. evening).</li><li>Compare the average milk yield across three dietary supplement groups (A, B, and C).</li></ol><p><strong>Assumptions for Repeated Measures ANOVA in This Context:</strong></p><ol><li>The dependent variable, milk yield, is continuous and measured in liters.</li><li>Observations from different cows are independent of each other.</li><li>Milk yield values should follow a normal or approximately normal distribution.</li><li>Outliers in milk yield measurements should be minimal or absent to ensure robust results.</li></ol><p>These adaptations tailor the usage and assumptions of repeated measures ANOVA to the specific characteristics of the milk yield dataset, ensuring the analysis is valid and meaningful.</p><h3>Hypotheses for Milk Yield Analysis</h3><p><strong>Null Hypothesis (H0H_0):</strong><br> There is no significant difference in the mean milk yield among cows given different dietary supplements (A, B, and C) or at different times of the day (morning vs. evening).</p><p><strong>Alternative Hypothesis (HaH_a):</strong><br> At least two mean milk yields are significantly different, either among the dietary supplement groups or between the times of the day.</p><p>This formulation aligns the hypotheses with the goal of testing whether dietary supplements and time of day influence milk yield.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*yUrWFF7M96jZqKga6qQdcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*gKxuEFQTCxwLic4yXEgPRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*FXV0pcAZJ1wjDZ2EtwTQcQ.png" /></figure><pre><br><br># Means for each group<br>mu1 = df[df[&#39;Supplement&#39;] == &#39;A&#39;][&#39;Milk_Yield&#39;].mean()<br>mu2 = df[df[&#39;Supplement&#39;] == &#39;B&#39;][&#39;Milk_Yield&#39;].mean()<br>mu3 = df[df[&#39;Supplement&#39;] == &#39;C&#39;][&#39;Milk_Yield&#39;].mean()<br><br># Grand mean<br>mu = df[&#39;Milk_Yield&#39;].mean()<br><br># Printing the means in Markdown<br>from IPython.display import display, Markdown<br>display(Markdown(r&#39;$\overline{{x}}_1 = {:.3f}$&#39;.format(mu1)))<br>display(Markdown(r&#39;$\overline{{x}}_2 = {:.3f}$&#39;.format(mu2)))<br>display(Markdown(r&#39;$\overline{{x}}_3 = {:.3f}$&#39;.format(mu3)))<br>display(Markdown(r&#39;$\overline{{x}} = {:.3f}$&#39;.format(mu)))<br><br># Sample sizes for each group<br>n1 = len(df[df[&#39;Supplement&#39;] == &#39;A&#39;])<br>n2 = len(df[df[&#39;Supplement&#39;] == &#39;B&#39;])<br>n3 = len(df[df[&#39;Supplement&#39;] == &#39;C&#39;])<br><br># SS groups<br>SSgroups = n1 * (mu1 - mu)**2 + n2 * (mu2 - mu)**2 + n3 * (mu3 - mu)**2<br>display(Markdown(r&quot;$SS_{{groups}} = {:.3f}$&quot;.format(SSgroups)))</pre><p>I am calculating the means for each group (x‾1,x‾2,x‾3\overline{x}_1, \overline{x}_2, \overline{x}_3) and the grand mean (x‾\overline{x}) of milk yield to quantify the variability in milk production across different supplement groups (A, B, and C). By determining the sample sizes for each group and computing the sum of squares for groups (SSgroupsSS_{\text{groups}}), I aim to measure the extent to which the differences between group means contribute to the overall variability in the data. This step is essential for performing an Analysis of Variance (ANOVA), which will help evaluate whether the type of supplement has a statistically significant effect on milk yield.</p><p>I calculated the within-group sum of squares (SSwSS_w) for milk yield data categorized by supplement groups A, B, and C to quantify the variability within each group. I started by isolating the milk yield values for each group and computing their respective means. For each group, I then calculated the sum of squares (SSSS) by summing the squared differences between individual data points and the group mean. These calculations were performed separately for groups A, B, and C. Finally, I summed the SSSS values for all three groups to determine the total within-group sum of squares (SSwSS_w). This value provides insight into the variability within the groups, which is critical for performing an Analysis of Variance (ANOVA) to assess the effect of the supplements on milk yield.</p><pre># Means for each group<br>mu1 = df[df[&#39;Supplement&#39;] == &#39;A&#39;][&#39;Milk_Yield&#39;].mean()<br>mu2 = df[df[&#39;Supplement&#39;] == &#39;B&#39;][&#39;Milk_Yield&#39;].mean()<br>mu3 = df[df[&#39;Supplement&#39;] == &#39;C&#39;][&#39;Milk_Yield&#39;].mean()<br><br># Grand mean<br>mu = df[&#39;Milk_Yield&#39;].mean()<br><br># Printing the means in Markdown<br>from IPython.display import display, Markdown<br>display(Markdown(r&#39;$\overline{{x}}_1 = {:.3f}$&#39;.format(mu1)))<br>display(Markdown(r&#39;$\overline{{x}}_2 = {:.3f}$&#39;.format(mu2)))<br>display(Markdown(r&#39;$\overline{{x}}_3 = {:.3f}$&#39;.format(mu3)))<br>display(Markdown(r&#39;$\overline{{x}} = {:.3f}$&#39;.format(mu)))<br><br># Sample sizes for each group<br>n1 = len(df[df[&#39;Supplement&#39;] == &#39;A&#39;])<br>n2 = len(df[df[&#39;Supplement&#39;] == &#39;B&#39;])<br>n3 = len(df[df[&#39;Supplement&#39;] == &#39;C&#39;])<br><br># SS groups<br>SSgroups = n1 * (mu1 - mu)**2 + n2 * (mu2 - mu)**2 + n3 * (mu3 - mu)**2<br>display(Markdown(r&quot;$SS_{{groups}} = {:.3f}$&quot;.format(SSgroups)))</pre><p>I started by calculating the within-group variability in milk yield for each supplement group (A, B, and C). First, for group A, I extracted the milk yield values where the supplement was ‘A’ and computed the mean for these values. Then, I calculated the sum of squares (SSSS) for group A by summing the squared differences between each individual value and the group mean. Next, I repeated the same process for group B by isolating its milk yield data, calculating the mean, and computing the sum of squares. Similarly, I performed these steps for group C to get its mean and sum of squares. Finally, I summed up the sum of squares for all three groups to calculate the total within-group sum of squares (SSwSS_w), which represents the combined variability within each supplement group. This process is key to understanding how much variation exists within the groups for further analysis, such as ANOVA.</p><pre>import numpy as np<br>from IPython.display import display, Markdown<br><br># Group 1 calculations<br>group1 = df[df[&#39;Supplement&#39;] == &#39;A&#39;][&#39;Milk_Yield&#39;].values<br>mu1 = group1.mean()  # Mean of group 1<br>ss_group1 = np.sum((group1 - mu1) ** 2)  # Sum of squares for group 1<br>display(Markdown(f&#39;SS for group 1 = {ss_group1:.3f}&#39;))<br><br># Group 2 calculations<br>group2 = df[df[&#39;Supplement&#39;] == &#39;B&#39;][&#39;Milk_Yield&#39;].values<br>mu2 = group2.mean()  # Mean of group 2<br>ss_group2 = np.sum((group2 - mu2) ** 2)  # Sum of squares for group 2<br>display(Markdown(f&#39;SS for group 2 = {ss_group2:.3f}&#39;))<br><br># Group 3 calculations<br>group3 = df[df[&#39;Supplement&#39;] == &#39;C&#39;][&#39;Milk_Yield&#39;].values<br>mu3 = group3.mean()  # Mean of group 3<br>ss_group3 = np.sum((group3 - mu3) ** 2)  # Sum of squares for group 3<br>display(Markdown(f&#39;SS for group 3 = {ss_group3:.3f}&#39;))<br><br># Total within-group sum of squares<br>SSw = ss_group1 + ss_group2 + ss_group3<br>display(Markdown(f&#39;$SS_w = {SSw:.3f}$&#39;))</pre><p>I calculated the variability among the subjects and within the groups to prepare for ANOVA. First, I determined the sum of squares for the subjects (SSsubjectsSS_{\text{subjects}}) by multiplying the number of groups (k=3k = 3) by the sum of squared differences between individual subject means and the overall grand mean (μ\mu). Then, I calculated the error sum of squares (SSerrorSS_{\text{error}}) by subtracting SSsubjectsSS_{\text{subjects}} from the within-group sum of squares (SSwSS_w) that was computed earlier.</p><p>Next, I calculated the degrees of freedom (dfdf) required for ANOVA. For the groups, df1df_1 was computed as k−1k — 1, and for the error, df2df_2 was calculated as (n×k)−k(n \times k) — k, assuming a balanced design where each group has the same number of samples (n=2400n = 2400).</p><p>Following this, I computed the mean squares for groups (MSgroupsMS_{\text{groups}}) and error (MSerrorMS_{\text{error}}) by dividing their respective sum of squares (SSgroupsSS_{\text{groups}} and SSerrorSS_{\text{error}}) by their degrees of freedom. Finally, I calculated the F-statistic by dividing MSgroupsMS_{\text{groups}} by MSerrorMS_{\text{error}}.</p><p>To summarize and present these results, I used Markdown to format the output for readability, displaying the values of MSgroupsMS_{\text{groups}}, MSerrorMS_{\text{error}}, the F-statistic, and the degrees of freedom (df1df_1 and df2df_2). This step is crucial for determining whether there are significant differences between the groups in the ANOVA test.</p><pre>k=3.0<br>subject_means = mean_id_df[&#39;Milk_Yield&#39;].values<br>SSsubjects = k * np.sum( (subject_means - mu)**2 )<br><br>display(Markdown(&#39;$SS_{{subjects}} = {}$&#39;.format(round(SSsubjects,3))))<br><br># Assuming SSw and SSsubjects have been calculated earlier:<br>SSerror = SSw - SSsubjects<br><br># Displaying the result in Markdown format<br>from IPython.display import display, Markdown<br>display(Markdown(f&#39;$SS_{{error}} = {SSerror:.3f}$&#39;))<br><br><br># Assuming variables are already defined:<br># k = number of groups<br># n = number of observations per group<br># SSgroups and SSerror are calculated beforehand<br><br># Degrees of freedom for groups<br>df1 = k - 1<br><br># Degrees of freedom for error<br>df2 = (2400 * k) - k  # This assumes a balanced design (equal samples per group)<br><br># Mean squares<br>MSgroups = SSgroups / df1<br>MSerror = SSerror / df2<br><br># F-statistic<br>Fstatistic = MSgroups / MSerror<br><br># Printing results using Markdown<br>from IPython.display import display, Markdown<br>display(Markdown(f&#39;$MS_{{groups}} = {MSgroups:.3f}$&#39;))<br>display(Markdown(f&#39;$MS_{{error}} = {MSerror:.3f}$&#39;))<br>display(Markdown(f&#39;$F$-statistic $= {Fstatistic:.3f}$&#39;))<br>display(Markdown(f&#39;DF1 = {df1}, DF2 = {df2}&#39;)),</pre><p>Thanks for making till to end, you can download the entire notebook form this link</p><p><a href="https://colab.research.google.com/drive/1wZzl1x-A4wsltnP445oFMbGXG1dI-Vgx?usp=sharing">https://colab.research.google.com/drive/1wZzl1x-A4wsltnP445oFMbGXG1dI-Vgx?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f469f8703e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Plot Statistically Significant Letters on Bar Plots Using Tukey Test Results in Python]]></title>
            <link>https://medium.com/@rajeshneupane7/plotting-statically-significant-letters-on-top-of-bar-plot-using-results-post-hoc-tukey-test-in-250a9751a8df?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/250a9751a8df</guid>
            <category><![CDATA[letters]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[generation]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 19:21:56 GMT</pubDate>
            <atom:updated>2024-12-08T18:40:22.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*ie2bKvxGx_HSUDS33-C9mA.jpeg" /><figcaption>Image: BIng AI</figcaption></figure><p>Have you ever wondered how to add letters on top of a bar plot to represent statistically significant relationships between groups using Python? In this tutorial, I’ll guide you step by step through the process. We’ll keep things simple, using only a few essential libraries like statsmodels, along with Python&#39;s built-in dictionaries and list comprehensions. No need for heavy external libraries—just straightforward Python code!</p><p>At first we need to generate some some random data, for this I am going to use random module from python</p><p>I am generating randomly car brand name and some weird hypothetical prices using this code, and making sure some are statically different!</p><pre>import pandas as pd<br>import random<br>import numpy as np<br><br># Define the list of car names and their respective price ranges (mean and std deviation)<br>car_names = [&quot;toyota&quot;, &quot;mercedes&quot;, &quot;mazda&quot;, &quot;chevy&quot;, &quot;ram&quot;]<br>car_price_stats = {<br>    &quot;toyota&quot;: {&quot;mean&quot;: 7000, &quot;std&quot;: 500},<br>    &quot;mercedes&quot;: {&quot;mean&quot;: 9000, &quot;std&quot;: 800},<br>    &quot;mazda&quot;: {&quot;mean&quot;: 6500, &quot;std&quot;: 400},<br>    &quot;chevy&quot;: {&quot;mean&quot;: 7500, &quot;std&quot;: 600},<br>    &quot;ram&quot;: {&quot;mean&quot;: 8000, &quot;std&quot;: 700}<br>}<br><br># Set the number of rows for the DataFrame<br>num_rows = 1000<br><br># Generate random data<br>random_car_names = [random.choice(car_names) for _ in range(num_rows)]<br>random_avg_prices = [<br>    int(np.clip(<br>        np.random.normal(<br>            car_price_stats[car][&quot;mean&quot;], <br>            car_price_stats[car][&quot;std&quot;]<br>        ), <br>        5000, 10000<br>    ))<br>    for car in random_car_names<br>]<br><br># Create the DataFrame<br>data = {<br>    &quot;car_name&quot;: random_car_names,<br>    &quot;avg_price&quot;: random_avg_prices<br>}<br>df = pd.DataFrame(data)<br><br># Display the DataFrame<br>print(df)<br></pre><p>if we do df.head()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*I8725la4-X3SPSmMLsWrQw.png" /></figure><p>Now, we want to determine whether there is a statistically significant difference in price between the cars.</p><p>Before doing that we can return some nice descriptive statistics using this formula form researchpy, it is really clean to see what is happening in data before jumping to do any analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*oBgP2ApJWfQLzQ6jj9Qk_Q.png" /></figure><p>Now we can to anova, and see if these are statically different or not, anova tells us, at least one is different to another but it does not tells us which one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Cldu7ihljHWh75nPcNP5Q.png" /></figure><p>From the model p value, we see that they are statistically different, now we can go ahead and do post hoc test, which one are different to each other,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*nNkE8pXL8MVf9uW8xhpJQg.png" /></figure><p>We observe that Chevy and Mazda are not statistically different, while the rest of the car brands show significant differences. Therefore, Chevy and Mazda should share the same letter, distinguishing them from the other car brands.</p><p>we can use tukey plot see the differences</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2eUBG9BsI-FVZKvXDyvHg.png" /></figure><pre>df_tukey_car = pd.DataFrame(data=tukey_car._results_table.data[1:], <br>                            columns=tukey_car._results_table.data[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*ScueSJgOGdi8Hb9RaDSQ6Q.png" /></figure><p>Now we have changed the tukey results into dataframe, we can extract the relevent information from this, to generate letters.</p><pre><br>import string<br>import pandas as pd<br><br>def letters(df, alpha=0.05):<br><br>    df[&quot;p-adj&quot;] = df[&quot;p-adj&quot;].astype(float)<br><br>    # Creating a list of the different treatment groups from Tukey&#39;s<br>    group1 = set(df.group1.tolist())  # Dropping duplicates by creating a set<br>    group2 = set(df.group2.tolist())  # Dropping duplicates by creating a set<br>    groupSet = group1 | group2  # Set operation that creates a union of 2 sets<br>    groups = list(groupSet) #removed sorted from here<br><br>    # Creating lists of letters that will be assigned to treatment groups<br>    letters = list(string.ascii_lowercase)[:len(groups)]<br>    cldgroups = letters<br><br>    # the following algoritm is a simplification of the classical cld,<br><br>    cld = pd.DataFrame(list(zip(groups, letters, cldgroups)))<br>    cld[3]=&quot;&quot;<br>    <br>    for row in df.itertuples():<br>        if df[&quot;p-adj&quot;][row[0]] &gt; (alpha):<br>            cld.iat[groups.index(df[&quot;group1&quot;][row[0]]), 2] += cld.iat[groups.index(df[&quot;group2&quot;][row[0]]), 1]<br>            cld.iat[groups.index(df[&quot;group2&quot;][row[0]]), 2] += cld.iat[groups.index(df[&quot;group1&quot;][row[0]]), 1]<br>            <br>        if df[&quot;p-adj&quot;][row[0]] &lt; (alpha):<br>                cld.iat[groups.index(df[&quot;group1&quot;][row[0]]), 3] +=  cld.iat[groups.index(df[&quot;group2&quot;][row[0]]), 1]<br>                cld.iat[groups.index(df[&quot;group2&quot;][row[0]]), 3] +=  cld.iat[groups.index(df[&quot;group1&quot;][row[0]]), 1]<br><br>    cld[2] = cld[2].apply(lambda x: &quot;&quot;.join(sorted(x)))<br>    cld[3] = cld[3].apply(lambda x: &quot;&quot;.join(sorted(x)))<br>    cld.rename(columns={0: &quot;groups&quot;}, inplace=True)<br><br>    # this part will reassign the final name to the group<br>    # for sure there are more elegant ways of doing this<br>    cld = cld.sort_values(cld.columns[2], key=lambda x: x.str.len())<br>    cld[&quot;labels&quot;] = &quot;&quot;<br>    letters = list(string.ascii_lowercase)<br>    unique = []<br>    for item in cld[2]:<br><br>        for fitem in cld[&quot;labels&quot;].unique():<br>            for c in range(0, len(fitem)):<br>                if not set(unique).issuperset(set(fitem[c])):<br>                    unique.append(fitem[c])<br>        g = len(unique)<br><br>        for kitem in cld[1]:<br>            if kitem in item:<br>                if cld[&quot;labels&quot;].loc[cld[1] == kitem].iloc[0] == &quot;&quot;:<br>                    cld[&quot;labels&quot;].loc[cld[1] == kitem] += letters[g]<br><br>                #Checking if there are forbidden pairing (proposition of solution to the imperfect script)                <br>                if kitem in &#39; &#39;.join(cld[3][cld[&quot;labels&quot;]==letters[g]]): <br>                    g=len(unique)+1<br>               <br>                # Checking if columns 1 &amp; 2 of cld share at least 1 letter<br>                if len(set(cld[&quot;labels&quot;].loc[cld[1] == kitem].iloc[0]).intersection(cld.loc[cld[2] == item, &quot;labels&quot;].iloc[0])) &lt;= 0:<br>                    if letters[g] not in list(cld[&quot;labels&quot;].loc[cld[1] == kitem].iloc[0]):<br>                        cld[&quot;labels&quot;].loc[cld[1] == kitem] += letters[g]<br>                    if letters[g] not in list(cld[&quot;labels&quot;].loc[cld[2] == item].iloc[0]):<br>                        cld[&quot;labels&quot;].loc[cld[2] == item] += letters[g]<br><br>    cld = cld.sort_values(&quot;labels&quot;)<br><br>    cld.drop(columns=[1, 2, 3], inplace=True)<br>    cld= dict(zip(cld[&quot;groups&quot;], cld[&quot;labels&quot;]))<br><br>    return(cld)</pre><p>This code block would take the input as a tukey dataframe that we generated and returns the dictionary with keys being the car name values being the letters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*puS5kIjb-G54VZR5OzB2Mg.png" /></figure><p>Now, we have successfully generated the letters, and we can plot this letters in a bar chart, before that we need to generate the mean and standard error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1BKZBcE5Jo3FTvkUwH7Ag.png" /></figure><p>Now, we have data and related letters we can plot these together using this code block</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br>plt.figure(figsize=(12, 10), dpi=200)<br>error = np.full(len(df_plot_car), df_plot_car[&#39;sem&#39;])<br>custom_letters = group_labels<br><br># Create the bar plot<br>bars = plt.bar(df_plot_car[&#39;car_name&#39;], df_plot_car[&#39;mean&#39;], yerr=error, capsize=5)<br><br># Add annotations above bars<br>for bar, car_name in zip(bars, df_plot_car[&#39;car_name&#39;]):<br>    height = bar.get_height()<br>    plt.annotate(<br>        custom_letters[car_name],<br>        xy=(bar.get_x() + bar.get_width() / 2, height + 0.8),<br>        xytext=(0, 5),  # 3 points vertical offset<br>        textcoords=&quot;offset points&quot;,<br>        ha=&#39;center&#39;, va=&#39;bottom&#39;<br>    )<br><br># Set x-ticks with rotation<br>plt.xticks(<br>    ticks=range(len(df_plot_car[&#39;car_name&#39;])),<br>    labels=df_plot_car[&#39;car_name&#39;],<br>    rotation=45,<br>    ha=&#39;right&#39;<br>)<br><br># Add labels and title with larger font sizes and spacing<br>plt.xlabel(&#39;Car Names&#39;, fontsize=14)<br>plt.ylabel(&#39;Average Price in USD&#39;, fontsize=14)<br>plt.title(&#39;Average Price By Different Car Names&#39;, fontsize=16, pad=20)  # Increased title font size and added padding<br><br># Adjust layout for better spacing<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdkDuPR-bzRxKaOBwoV0ZQ.png" /></figure><p>Now we have successfully completed our task, to achieve this we have different other ways such as compact letter display, and other, However, I find this approach to be most reliable due to compatibility issues between libraries.</p><p>Thanks for the reading until the end, this is a google colab notebook with all code for this tutorial,</p><p><a href="https://colab.research.google.com/drive/15agod0EqGeH3v9uVVIn8fq_CnhdH6huf?usp=sharing">https://colab.research.google.com/drive/15agod0EqGeH3v9uVVIn8fq_CnhdH6huf?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=250a9751a8df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating statistically significant letters for multiple means comparisons in python]]></title>
            <link>https://medium.com/@rajeshneupane7/generating-statistically-significant-letters-for-multiple-means-comparisons-in-python-3f5a51d77b17?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f5a51d77b17</guid>
            <category><![CDATA[assign]]></category>
            <category><![CDATA[tukey-hsd-test]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statsmodels]]></category>
            <category><![CDATA[letters]]></category>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 03:17:13 GMT</pubDate>
            <atom:updated>2024-07-20T03:17:13.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hQaPMCEObOolp-Sb" /></figure><p>We all have a dataset in which we want to do a see if the mean from a group is statistically different form mean of another group. We can to the simple 2 tailed t-test to check this hypothesis. If we have multiple groups to compare, we need to do the post hoc test for example, tukey test.</p><p>What if we want to to plot the the means of the different groups and corresponding letter to denote the statistical relationship between other groups? Is there any python module that does it for us? or we need to write a code for this?</p><p>To answer this let begun with random data generation,</p><pre>np.random.seed(0)<br><br># Generate random data with distinct means<br>n = 50  # Number of rows per category<br><br># Mean prices for each brand<br>price_apple = np.random.normal(loc=700, scale=50, size=n)<br>price_google = np.random.normal(loc=710, scale=50, size=n)<br>price_samsung = np.random.normal(loc=705, scale=50, size=n)<br>price_redmi = np.random.normal(loc=400, scale=50, size=n)<br>price_honor = np.random.normal(loc=500, scale=50, size=n)<br><br># Combine the data<br>prices = np.concatenate([price_apple, price_google, price_samsung, price_redmi, price_honor])<br>categories = np.array([&#39;Apple&#39;] * n + [&#39;Google&#39;] * n + [&#39;Samsung&#39;] * n + [&#39;Redmi&#39;] * n + [&#39;Honor&#39;] * n)</pre><p>We want to see if there is actually difference between the average prices of the high end smartphones, we can use t test</p><pre>tukey_smartphone_price = pairwise_tukeyhsd(endog=df[&#39;Price&#39;], groups=df[&#39;High_End_Smartphones&#39;])<br><br># Convert the Tukey HSD result to a DataFrame<br>df_tukey_smart_price = pd.DataFrame(data=tukey_smartphone_price._results_table.data[1:], <br>                                    columns=tukey_smartphone_price._results_table.data[0])<br></pre><p>Now, we have the df_tukey_smart_price which contains</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*qoqvA8zcM6hVF1OgbCHBAQ.png" /></figure><p>We should assign, the specific letters to the the groups, which has has the statically significant relationship to represent relationship, we can do this by following code block</p><p>Now we can use df_tukey_smart_price datafarme to select only the the groups with the reject is True</p><pre>df_True = df.loc[df.reject == True, :]</pre><p>Now we should be able to extrac and list the uique groups by using this code block</p><pre>letters = list(string.ascii_lowercase)<br>n = 0<br><br>group1_list = df_True.group1.tolist()<br>group2_list = df_True.group2.tolist()<br>group3 = group1_list + group2_list<br>group4 = list(set(group3))<br>group5 = [str(i) for i in group4]<br>group5.sort()</pre><p>we can now initialize the dictionary to track the group labels</p><pre>gen = ((i, 0) for i in group5)<br>dictionary = dict(gen)</pre><p>We generate all possible pairs of groups and compare them. For each pair, we check if they are present in df_True</p><pre>group6 = [(group5[i], group5[j]) for i in range(len(group5)) for j in range(i + 1, len(group5))]<br><br>for pairs in group6:<br>    print(n)<br>    print(dictionary)<br><br>    try:<br>        a = df_True.loc[(df_True.group1 == pairs[0]) &amp; (df_True.group2 == pairs[1]), :]<br>    except:<br>        a.shape[0] == 0<br><br>    if a.shape[0] == 0:<br>        print(&#39;equal&#39;)<br>        if dictionary[pairs[0]] != 0 and dictionary[pairs[1]] == 0:<br>            print(&quot;1st is populated and 2nd is empty&quot;)<br>            dictionary[pairs[1]] = dictionary[pairs[0]]<br>        elif dictionary[pairs[0]] != 0 and dictionary[pairs[1]] != 0:<br>            print(&quot;both are populated&quot;)<br>            if len(list(set([c for c in dictionary[pairs[0]] if c in dictionary[pairs[1]]]))) &gt; 0:<br>                print(&quot;they have a shared character&quot;)<br>            else:<br>                print(&quot;equal but have different labels&quot;)<br>            m = 0<br>            j = 0<br>            for key, value in dictionary.items():<br>                if key != pairs[0] and len(list(set([c for c in dictionary[pairs[0]] if c in value]))) == 0:<br>                    m += 1<br>            for key, value in dictionary.items():<br>                if key != pairs[1] and len(list(set([c for c in dictionary[pairs[1]] if c in value]))) == 0:<br>                    j += 1<br>            if m == len(dictionary) - 1 and j == len(dictionary) - 1:<br>                print(&quot;unique&quot;)<br>                dictionary[pairs[1]] = dictionary[pairs[0]][0]<br>            else:<br>                print(&quot;there is at least one group in the dict that shares a char with the 1st group&quot;)<br>                dictionary[pairs[1]] = dictionary[pairs[1]] + dictionary[pairs[0]][0]<br>        else:<br>            print(&quot;both are empty&quot;)<br>            dictionary[pairs[0]] = letters[n]<br>            dictionary[pairs[1]] = letters[n]<br>    else:<br>        print(&quot;not equal&quot;)<br>        if dictionary[pairs[0]] != 0:<br>            print(&#39;1st is populated&#39;)<br>            if dictionary[pairs[1]] != 0 and len(list(set([c for c in dictionary[pairs[0]] if c in dictionary[pairs[1]]]))) == 0:<br>                print(&quot;no change&quot;)<br>            elif dictionary[pairs[1]] == 0:<br>                dictionary[pairs[1]] = letters[n + 1]<br>            elif dictionary[pairs[1]] != 0 and len(list(set([c for c in dictionary[pairs[0]] if c in dictionary[pairs[1]]]))) &gt; 0:<br>                print(&quot;need to add a letter&quot;)<br>                original_value = dictionary[pairs[1]]<br>                dictionary[pairs[1]] = letters[n]<br>                for key, value in dictionary.items():<br>                    if key != pairs[0] and len(list(set([c for c in original_value if c in value]))) &gt; 0:<br>                        dictionary[key] = original_value + letters[n]<br>        else:<br>            print(&#39;1st is empty&#39;)<br>            dictionary[pairs[0]] = letters[n]<br>            dictionary[pairs[1]] = letters[n + 1]<br>            print(dictionary)<br>        n += 1</pre><p>After processing all pairs, we update the dictionary with unique labels and ensure all group names are included.</p><pre>labels = list(dictionary.values())<br>labels1 = list(set(labels))<br>labels1.sort()<br>final_label = &#39;&#39;.join(labels1)<br><br>df2 = pd.concat([df.group1, df.group2])<br>group_names = df2.unique()<br>for GroupName in group_names:<br>    if GroupName in dictionary:<br>        print(&quot;already exists&quot;)<br>    else:<br>        dictionary[str(GroupName)] = final_label<br><br>for key, value in dictionary.items():<br>    dictionary[key] = &#39;&#39;.join(set(value))<br><br>dict2 = dict(sorted(dictionary.items()))</pre><p>After we get the possible letters we can use those to plot to in bar chart.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f5a51d77b17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find common elements in two list using python, list and set]]></title>
            <link>https://medium.com/@rajeshneupane7/find-common-elements-in-two-list-using-python-list-and-set-cc6c1ee3686d?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc6c1ee3686d</guid>
            <category><![CDATA[commons]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[elements]]></category>
            <category><![CDATA[set]]></category>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Sun, 12 May 2024 15:30:27 GMT</pubDate>
            <atom:updated>2024-05-12T15:30:27.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction: In Python, it’s a common task to find common elements between two lists. There are several approaches to achieve this, but two popular methods involve using lists and sets. In this tutorial, we’ll explore both methods, highlighting their differences and when to use each one.</p><ol><li>Using Lists: When using lists, you typically iterate over one list and check if each element exists in the other list. This approach involves nested loops and can have a time complexity of O(n²), where n is the length of the lists.</li></ol><pre>list1 = [1, 2, 3, 4, 5]<br>list2 = [3, 4, 5, 6, 7]<br><br>common_elements = []<br>for item in list1:<br>    if item in list2:<br>        common_elements.append(item)<br><br>print(&quot;Common elements using lists:&quot;, common_elements)</pre><p>Title: Exploring Common Elements Between Lists Using Python’s List and Set Data Structures</p><p>Introduction: In Python, it’s a common task to find common elements between two lists. There are several approaches to achieve this, but two popular methods involve using lists and sets. In this tutorial, we’ll explore both methods, highlighting their differences and when to use each one.</p><ol><li>Using Lists: When using lists, you typically iterate over one list and check if each element exists in the other list. This approach involves nested loops and can have a time complexity of O(n²), where n is the length of the lists.</li></ol><pre>list1 = [1, 2, 3, 4, 5]<br>list2 = [3, 4, 5, 6, 7]</pre><pre>common_elements = []<br>for item in list1:<br>    if item in list2:<br>        common_elements.append(item)</pre><pre>print(&quot;Common elements using lists:&quot;, common_elements)</pre><ol><li>Using Sets: Sets are unordered collections of unique elements in Python. They provide a faster way to find common elements between two collections because of their hashing mechanism. By converting the lists to sets, we can take advantage of set operations like intersection.</li></ol><pre>list1 = [1, 2, 3, 4, 5]<br>list2 = [3, 4, 5, 6, 7]<br><br>set1 = set(list1)<br>set2 = set(list2)<br><br>common_elements = set1.intersection(set2)<br><br>print(&quot;Common elements using sets:&quot;, common_elements)</pre><p>Comparing the Methods:</p><ul><li>Efficiency: Using sets is generally more efficient, especially for large collections, due to their hashing mechanism. Sets have an average time complexity of O(1) for common operations like adding or checking for existence.</li><li>Duplicate Handling: Lists allow duplicate elements, while sets automatically eliminate duplicates. If duplicates are present and need to be retained, you might prefer using lists.</li><li>Ordering: Lists preserve the order of elements, while sets do not guarantee any specific order.</li></ul><p>Conclusion: In summary, both lists and sets offer ways to find common elements between collections in Python. While lists provide a straightforward approach, sets offer better performance and automatic duplicate handling. Depending on the specific requirements of your task, you can choose the method that best suits your needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc6c1ee3686d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proportional Odds model(Constrained Cumulative Logit Model) in Python using Statsmodels]]></title>
            <link>https://medium.com/@rajeshneupane7/proportional-odds-model-constrained-cumulative-logit-model-in-python-using-statsmodels-04c690c658d0?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/04c690c658d0</guid>
            <category><![CDATA[model]]></category>
            <category><![CDATA[proportional]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statsmodels]]></category>
            <category><![CDATA[epidemiology]]></category>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 17:56:14 GMT</pubDate>
            <atom:updated>2024-03-20T17:56:14.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOqdqjbaouArVa7sv3PtSQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yvced?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Yves Cedric Schulze</a> on <a href="https://unsplash.com/photos/a-black-and-white-photo-of-a-lighthouse-on-a-rocky-shore-voLpGIyBzMo?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>As we have discussed the multinomial logistic regression is mainly used for the unordered classes of data, what about the models for ordered outcome variable, we have proportional odds model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxWNRDT6uRwn7ufX3iaI9g.png" /><figcaption>This is a textbook image taken from the VETERINARYEPIDEMIOLOGICRESEARCH book freely available</figcaption></figure><p>We estimate a single b1 coefficient and j(no of outcome)-1, intercepts, and for this tutorial, we are going to use the data from the url = “https://stats.idre.ucla.edu/stat/data/ologit.dta&quot;,</p><pre>import pandas as pd<br>import statsmodels.formula.api as smf<br>import seaborn as sns<br>import researchpy as rp<br>url = &quot;https://stats.idre.ucla.edu/stat/data/ologit.dta&quot;<br>data_student = pd.read_stata(url)<br></pre><p>To describe more about the data we can use</p><pre>rp.codebook(data_student)<br>#or<br>data_studnet.head()</pre><p>This hypothetical data set has a three level variable called <strong>apply</strong>, with levels “unlikely”, “somewhat likely”, and “very likely”, coded 1, 2, and 3, respectively, that we will use as our outcome variable. We also have three variables that we will use as predictors: which is a 0/1 variable indicating whether at least one parent has a graduate degree; <strong>public</strong>, which is a 0/1 variable where 1 indicates that the undergraduate institution is public and 0 private, and <strong>gpa, which is the student gpa.</strong></p><pre>plt.figure(figsize=(12, 8))<br><br>g = sns.FacetGrid(data_student, row=&#39;pared&#39;, col=&#39;public&#39;, margin_titles=True)<br>g.map_dataframe(sns.boxplot, x=&#39;apply&#39;, y=&#39;gpa&#39;, linewidth=0.75)<br>g.map_dataframe(sns.stripplot, x=&#39;apply&#39;, y=&#39;gpa&#39;, alpha=0.5, jitter=True)<br><br>plt.xticks(rotation=45, ha=&#39;right&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*qIxrIElc5dF4YYNw9ronqw.png" /></figure><p>This is a general graphical representation of the dataset.</p><p>we can fit the orderedmodel from statsmodels library, we can use from_formula methods to give input in terms of pasty format</p><pre>from statsmodels.miscmodels.ordinal_model import OrderedModel<br>model= OrderedModel.from_formula(&#39;apply~C(pared)+C(public)+gpa&#39;, data= data_student)<br>model=model.fit()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*WeHIHdWmSTKbVoDUV_dNQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*-wotil1ZYkBclOdnb1nM7w.png" /></figure><p>We are more interested to the factors rather than the coefficients, so, in this example, we can expontiate the model parameters to get the odds ratio,</p><p>We can interpret the model using odds ratio</p><p>the baseline to compare here will be the Unlikely, parents with no colleg degree and in the private university.</p><p>For those students whose parents did go to the college, the odds of being more likely (very or somewhat likely vs unlikely) to apply is 1.81 times that of the students whose parents did not go to the college, holding all other variables constant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04c690c658d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multinomial Logistic regression in python and statsmodels]]></title>
            <link>https://medium.com/@rajeshneupane7/multinomial-logistic-regression-in-python-and-statsmodels-a674c890fe1c?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a674c890fe1c</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[logistics]]></category>
            <category><![CDATA[multinomial]]></category>
            <category><![CDATA[statsmodels]]></category>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 23:49:04 GMT</pubDate>
            <atom:updated>2024-03-14T23:49:04.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Now, we can use the statsmodels api to run the multinomial logistic regression, the data that we will be using in this tutorial would be from the first we are going to import necessary packages and data is available in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngkliL6E-rvuo1P7YqtpgA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@neom?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">NEOM</a> on <a href="https://unsplash.com/photos/a-hand-reaching-up-into-a-palm-tree-lh1uDwaUPPM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><a href="https://github.com/rajeshneupane7/Multinomial-logistic-regression/blob/main/data5000_LesionScore.csv">Multinomial-logistic-regression/data5000_LesionScore.csv at main · rajeshneupane7/Multinomial-logistic-regression</a></p><p>Please fill free to use this.</p><pre>import numpy as np<br>import pandas as pd<br>from sklearn import datasets<br>data= pd.read_csv(&quot;Your data path&quot;)<br>import statsmodels.formula.api as smf</pre><p>for the description of the dataset, we can use the researchpy library which gives us code bookfunction</p><pre>import researchpy as rp<br>rp.codebook(df)</pre><p>else we can print unique values from each of the variables using following codes</p><pre>print(df[&#39;density_label&#39;].unique())<br>print(df[&#39;lesionscore&#39;].unique())<br>print(df[&#39;littertype&#39;].unique())</pre><p>[1 2 3]</p><p>[0 2 1]</p><p>[0 1]</p><p>So, we will get follwing output, density_lelvel having 3 category, lesion_score having, 3 and littertype having 2 category, and one of the assumption of the multinomial logistic regression is that the outcome is not ordered or leveled.</p><pre>model= smf.mnlogit(&#39;lesionscore~C(littertype)+C(density_label)&#39;, df).fit()</pre><p>In this model we have used statsmodels formula api, which gives us opportunity to write our model as pasty, in R. Here, lesion score is our dependent variable , litter type and density_lebel are categorical variables, coded with “C” in the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*tO--BdJ5_4jJ-5mIcbnLoQ.png" /></figure><p>As discussed earlier this will fit K-1 different models, K being outcome level, as seen in the picture.</p><p>If we want odds ratio insted of the log-odds coefficient we could, do</p><pre>np.exp(model.params<br>       )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*fLSMZZBl2MAmPFzkTNn_hA.png" /></figure><p>This gives the odds ratio of the two differnt model, when compared to the base level. From the figure 1, we have the a base level as THe baseline lesionscore is 0, littertype is 0 and density_level is 1.</p><p>Interpretation of coefficients :</p><p>Littertype 1 — The odds of the birds having lesionscore 1 is 31.48 times of having lesion score 0, in littertype 1, when compared to littertype 0, while holding all other variables in the model constant.</p><p>Or</p><p>The multinomial logit estimate for littertype1 for lesison score 1 relative to lesion score 0, is 3.44 given the other variables in the model are held constant. If a birds were to shifted to the littertype 1, the multinomial log-odds for lesionscore 1 would be expected to increase by 3.44 unit while holding all other variables in the model constant.</p><p>Similar interpretation could be performed for the rest of model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a674c890fe1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Log Likelihood ratio comparisons of two different models using python]]></title>
            <link>https://medium.com/@rajeshneupane7/log-likelihood-ratio-comparisons-of-two-different-models-using-python-8b1c668d59c5?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b1c668d59c5</guid>
            <category><![CDATA[epidemiology]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[negative-log-likelihood]]></category>
            <category><![CDATA[log-likelihood]]></category>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 21:49:18 GMT</pubDate>
            <atom:updated>2024-02-19T21:49:18.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Log likelihood is one of the methods for comparing and selection of best performing models, to be quick, we are here predicting the occurrence of the some disease condition in dairy cattle, the predictor variables of disease are herdsize, age of animal, and county where animals are located, and the all of except herdsize all other are continuous variables.</p><pre>#Import of necessary libraries<br>import pandas as pd #data reading <br>import numpy as np <br>import statsmodels.formula.api as smf<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import scipy</pre><p>loading the data , you can get the data from</p><p><a href="https://github.com/rajeshneupane7/data/blob/main/data_FMD.csv">https://github.com/rajeshneupane7/data/blob/main/data_FMD.csv</a></p><pre>data= pd.read_csv(&#39;Your file path .csv&#39;)</pre><p>Now you can fit the two different models,</p><p>where county, herdsize and age_cat(age categorical) are predictor variables and disease is a outcome variables, “C” in formula is representating the categorical nature of the variables</p><pre>model_logistic= smf.logit(formula=&quot;disease~C(county)+C(age_cat)+ herdsize&quot;, data= data).fit()<br><br></pre><p>To compare with other models we could make other variables from the variables we already have for example herdsize, so</p><p>Thus new_herd is quadradic , we could put this variable in the model</p><pre>herdsize_sq= herdsize^3</pre><pre>model_logistic_sq= smf.logit(formula=&quot;disease~C(county)+C(age_cat)+ herdsize+ herdsize_sq&quot;, data= data).fit()</pre><p>Until now, we have fitted two models, one model (first) nested to another model (second), as first one is a subset of second model, we need to find out if actually the performance of these two model differ and which model is the best :</p><p>for this we need to do loglikelihood ratio comparions, we get the loglikelihood from the</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*vbwaOTTejm6848dVsa8ulg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*fvy3z9lTmovFl6OtfaZhow.png" /></figure><p>If we look into the log-Likelihood values form the both models we can see that second model with quadratic term is better, but we don’t know if it is actually different form the other fitted model, so we need to do log-likelihood ratio test, for this we can use chi square test of likelihood ratio</p><pre>from scipy.stats.distributions import chi2<br>def likelihood_ratio(llmin, llmax):<br>    return(2*(llmax-llmin))<br><br><br>LR = likelihood_ratio(-151.10,-149.63)<br>#LR = likelihood_ratio(L1,L2)<br><br>p = chi2.sf(LR, 1) # L2 has 1 DoF more than L1</pre><p>Little bit of stat revision:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*5hUBjeiKvdTDBWO0.png" /><figcaption>log-likelihood test and associated assumptions</figcaption></figure><p>now we can see the p value, in our case is 0.08,</p><p>which is more than the o.o5, and hence we fail to reject the null hypothesis, and conclude that the both models are not statistically different.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b1c668d59c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Data Deluge: Transforming Dairy Farming with Technology]]></title>
            <link>https://medium.com/@rajeshneupane7/navigating-the-data-deluge-transforming-dairy-farming-with-technology-766fc0c1a651?source=rss-f77dddad14a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/766fc0c1a651</guid>
            <category><![CDATA[dairy-farming]]></category>
            <category><![CDATA[cows]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[employment]]></category>
            <category><![CDATA[sensors]]></category>
            <dc:creator><![CDATA[Rajeshneupane]]></dc:creator>
            <pubDate>Thu, 16 Nov 2023 17:51:56 GMT</pubDate>
            <atom:updated>2023-11-16T22:08:09.292Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-evolving landscape of dairy farming, technology has become the silent architect, weaving intricate networks of data that hold the key to optimizing operations and ensuring the well-being the cattle. From robotic milking systems to IoT-enabled sensors, modern dairy farms are generating a staggering amount of data. In this article, we delve into the challenges and opportunities presented by this data deluge, exploring how it is reshaping the dairy industry and creating a demand for a new breed of professionals — those master at both animal physiology and data analytics</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhpME_q5zDiI%3Fstart%3D238%26feature%3Doembed%26start%3D238&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhpME_q5zDiI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhpME_q5zDiI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2a5155b5788d3b5663c3210727a5cb/href">https://medium.com/media/cd2a5155b5788d3b5663c3210727a5cb/href</a></iframe><p>Let&#39;s break down the intricate dance of data orchestrated by a robotic milking system, such as the one pioneered by Lely. As the cow ambles through different gates, each equipped with sensors, a symphony of information is conducted. Entry times are recorded, accompanied by the cow&#39;s unique ID via RFID or wearables. Upon reaching the milking robot, a ballet of metrics ensues: milking duration, milking speed, and volume, coupled with the fat percentage, SNF (Solid-Not-Fat) percentage, and somatic cell counts of each teat.</p><p>Now, envision a medium to large dairy farm in the USA with 3000 cows undergoing this process twice a day. The data points generated are formidable – 6000 every day. Extend this over a month, and you&#39;re grappling with 180,000 data points. Scale it to a year, and the figure skyrockets to a staggering 2,160,000 data points. As this tidal wave of data crashes upon us, the question emerges: How do we harness its potential?</p><p>This deluge of data presents both a promise and a challenge. The sheer volume demands advanced storage solutions and processing power, creating a need for skilled individuals who can navigate the intersection of animal physiology and data analytics. In essence, the modern dairy farm is not just a hub of milk production; it has become a data-driven ecosystem.</p><p>Imagine a team of professionals deciphering this wealth of information to uncover patterns, anomalies, and trends. This isn’t merely about numbers; it’s about understanding the nuanced rhythm of a cow’s production cycle, recognizing deviations that may signal health issues, and ultimately optimizing the farm’s efficiency.</p><p>This data revolution in dairy farming isn’t just transforming how we manage information; it’s birthing new career paths. The demand for individuals proficient in both animal science and data analytics is on the rise. Roles like data analysts and farm data scientists are becoming integral to the success of dairy operations. These professionals are the interpreters of this data symphony, translating it into actionable insights that drive decision-making on the farm.</p><p>To thrive in this emerging field, one needs more than just technical skills. A deep understanding of the physiological aspects of a cow’s life, combined with the ability to navigate the intricacies of programming and data analysis, creates a potent skill set. The dairy farms of tomorrow will rely on this synergy to maximize productivity while ensuring the well-being of their herds</p><p>Beyond the immediate applications in health monitoring, the data harvested from robotic milking systems opens the door to a myriad of possibilities. Take, for instance, the optimization of feed efficiency. By correlating feeding patterns with milk production data, farms can tailor nutrition plans, minimizing waste and maximizing output. Predicting reproductive patterns and fine-tuning breeding programs are additional frontiers where data-driven insights can revolutionize traditional practices.</p><p>The interconnectedness of these variables also allows for a holistic approach to farm management. By leveraging historical data, farms can make informed decisions on resource allocation, infrastructure development, and even sustainability initiatives. The possibilities are as vast as the data sets themselves.</p><p>The wealth of data generated by robotic milking systems is not confined to the boundaries of the farm. Imagine a scenario where we go beyond individual cow health and use this data to validate the presence of diseases like mastitis across regions. By cross-referencing health data with weather patterns, we can uncover correlations that were previously elusive.</p><p>For instance, does mastitis tend to spike in regions experiencing high humidity or during certain temperature ranges? Answering these questions could enable farms to implement preemptive measures, adjusting management practices based on environmental factors. This not only enhances the health of individual cows but contributes to a more robust and resilient farming system.</p><p>The discussion around data isn’t solely confined to production metrics; it extends to the ethical and humane treatment of farm animals. In an era where animal welfare is a paramount concern, the data collected from farms can be a powerful tool for transparency and accountability.</p><p>By channeling real-time data on animal behavior, health, and living conditions to public domains, farms can address concerns raised by activists and the wider public. This direct line of communication not only debunks misconceptions but also fosters a more credible and responsible image for the dairy industry. The marriage of technology and transparency becomes a compelling response to the growing demand for ethical treatment of farm animals.</p><p>In conclusion, the integration of technology and data in dairy farming represents not just a paradigm shift but a revolution. The challenges posed by the sheer volume of data are met with equal opportunities for innovation and improvement. As we navigate this data-driven landscape, the emergence of new careers at the intersection of animal science and data analytics signals a transformative era for the dairy industry.</p><p>From predictive health management to optimized resource allocation, the applications of farm data are diverse and impactful. The proactive use of data not only enhances the efficiency and productivity of dairy operations but also addresses broader concerns around animal welfare and transparency. As we stand at the crossroads of tradition and technology, the data flowing through the veins of modern dairy farms has the potential to redefine not just how we farm but also how we perceive and interact with our bovine partners. The future of dairy farming is, indeed, data-driven.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=766fc0c1a651" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>