<?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 Rigat Nirayo on Medium]]></title>
        <description><![CDATA[Stories by Rigat Nirayo on Medium]]></description>
        <link>https://medium.com/@rigatanirayo?source=rss-981d5bd49c3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OpQzuiPkpz0X2B6nE2eAsg.jpeg</url>
            <title>Stories by Rigat Nirayo on Medium</title>
            <link>https://medium.com/@rigatanirayo?source=rss-981d5bd49c3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:38:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rigatanirayo/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[The Perils of Class Imbalance Corrections in Risk Prediction Models]]></title>
            <link>https://medium.com/@rigatanirayo/the-perils-of-class-imbalance-corrections-in-risk-prediction-models-8a20f4556491?source=rss-981d5bd49c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a20f4556491</guid>
            <dc:creator><![CDATA[Rigat Nirayo]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 01:22:34 GMT</pubDate>
            <atom:updated>2024-01-19T20:01:18.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bKLWTxm_WmSKTFum" /><figcaption>Photo by <a href="https://unsplash.com/@johnmoeses?utm_source=medium&amp;utm_medium=referral">John Moeses Bauan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I encountered an intriguing journal article and found it quite interesting. Therefore, I’ve decided to create a summary for it. Here is the <a href="http://I encountered an intriguing journal article and found it quite interesting. Therefore, I&#39;ve decided to create a summary for it. Here is the link to the complete journal article.">link</a> to the complete journal article.</p><h3>Introduction</h3><p>In the dynamic landscape of machine learning, the quest for accurate risk prediction models is unceasing. However, a critical aspect often overlooked is the handling of class imbalances within datasets. This blog delves into the complexities and potential harms associated with class imbalance corrections, with a focus on illustration and simulation using logistic regression.</p><h3>Understanding Class Imbalance</h3><p>Class imbalance occurs when the distribution of classes in a dataset is uneven, leading to challenges in training models. In the realm of risk prediction, this imbalance can be particularly pronounced, as certain outcomes may be rare compared to others.</p><h3>Common Approaches to Class Imbalance</h3><p>To address class imbalance, practitioners often turn to various techniques, such as oversampling the minority class, undersampling the majority class, or using advanced algorithms designed to handle imbalanced data. While these methods may seem intuitive, their application is not without consequences.</p><h3>The Pitfalls of Oversampling</h3><p>Oversampling involves increasing the instances of the minority class to balance the dataset. However, this approach can lead to overfitting, where the model becomes too tailored to the minority class and loses its generalization ability. The risk of producing overly optimistic results on imbalanced datasets is a concern that should not be underestimated.</p><h3>Undersampling Dilemmas</h3><p>Conversely, undersampling reduces the instances of the majority class, aiming to create a more balanced dataset. Yet, this approach sacrifices potentially valuable information from the majority class, which can hinder the model’s ability to capture the true complexities of the problem.</p><h3>Simulation Using Logistic Regression</h3><p>To illustrate the potential harms of class imbalance corrections, logistic regression provides a suitable framework for exploration. Through simulation, we can observe the impact of oversampling and undersampling on model performance metrics, such as accuracy, precision, recall, and F1 score.</p><h3>Results and Insights</h3><p>Our simulated scenarios uncover the nuanced effects of class imbalance corrections. While these techniques may appear to enhance model performance, they often come at the cost of introducing bias, reducing the model’s interpretability, and yielding unreliable predictions.</p><h3>Conclusion</h3><p>In the pursuit of robust risk prediction models, acknowledging the pitfalls of class imbalance corrections is paramount. Oversimplifying the complexities of imbalanced datasets can lead to unintended consequences, compromising the very essence of accurate risk assessment. Striking a delicate balance between addressing class imbalances and preserving the integrity of the dataset is the key to navigating this intricate terrain. As the machine learning community continues to innovate, a nuanced understanding of class imbalance corrections is essential for building models that stand the test of real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a20f4556491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Yelp API: Exploring Data for Sushi Restaurants]]></title>
            <link>https://medium.com/@rigatanirayo/a-guide-to-yelp-api-exploring-data-for-sushi-restaurants-a7b3a611926e?source=rss-981d5bd49c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7b3a611926e</guid>
            <dc:creator><![CDATA[Rigat Nirayo]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 07:53:04 GMT</pubDate>
            <atom:updated>2023-12-28T08:06:42.209Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1DlQFdahDd4l5Bfd" /><figcaption>Photo by <a href="https://unsplash.com/@deram31?utm_source=medium&amp;utm_medium=referral">Riccardo Bergamini</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sushi holds a special place as my cherished and preferred dish these days. Nigiri and maki (rolled sushi) stand out as my favorites. The delightful combination of freshness and chewy texture fills the mouth with satisfaction.If you share a similar sentiment, feel free to comment. This guide will center around sushi restaurants, demonstrating the step-by-step process of leveraging the Yelp API.</p><p>To access the Yelp API you need a key, which you can easily register for<a href="https://www.yelp.com/login?return_url=/developers/v3/manage_app"> here.</a></p><p>Steps i followed</p><p>first lets import necessary libraries</p><pre>import requests<br>import pandas as pd <br>import json</pre><p>The provided code sets up the necessary parameters to query the Yelp API for information about sushi restaurants in San Jose. The headers variable includes the authentication token for secure access, and the params variable specifies the location, search term (&#39;Sushi&#39;), and limits the results to 50. The url variable defines the API endpoint for business searches on Yelp. This compact script serves as a foundation for retrieving detailed data on sushi establishments in San Jose through the Yelp API.</p><pre>api_key=&#39;replace with your api key&#39;<br>headers = {&#39;Authorization&#39;: f&#39;Bearer {api_key}&#39;}<br>params = {&#39;location&#39;: &#39;san jose&#39;, &#39;term&#39;: &#39;Sushi&#39;,&#39;limit&#39;:50}<br>url = &#39;https://api.yelp.com/v3/businesses/search&#39;</pre><p>lets define a function, fetch_data_with_offset, which is designed to retrieve data from a specified API endpoint with pagination, where the API allows for offset-based pagination. The “offset” indicates the starting point or position from which the API should begin returning results.</p><p>It takes the API URL (url), parameters for the request (par), and the maximum offset (max_offset) as input parameters. The function iterates through the API responses, incrementing the offset by 50 for each iteration until reaching the specified maximum offset. It appends the retrieved data to a Pandas DataFrame. If the response status code is 200, indicating a successful request, the function extracts and normalizes relevant JSON data from the &#39;businesses&#39; or &#39;reviews&#39; keys, depending on their presence in the response. If the status code is not 200, an error message is printed, and the function breaks out of the loop. The resulting DataFrame is then returned.</p><p>This function provides a flexible and reusable solution for handling paginated requests and extracting data from APIs with offset-based pagination.</p><pre>def fetch_data_with_offset(url,par,max_offset):<br>    data=pd.DataFrame()<br>    offset=0<br>    count=0<br>    <br>    while offset&lt;=max_offset:<br>        par.update({&#39;offset&#39;: offset})<br>        response = requests.get(url,params=par ,headers=headers)<br>        json_data=response.json()<br>        if &#39;businesses&#39; in json_data.keys():<br>            data=data.append(pd.json_normalize(json_data[&#39;businesses&#39;]))<br>        else:<br>            data=data.append(pd.json_normalize(json_data[&#39;reviews&#39;]))<br><br>        offset+=50<br>           <br>    return data</pre><p>Now we can call the function by passing url and params with maximum offset we want. It makes multiple requests with a maximum offset of 100, collecting information about businesses such as their names, locations, and ratings. The resulting data is stored in the &#39;businesses_df&#39; DataFrame.</p><pre>businesses_df=fetch_data_with_offset(url,params,100)<br>businesses_df.shape<br>#we will get (150, 24)</pre><p>Next lets fetch reviews for each restaurant in a DataFrame (‘businesses_df’) . It iterates through the restaurant IDs, constructs review API URLs, and then employs the offseting2 function to accumulate review data. The &#39;params2&#39; dictionary specifies a limit of 50 reviews per request.</p><p>The resulting review data is stored in the &#39;reviews_df&#39; DataFrame. This code efficiently retrieves and compiles a substantial amount of review data for the specified restaurants, facilitating a comprehensive analysis of customer feedback.</p><pre>url=[]<br>for index , value in enumerate(businesses_df.id):<br>    url.append(f&#39;https://api.yelp.com/v3/businesses/{value}/reviews&#39;)<br><br>review_params={&#39;limit&#39;:50}<br>reviews_df=pd.DataFrame()<br>for i in url:<br>    reviews_df=reviews_df.append(fetch_data_with_offset(i,review_params,5))<br>    <br>reviews_df.shape<br># (444, 9), for each business we get </pre><p>To combine the two data frames, we can identify a common key for merging. One approach is to create a new column, ‘alias,’ derived from the restaurant URLs, capturing the restaurant alias names. Following this, we can merge the two data frames using the ‘alias’ column as the key. This strategy facilitates the integration of business details and reviews, providing a unified dataset for comprehensive analysis.</p><pre>reviews_df.url.head(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5kmMilNrUDcOJUa6hxrVg.png" /><figcaption>output</figcaption></figure><pre>reviews_df[&#39;alias&#39;] = reviews_df[&#39;url&#39;].str.extract(r&#39;/biz/([^/?]+)&#39;)<br>bus_review=pd.merge(new_buss_df , reviews_df , on=&#39;alias&#39; , how=&#39;inner&#39;)</pre><p>I hope you found this helpful and ,I welcome any comments or feedback.Thank you for taking the time to read. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7b3a611926e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hybrid :Pandas + SQLite]]></title>
            <link>https://medium.com/@rigatanirayo/hybrid-pandas-sqlite-8c384c4b65cc?source=rss-981d5bd49c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c384c4b65cc</guid>
            <dc:creator><![CDATA[Rigat Nirayo]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 03:53:08 GMT</pubDate>
            <atom:updated>2023-11-29T03:53:08.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hybrid :Pandas + SQLite</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbh9OYfxrDv-hs4J" /><figcaption>Photo by <a href="https://unsplash.com/@ispywithmylittleeye?utm_source=medium&amp;utm_medium=referral">Zeynep Sümer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a data scientist, Almost 80% — of the workload revolves around data manipulation. Both Pandas and SQLite queries in Python serve distinct roles in handling and manipulating data, and their effectiveness hinges on the particular task at hand. In this blog, I endeavor to explore different scenarios where the interchangeability of SQLite and Pandas proves beneficial, aiming to elevate the data manipulation and analysis to unprecedented levels of efficiency. The integration of the strengths of both tools in a hybrid approach emerges as a pivotal strategy, fostering the workflow that is not only flexible but also potent.</p><h3>1. Storing and cleaning</h3><p>Pandas offers extensive data cleaning and exploration functions, making it preferable. However, its efficiency is notable when handling smaller datasets that fit into machine memory. On the other hand, SQLite is well-suited for complex transformations and analysis on large datasets because it performs operations directly on disk-stored tables. In this kind of scenario, it is preferable to use SQLite to store the data persistently and use Pandas for cleaning and manipulating the dataset.</p><pre># Pandas for data cleaning<br>import pandas as pd<br><br># SQLite for data storage<br>import sqlite3<br><br># Read and clean data using Pandas<br>data = pd.read_csv(&#39;large_dataset.csv&#39;)<br>cleaned_data = data.dropna()<br><br># Store cleaned data in SQLite<br>conn = sqlite3.connect(&#39;data.db&#39;)<br>cleaned_data.to_sql(&#39;cleaned_data&#39;, conn, index=False)<br></pre><h3>2. Data Transformations</h3><p>To perform extensive aggregations, grouping, and joins using SQLite within the database. This approach aids in reducing the data volume before importing it into Python, ensuring that only essential data is brought in for analysis, which is well-suited for our limited machine memory. After obtaining the trimmed data in Python, we can then proceed to conduct further analyses using Pandas.</p><pre><br># Let&#39;s connect to our database named &#39;Employees.db&#39; as example<br>conn = sqlite3.connect(&#39;Employees.db&#39;)<br><br># Read the aggregated data into a Pandas DataFrame<br>query = &#39;&#39;&#39;<br>    WITH DepartmentAverages AS (<br>        SELECT<br>            department,<br>            AVG(salary) AS avg_salary<br>        FROM<br>            employees<br>        GROUP BY<br>            department<br>    )<br><br>    SELECT<br>        *<br>    FROM<br>        DepartmentAverages;<br>&#39;&#39;&#39;<br><br>df = pd.read_sql(query, conn)<br><br># Further analysis with Pandas<br># For example, you can filter the data for departments with average salary above a value<br>filtered_data = df[df[&#39;avg_salary&#39;] &gt; 50000]</pre><h3>3. Exploration and Analysis</h3><p>Pandas provides a versatile environment for exploratory data analysis, while SQLite enables efficient querying. By transitioning between pandas and SQLite strategically, data scientists can conduct a comprehensive and resource-efficient exploration and analysis of their datasets.</p><pre><br># Load data into Pandas DataFrame - lets use employees database as example<br>students_df = pd.read_csv(&#39;students.csv&#39;)<br><br># data exploration examples<br>students_df.describe()<br>students_df.head()<br>students_df[&#39;Gender&#39;].value_counts()<br><br># Visualizations using simple pandas plot for data exploration <br>students_df[&#39;Gender&#39;].plot(kind=&#39;hist&#39;, bins=10, edgecolor=&#39;black&#39;)</pre><pre># Establish a connection to SQLite database<br>conn = sqlite3.connect(&#39;Class.db&#39;)<br><br># Store the Pandas DataFrame in SQLite<br>data.to_sql(&#39;students_df&#39;, conn, index=False)</pre><pre># SQLite for efficient querying<br>query = &#39;&#39;&#39;<br>    SELECT Status,Gender COUNT(*) As Count<br>    FROM students_df<br>    WHERE Status== &#39;Pass&#39;<br>    GROUP BY Status, Gender;<br>&#39;&#39;&#39;<br><br># Execute the query and load results into a Pandas DataFrame<br>query_result = pd.read_sql(query, conn)</pre><h3>Conclusion:</h3><p>By strategically combining the strengths of Pandas and SQLite, you can create a powerful and efficient workflow for your data analysis tasks. Whether it’s handling large datasets or performing complex transformations, the synergy between these two tools opens up a world of possibilities. Experiment with this hybrid approach in your projects, and witness the enhanced efficiency and flexibility it brings to your data-driven endeavors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c384c4b65cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Less expensive python methods]]></title>
            <link>https://medium.com/@rigatanirayo/less-expensive-python-methods-48987277da76?source=rss-981d5bd49c3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/48987277da76</guid>
            <dc:creator><![CDATA[Rigat Nirayo]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 04:51:35 GMT</pubDate>
            <atom:updated>2023-11-08T05:14:44.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7Eef43-CrBjQ-A2i" /><figcaption>Photo by <a href="https://unsplash.com/@obionyeador?utm_source=medium&amp;utm_medium=referral">Obi - @pixel8propix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Python is ideal choice for data science due to its rich libraries and tools like numpy , pandas , matplotlib and many more. However, when working with large datasets and complex analysis , memory and performance can become significant concerns. When i refer to less expensive python methods it is in terms of computational resources (CPU and memory usage).</p><p>I came to understand those two ways are more efficient to use:</p><h4>Indexing instead of .get() method</h4><p>The .get()method returns the value of any given key from the dictionary. If the key is not in the dictionary it returns a <em>None</em> value without raising an error.</p><pre>data={&#39;A&#39;:[1,2,3] , &#39;B&#39;:[4,5,6] , &#39;C&#39;:[7,8,9]}<br>df=pd.DataFrame(data)<br>%timeit value = df.get(&#39;A&#39;)<br><br>#output<br>#2.11 µs ± 227 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)</pre><p>On the other hand using indexing is faster and less expensive as it directly grabs the value associated with the key. It raises a ‘<em>keyError’</em> if the key we passed is not in the dictionary. it is also easier to read.</p><pre>data={&#39;A&#39;:[1,2,3] , &#39;B&#39;:[4,5,6] , &#39;C&#39;:[7,8,9]}<br>df=pd.DataFrame(data)<br>%timeit value = df[&#39;A&#39;]<br><br>#output<br>#1.87 µs ± 13.1 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)</pre><p>Using indexing takes less time to execute compared to the .get() method.</p><h4><strong>pandas .mean() or np.mean()</strong></h4><p>During my analysis of a freely available dataset from <a href="https://www.kaggle.com/datasets/cygmeda/ames-housing-prices">Kaggle</a>, which contains housing price information for Ames, Iowa, I utilized the NumPy np.mean() method to create a vertical line indicator that represents the mean of the &#39;SalesPrice&#39; feature. I got curious to know whether using the NumPy mean method is more efficient compared to the pandas mean method for this particular task. In my quest for answers, I conducted research and performed a timeit analysis to measure the execution times of both.</p><pre>#pandas mean<br><br>%timeit df[&#39;SalePrice&#39;].mean()<br><br>#output<br>#26.7 µs ± 211 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)</pre><pre>#numpy mean<br><br>%timeit np.mean(df[&#39;SalePrice&#39;])<br><br>#output<br>#37.8 µs ± 1.84 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)</pre><p>Based on the comparison of execution times, it appears that using pandas for calculating the mean of ‘SalePrice’ is more efficient. Pandas <em>‘.mean()’</em> calculates the mean of a DataFrame by excluding missing values which makes it ideal for data analysis purpose. The other hand NumPy <em>‘np.mean()’ </em>function calculates the mean by including the null values.</p><p>To conclude, when dealing with large datasets, it is generally more efficient and less resource-intensive to use pandas’ <em>‘.mean() ’ </em>method for mean calculations.</p><p>Thank you for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48987277da76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>