<?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 Binita Shrestha on Medium]]></title>
        <description><![CDATA[Stories by Binita Shrestha on Medium]]></description>
        <link>https://medium.com/@binita.bbshrestha?source=rss-8bfbc8736b90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*alnwv29jY8bIrJuIp8_AJQ.jpeg</url>
            <title>Stories by Binita Shrestha on Medium</title>
            <link>https://medium.com/@binita.bbshrestha?source=rss-8bfbc8736b90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:58:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@binita.bbshrestha/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[Decoding K-means Clustering using inR]]></title>
            <link>https://medium.com/@binita.bbshrestha/decoding-k-means-clustering-using-inr-c515f539e3bb?source=rss-8bfbc8736b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/c515f539e3bb</guid>
            <dc:creator><![CDATA[Binita Shrestha]]></dc:creator>
            <pubDate>Sun, 10 Mar 2024 20:19:09 GMT</pubDate>
            <atom:updated>2024-03-10T20:50:05.799Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Decoding K-means Clustering using R</strong></h3><p><strong>Introduction:</strong></p><p>Clustering algorithms play a crucial role in uncovering hidden patterns and structures within datasets. Among these algorithms, K-means clustering is known for its simplicity and effectiveness in partitioning data into distinct groups. In this blog post, we’ll delve into the fundamentals of implementing K-means clustering using the R programming language.</p><p><strong>Understanding K-means Clustering: </strong>At its core, K-means clustering is a partitioning algorithm designed to organize a dataset into K distinct clusters. It iteratively assigns data points to clusters based on their proximity to centroids, which represent the mean value of the cluster. This iterative process continues until convergence, with centroids being recalculated to minimize the within-cluster sum of squares.</p><figure><img alt="Elbow method in K-means clustering showing k=3" src="https://cdn-images-1.medium.com/max/1024/0*KeWE5VCbIa8HCNbA" /><figcaption>Elbow method in K-means clustering showing k=3</figcaption></figure><p>Let’s dive into a practical example of applying K-means clustering in R using a sample dataset of customer records with features such as amount spent, number of purchases, and purchase frequency for up to 200 records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*AXNTSqiO8WN-mjPf" /></figure><p><strong>Loading Libraries and Reading Sample Dataset:</strong></p><p>We begin by loading the necessary library cluster using the library(cluster). Next, we read the CSV file into R using read.csv() and store it in the variable data.</p><p><strong>Determining the Optimal Value of K:</strong></p><p>Choosing the right value for K is crucial for effective clustering. We employ the elbow method, a common technique to identify the optimal number of clusters. By calculating the within-cluster sum of squares (WSS) for different values of K, we create a plot to visualize the WSS values against the number of clusters. Cluster assignments for each data point are obtained using kmeans_model$cluster.</p><p>The K-means algorithm consists of the following steps:</p><ul><li>Initialization: Randomly select K initial centroids from the dataset.</li><li>Assignment: Assign each data point to the nearest centroid based on a distance metric (typically Euclidean distance).</li><li>Update centroids: Recalculate the centroids based on the mean of all data points within each cluster.</li><li>Repeat steps 2 and 3 until convergence criteria are met.</li></ul><p>Here, the length of 10 is chosen because we’re calculating WSS for different values of K ranging from 1 to 10. Each element in the vector will correspond to the WSS value for a particular value of K. As the loop iterates through different values of K, it calculates the WSS for each value and stores it in the WSS vector. This allows us to later plot the WSS values against the number of clusters to identify the optimal value of K using the elbow method.</p><pre>wss &lt;- numeric(10)<br>for (i in 1:10) {<br>  kmeans_model &lt;- kmeans(data, centers = i)<br>  wss[i] &lt;- sum(kmeans_model$withinss)<br>}<br>plot(1:10, wss, type = &quot;b&quot;, xlab = &quot;Number of clusters (K)&quot;, ylab = &quot;Within-cluster sum of squares (WSS)&quot;)</pre><p>Now, chosen_K &lt;- 3 based on the elbow point, we have taken k =3 and kmeans_model &lt;- kmeans(data, centers = chosen_K) perform k-means clustering on the data with a specified number of clusters. cluster_assignments &lt;- kmeans_model$cluster retrieves the cluster assignments for each data point from the resulting K-means model.</p><pre>chosen_K &lt;- 3<br>kmeans_model &lt;- kmeans(data, centers = chosen_K)<br>cluster_assignments &lt;- kmeans_model$cluster</pre><p><strong>Visualizing the Clusters:</strong></p><p>We visualize the clusters by creating a scatter plot based on the first two features (amount spent and number of purchases). Data points are plotted with different colours representing their cluster assignments, and centroids of the clusters are added to the plot.</p><figure><img alt="K-means Clustering visualization using a Scatter plot" src="https://cdn-images-1.medium.com/max/1024/0*efraUhRnb-rrb2Dh" /><figcaption>K-means Clustering visualization using a Scatter plot</figcaption></figure><p><strong>Generating Synthetic Data (Optional):</strong></p><p>We provide code to generate synthetic data for customer purchase behaviour if you don&#39;t have a sample dataset. This includes the amount spent, the number of purchases, and purchase frequency. The generated customer_data data frame was saved as a CSV file named “customer_data.csv” using write.csv().</p><pre># Set seed for reproducibility<br>set.seed(123)<br><br># Number of customers<br>num_customers &lt;- 200<br><br># Generate synthetic data for customer purchases<br>amount_spent &lt;- rnorm(num_customers, mean = 100, sd = 20)<br>num_purchases &lt;- rpois(num_customers, lambda = 5)<br>purchase_frequency &lt;- runif(num_customers, min = 0.1, max = 1)<br><br># Create a data frame<br>customer_data &lt;- data.frame(<br>  AmountSpent = amount_spent,<br>  NumPurchases = num_purchases,<br>  PurchaseFrequency = purchase_frequency<br>)</pre><p><strong>Conclusion:</strong></p><p>In this blog post, we’ve explored the implementation of K-means clustering in R, covering key concepts, practical examples, and visualization techniques. With this knowledge, beginners can begin their journey into the world of clustering analysis and uncover valuable insights within their datasets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c515f539e3bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KaggleX BIPOC Mentorship Program Journey: Geospatial Analysis of Air Pollution Data:]]></title>
            <link>https://medium.com/@binita.bbshrestha/kagglex-bipoc-mentorship-program-journey-geospatial-analysis-of-air-pollution-data-0814a389fd8c?source=rss-8bfbc8736b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/0814a389fd8c</guid>
            <dc:creator><![CDATA[Binita Shrestha]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 22:52:18 GMT</pubDate>
            <atom:updated>2023-11-18T13:58:50.724Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>KaggleX BIPOC Mentorship Program:</strong></blockquote><blockquote>I began the <a href="https://www.kaggle.com/kagglex">KaggleX BIPOC Mentorship Program</a> journey as a mentee which evolved into a transformative experience that has opened new horizons in the field of data science. This Program has been invaluable to my growth, transcending the boundaries of traditional learning and paving the way for exciting opportunities.</blockquote><blockquote>What made this experience truly remarkable is the privilege of working closely with a dedicated mentor <a href="https://www.linkedin.com/in/ggiasemidis/">Dr Georgios Giasemidis</a>, Lead Data Scientist at Choreograph whose expertise and guidance have been instrumental in navigating the complexities of this geospatial data analysis project. The application of air quality metrics and the nuances of working with geospatial data have expanded my knowledge and problem-solving capabilities.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Dglg0E_EkVT8nq06L5olg.png" /><figcaption>KaggleX BIPOC Mentorship Program Certificate</figcaption></figure><p><strong>Unveiling Air Quality Insights: Geospatial Analysis of Air Pollution Data:</strong></p><p>In a world where the air we breathe directly impacts our health and the environment, understanding air quality is paramount. This blog explored the findings of a geospatial data analysis project that delved into air quality data at three geographic levels, including global countries, USA states, and USA counties. The project aimed to assess trends and variations in air quality from 2019 to 2022, highlighting regions with the best and worst air quality, identifying outliers, and tracking changes over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whB3ydmrA_qpcC_U2BPF0A.png" /></figure><p><strong>Analyzing Air Quality Metrics:</strong></p><p>At the core of this project was a deep dive into air quality metrics, including the Air Quality Index (AQI), carbon monoxide (CO), ground-level ozone (O3), nitrogen dioxide (NO2), particulate matter (PM2.5 and PM10), and sulfur dioxide (SO2). These metrics are the measuring benchmarks set by the government through which air quality is assessed, evaluated and monitored, and they provide essential insights into the state of our atmosphere.</p><p><strong>Data Sources:</strong></p><p>The data was collected from various sources as below:</p><p>1. Air quality data</p><p>Country Level: <a href="https://www.kaggle.com/datasets/hasibalmuzdadid/global-air-pollution-dataset">Air Quality Index- World Pollution Dataset by Kaggle</a></p><p>USA states and counties Level: <a href="https://aqs.epa.gov/aqsweb/airdata/download_files.html">Air Quality Index- USA pollution Dataset 2019–22 by Environmental Protection Agency</a></p><p>2. Geography data and Boundary data</p><p><a href="https://datahub.io/core/geo-countries#resource-geo-countries_zip">World Countries by Datahub</a></p><p><a href="https://datahub.io/core/geo-countries#resource-geo-countries_zip">USA States Dataset by Datahub</a></p><p><a href="https://public.opendatasoft.com/explore/dataset/us-county-boundaries/export/?disjunctive.statefp&amp;disjunctive.countyfp&amp;disjunctive.name&amp;disjunctive.namelsad&amp;disjunctive.stusab&amp;disjunctive.state_name">USA Counties dataset by Opendatasoft</a></p><p><strong>Visualization:</strong></p><p>The collected data was then processed and aggregated. For country-level analysis, the median Air Quality Index (AQI) based on data from cities within each country was calculated. This approach allowed us to capture the overall air quality status for each country. We have selected the USA as an example for state and county-level air quality analysis, the air quality data was therefore merged with the respective state or county geometries to create spatial representations. For the visualization, we leveraged geospatial libraries, such as GeoPandas, to create choropleth maps. The <a href="https://github.com/waxxeBinita/Geospatial-Analysis-of-Air-Pollution-Data/blob/master/.idea/Geospatial_Analysis_of_Air_Pollution_Data.ipynb">notebook</a> is available here.</p><p><strong>Key Findings:</strong></p><p>Based on the dataset we have used, the key findings of the project at world countries, USA states and USA counties levels were:</p><ol><li><strong>Country Level: </strong>One of the primary findings of this project underscored the pressing need for improved air quality in specific regions, particularly South Asia and North Africa. These areas exhibited notably high Air Quality Index (AQI) values, signifying poor air quality. In contrast, continents like Australia and South America stand out with lower AQI values, indicating cleaner and healthier air. The project incorporated visualizations such as choropleth maps and boxplots to present AQI variations, offering valuable insights for real-world interventions and effective environmental policies.</li></ol><p><strong>2. USA State Level: </strong>At the USA state level, the geospatial analysis revealed significant improvements in air quality from 2019 to 2022. States like Texas, Nebraska, and Montana, which experienced poor air quality in 2019, have remarkably transformed into leaders in maintaining the best air quality by 2022. In contrast, Kansas experienced a decline in air quality over the same period, signalling the need for enhanced air quality interventions. Alaska stands out for consistently maintaining good air quality throughout the years, highlighting the effectiveness of its air quality management measures.</p><p><strong>3. USA County Level:</strong> Analyzing air quality at the USA county level, the project identified Riverside County as consistently recording the highest maximum AQI values, indicating areas with persistent air quality challenges. In contrast, Latah County consistently displayed the lowest median AQI values, setting an example of better air quality at the county level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-6-0kcaYZKdyQ6_l2D1_Q.gif" /></figure><p>These county-level insights can be useful for providing valuable information for policymakers and public health officials, supporting effective air quality management and emphasizing areas that require immediate attention. In conclusion, air quality is a matter of public health, environmental sustainability, and overall well-being. This geospatial data analysis project highlighted the importance of addressing air quality challenges, whether at the country, state, or county level, offering a window into the global state of our atmosphere and highlighting areas where action is urgently needed.</p><blockquote><strong>Looking Ahead:</strong></blockquote><blockquote>The mentorship relationship with my mentor and kaggle team doesn’t end with end of the program but it continues further. I aim to make the project more interactive and user-friendly using Streamlit or the Shiny app. I believe that by incorporating real-time air quality data sources, it can provide timely updates on air quality conditions, enabling stakeholders to explore air quality insights effortlessly.</blockquote><blockquote>Additionally, to further enhance my geospatial data science capabilities, I will be participating in a <a href="https://spatial-data-science-conference.com/bootcamps/2023">Spatial Data Science Bootcamp</a> by <a href="https://carto.com/">CARTO</a> in 23rd of November 2023, and what makes this journey incredibly exciting is that my mentor helped facilitate my enrollment in this exciting bootcamp.</blockquote><blockquote>This Kaggle journey has not only been about analyzing data; it has been a profound learning experience. It has reinforced the importance of mentorship and the value of collaborative learning within the Kaggle community. It has been a journey of self-discovery, skill enhancement, and, most importantly, a journey that has nurtured a passion for data science and geospatial analysis. Continuing on this path, I look forward to contributing to Kaggle’s collaborative community, where I can share my insights, learn from the community, and embark on more data-driven adventures. This journey has ignited a passion for exploring the world of data science and geospatial analysis, and I’m eager to see where it takes me next.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0814a389fd8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logistic Regression]]></title>
            <link>https://medium.com/@binita.bbshrestha/logistic-regression-517a4283b326?source=rss-8bfbc8736b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/517a4283b326</guid>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Binita Shrestha]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 19:32:25 GMT</pubDate>
            <atom:updated>2023-04-25T15:31:04.424Z</atom:updated>
            <content:encoded><![CDATA[<p>Logistic regression is a statistical classification algorithm used to predict the probability of a binary outcome (0 or 1) based on one or more input variables. In other words, it is a predictive model that can be used to classify data into two classes based on some input variables. The model uses a training dataset to estimate the parameters of the logistic function, and then uses these parameters to predict the class of new data points and shows its output in the form of an S-shaped curve or sigmoid curve.</p><blockquote>Let’s take an example to understand logistic regression.</blockquote><figure><img alt="Receiver Operating Characteristic(ROC) curve using Confusion Metrics" src="https://cdn-images-1.medium.com/max/547/1*YPvLeKhEaHYPhn1dDCVkBA.png" /><figcaption>Receiver Operating Characteristic(ROC) curve for true positive rate against the false positive rate.</figcaption></figure><blockquote>To build a logistic regression model, we need a dataset with observations of customers’ gender, age, estimated salary, and whether they purchased the product or not. We have used a s<a href="https://github.com/waxxeBinita/Regression/blob/main/LRdata.csv">ample dataset</a> to train the model to learn the relationship between the independent variables and the dependent variable.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIaz_BgqTbwLjlJfpz7BuQ.png" /></figure><p>In this case, the dependent variable is whether the customer will make a purchase of the product or not, and it can take the encoded two values: 0 for not purchasing and 1 for purchasing.</p><pre>label_encoder = preprocessing.LabelEncoder()<br>df[&#39;Purchased&#39;]= label_encoder.fit_transform(df[&#39;Purchased&#39;])<br>df.Purchased.unique()</pre><p>We have considered the independent variables as feature_cols that include gender, age and income.</p><pre>feature_cols = [&#39;Gender&#39;, &#39;Age&#39;, &#39;EstimatedSalary&#39;]<br>X = df[feature_cols] # dependent variables<br>y = df.Purchased # Target variable</pre><p>A logistic regression model is then created using the LogisticRegression class. The model is fitted to the training data using the fit method, and the classes of the test set are predicted using the predict method.</p><p>First, let’s import the necessary libraries and split the data into training and testing sets:</p><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br>clf = LogisticRegression(random_state=42)<br>clf.fit(X_train, y_train)</pre><p>This example uses a simple dataset with a single feature (X) and a binary outcome (y). The dataset is split into train and test sets using the train_test_split function where 80% of the data is used for model training and 20% for model testing.</p><pre>X_test= [[1, 19,19000]]<br>y_pred = clf.predict(X_test)<br>if y_pred[0] == 0:<br>print(&quot;The customer did not purchased the product.&quot;)<br>else:<br>print(&quot;The passenger purchased the product.&quot;)</pre><p>Finally, the accuracy of the model is evaluated using the accuracy_score function. There are different ways to evaluate the accuracy of a logistic regression model.</p><p>For example, let’s say we have a female customer who is 19 years old and earns $19,000 per year. Based on our logistic regression model, we predict that this customer has a 98% chance of purchasing the product.</p><pre>#option one<br>accuracy = accuracy_score(y_test, y_pred)<br>print(“Accuracy:”, accuracy)</pre><p>Let’s use a confusion matrix for this example to summarize the performance of the classification algorithm.</p><pre>#option two<br>from sklearn import metrics<br>cnf_matrix = metrics.confusion_matrix(y_test, y_pred)<br>cnf_matrix</pre><pre>#now let&#39;s visualize confusion metrics using heatmap<br># import required modules<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>class_names=[0,1] # name  of classes<br>fig, ax = plt.subplots()<br>tick_marks = np.arange(len(class_names))<br>plt.xticks(tick_marks, class_names)<br>plt.yticks(tick_marks, class_names)<br><br># create heatmap<br>sns.heatmap(pd.DataFrame(cnf_matrix), annot=True, cmap=&quot;YlGnBu&quot; ,fmt=&#39;g&#39;)<br>ax.xaxis.set_label_position(&quot;top&quot;)<br>plt.tight_layout()<br>plt.title(&#39;Confusion matrix&#39;, y=1.1)<br>plt.ylabel(&#39;Actual label&#39;)<br>plt.xlabel(&#39;Predicted label&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*UULUfeOw1IPDzS5v4Ng99Q.png" /><figcaption>Text(0.5, 427.9555555555555, ‘Predicted label’)</figcaption></figure><p>From the above output, we can see that confusion matrix in the form of the array object with 2*2 matrix dimension,</p><p>This is a binary classification with 0 and 1 classes where diagonals value represent accurate predictions [output 51 and 14] and non-diagonal show incorrect predictions [output 1 and 0]</p><pre>#plotting Receiver Operating Characteristic(ROC) curve for true positive rate against the false positive rate.<br>#shows tradeoff between sensitivity and specificity. <br>y_pred_proba = clf.predict_proba(X_test)[::,1]<br>fpr, tpr, _ = metrics.roc_curve(y_test,  y_pred_proba)<br>auc = metrics.roc_auc_score(y_test, y_pred_proba)<br>plt.plot(fpr,tpr,label=&quot;data 1, auc=&quot;+str(auc))<br>plt.legend(loc=4)<br>plt.show()</pre><p>In summary, logistic regression is a useful technique for predicting binary outcomes based on one or more independent variables. It allows us to model the probability of a binary outcome as a function of the independent variables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517a4283b326" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering (Series)]]></title>
            <link>https://medium.com/@binita.bbshrestha/clustering-series-e12de453d7a?source=rss-8bfbc8736b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/e12de453d7a</guid>
            <dc:creator><![CDATA[Binita Shrestha]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 13:31:39 GMT</pubDate>
            <atom:updated>2024-03-10T20:39:46.076Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clustering</h3><p>Are you struggling to understand your customer in better ways for launching your next marketing campaigns? Well, then without any doubt, clustering can help you achieve magical segmentations including demographic, geographical, psychographic, and behavioural segmentations and impress your boss or yourself.</p><p><strong>What is Clustering?</strong></p><p>Clustering is one of the most popular techniques used under unsupervised machine learning. It is widely used in science, medication, showcasing, marketing, and others because of its information-mining features. The algorithm deals with the unlabeled dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ng6xOsHud2aAa8QQCVYwEA.png" /><figcaption>The result of a cluster analysis is shown as the colouring of the squares into three clusters.</figcaption></figure><p>In cluster analysis of data mining, the datasets are divided into specific gatherings known as clusters. These statistical data analysis techniques are an exceptionally renowned AI model to tackle numerous complex issues. The primary reason for conducting data analysis in this method is to check for likenesses and patterns. The datasets are looked for bits of knowledge utilising explicit calculations with specific boundaries reasonable for market analysis. From the above figure, we see three distinct clusters while dissecting datasets, and those share similarities yet differentiate from each other.</p><p>Some of the most common applications of clustering include:</p><ol><li>Market segmentation</li><li>Image segmentation</li><li>Social network analysis</li><li>Statistical data analysis</li><li>Anomaly detection and more.</li></ol><p>Find Decoding K-means Clustering using R here: <a href="https://rb.gy/wmy1yc">https://rb.gy/wmy1yc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e12de453d7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>