<?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 Onyeka ojumah on Medium]]></title>
        <description><![CDATA[Stories by Onyeka ojumah on Medium]]></description>
        <link>https://medium.com/@faith.ojumah?source=rss-ea562bca9461------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ANCb9OubJo5iRdcvbxCUpA.jpeg</url>
            <title>Stories by Onyeka ojumah on Medium</title>
            <link>https://medium.com/@faith.ojumah?source=rss-ea562bca9461------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:11:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@faith.ojumah/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[Solving the Cold Start Problem in E-Commerce Search with LLMs]]></title>
            <link>https://pub.towardsai.net/solving-the-cold-start-problem-in-e-commerce-search-with-llms-f2c0f54f7e96?source=rss-ea562bca9461------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2c0f54f7e96</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[search-engine-optimizati]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[retail]]></category>
            <category><![CDATA[data-scraping]]></category>
            <dc:creator><![CDATA[Onyeka ojumah]]></dc:creator>
            <pubDate>Sat, 20 Sep 2025 14:01:50 GMT</pubDate>
            <atom:updated>2025-09-20T14:01:50.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A search page of Amazon showing the search result of the query high back chairs — Screenshot by Author" src="https://cdn-images-1.medium.com/max/1024/1*TaK68VF5t14w4mGa_EJCpQ.png" /><figcaption>Source: Image by <a href="https://www.amazon.co.uk/">amazon.</a> Screenshot by author.</figcaption></figure><p>Find me on LinkedIn: <a href="https://www.linkedin.com/in/onyekachukwu-ojumah/">Onyekachukwu Ojumah</a></p><p>Launching an e-commerce site without historical search data could minimise the power of search to just keyword matching which does not give grace to the complexity of human communication. The result is frustration when shoppers cannot find products you stock, or products that are not relevant to their search and ultimately higher attrition.</p><p>There is a need a method to generate plausible, diverse, and attribute‑aware search queries from product information, then organise and annotate those queries to train downstream systems and validate search behaviour before real‑world traffic arrives.</p><p>Large language models (LLMs) are powerful as we have seen many use cases, but they are not magicians. The naive approach would be asking ChatGPT to “generate search query examples” which might yield a few dozen decent results, but scaling that to thousands quickly devolves into repetition, vagueness, and off-catalogue noise while costs climb. Trust me, I have been there.</p><p>That does not mean LLMs can not solve the cold-start problem; it means an unconstrained LLM won’t.</p><p>In this article, I describe an AI-driven architecture that successfully produced 8,000+ realistic, catalogue-grounded search queries. The approach integrates internal and external product data , LLM, human feedback and prompt finetuning to generate, categorise and understand search queries at a a scale.</p><p>The architecture can be broken down into four core segments: 1) Data Sourcing and Query Generation, 2) Query Enrichment 3) Structured Data Creation, and 4) Model Training and Evaluation.</p><figure><img alt="The architecture for solving cold-start problem for retail search — Designed by Author" src="https://cdn-images-1.medium.com/max/1024/1*mjaKnweSVws-J15gtAgC6Q.png" /><figcaption>Source: Image by the author.</figcaption></figure><h4><em>Step 1: Data Sourcing and Realistic Query Generation</em></h4><p>The foundation of any good search system is data. This pipeline aggregates information from multiple streams to ensure comprehensive coverage, moving far beyond a company’s internal jargon.</p><ul><li>Internal Product Data: The process begins with structured about to be launched product attributes (Title, Description, Brand, Colour, Size, Finish, Material). This is the ground truth for what exists in the catalogue.</li><li>External Open-Source Data: To capture the language customers use outside the company’s ecosystem, the system scrapes product data relating to the internal product data from the internet. This helps bridge the gap between internal product names and the descriptive, long-tail terms real people use to search.</li></ul><p>For example, this is a product data from amazon: “ROYALJOBO Ergonomic Mesh Executive Office Chair-Adjustable High Back Desk Chair with Lumbar &amp; Neck Support, Flip-Up Arms for Home Office, Gaming, Computer Work (Black)”.</p><p>The core of this stage is the use of a Large Language Model (LLM). The LLM is prompted to generate thousands of realistic, variable-length search queries for each product. For example, for the amazon product mentioned above, the LLM might generate:</p><ul><li>“Black office chair”</li><li>“Home office chairs with neck support”</li><li>“adjustable gaming chairs”</li><li>“office chairs”</li></ul><p>Best to generate at most seven search queries of different word length for each product data. These form the first set of search queries in the pool.</p><p>Synthetic data generation is the key to overcoming the cold-start problem for new products that have no historical search data.</p><h4>Step 2: Enrichment, and Quality Control</h4><p>Raw generated data is often noisy. This stage ensures quality, linguistic variety, and, most importantly, structures the search queries for two critical downstream tasks: Search Classification and Entity Recognition.</p><ul><li>Quality Filtering with LLM: Another LLM-based filter is employed to remove vague or unrealistic queries (e.g., “that thing for kitchen that is cold” can be filtered out or flagged for review). This ensures only high-quality, plausible search terms are used for training.</li><li>Paraphrasing &amp; Re-ordering: This creates variants like “Black office chair” vs. “Office chair black” which is added to the pool of search queries.</li><li>Pluralisation: Systematically generating plural and singular forms of queries (e.g., “Office chairs black” and “ Black Office chairs”) ensures the search engine can match products regardless of the grammatical number used in the query or the product catalogue. This dramatically improves recall. This is also added to the pool.</li><li>Building a Knowledge Base: Synonyms for all products and specific attributes (like colour) are compiled. This creates a rich vocabulary that understands that a customer searching for a “burgundy” sofa might also look for a “maroon” or “oxblood” one.</li></ul><h4>Step 3: Structured Data Creation</h4><p>The enriched queries are prepared for machine learning in two parallel streams. Crucially, this process is not a one-off but an iterative, human-guided feedback loop designed for rapid improvement.</p><ul><li>For the Search Classification API: Taxonomy Mapping: Business categories (e.g., “Furniture --&gt; chairs”) are converted into a flattened, machine-readable search category hierarchy (e.g.,|furniture|chairs).</li><li>Iterative LLM-Assisted Labelling: An LLM is used in a batch process to map each generated search query to the most relevant search category. This process is refined over multiple batches with human feedback:</li><li>Batch 1: The initial LLM output is reviewed by humans. For instance, the query “blue sofa with metal legs” might be correctly labelled with the category |furniture|livingroom|. However, the model might misclassify a &quot;Persian rug&quot; under |home|decor| instead of the more accurate |home|furniture|rugs|. These mistakes are identified and cleaned.</li><li>Prompt Adjustment: The prompts for the LLM are systematically adjusted based on these mistakes. The revised prompt would now include positive examples (e.g., “Query: blue sofa → Category: |furniture|livingroom|”) and negative examples with corrections (e.g., “Query: Persian rug → Incorrect Category: |home|decor| → Correct Category: |home|furniture|rugs|”).</li><li>Batch 2 &amp; 3: The refined LLM, now with clearer guidelines and examples, processes new data. Its output is significantly improved but may still be reviewed for subtle edge cases, leading to further prompt tuning.</li><li>Batch 4+: After several iterations, the LLM’s categorization becomes highly accurate. It can now reliably assign the category |furniture|livingroom| to various related queries like &quot;comfortable couch,&quot; &quot;three-seater sofa,&quot; or &quot;leather loveseat,&quot; requiring minimal human review. This creates the final, high-quality labelled training dataset (search_query, search_category).</li><li>For the Search Entity Recognition API: An LLM acts as an “Automated Annotator” to perform detailed entity extraction on each query. For the query “blue sofa with metal legs,” the goal is to generate structured JSON:{ “colour”: “blue”, “product_type”: “sofa”, “component”: “legs”, “material”: “metal” }. Humans review the generated JSON, correcting inconsistent labels (e.g., “color&quot; vs &quot;colour&quot; ) or missed entities. The entity extraction prompts are updated with these corrected examples and stricter formatting rules. After several batches, the LLM produces consistently accurate and well-structured entity JSON, creating a reliable training dataset of (search_query, entity_json) pairs.</li></ul><h4>Step 4: Model Training and Evaluation</h4><p>The refined pool of search queries from step 3 is now used to power live production systems.</p><ul><li>Search Classification model: A machine learning model (e.g., a fine-tuned transformer) is trained on the high-quality (search_query, search_category) data. Its job is to take a live user query and instantly predict the most relevant product category hierarchy, routing the search to the correct department.</li><li>Search Entity Recognition model: A separate model is trained on the (search_query, entity_json) data. This model operates alongside the classifier, parsing the user&#39;s query to extract precise attributes, enabling powerful faceted search and results ranking based on colour, size, brand, etc.</li></ul><p>The realism of the search queries or quality of data can be evaluated via downstream performance. With the constrained, taxonomy-anchored generation, the classification model attained 96% macro-precision, 95% macro-recall, and 97% accuracy; the entity model achieved 93% on these metrics. Under a naïve baseline free-form ChatGPT query generation at scale both models scored below 50% across precision, recall, and accuracy, reflecting degraded signal from repetitive and off-catalogue queries.</p><h4>Conclusion</h4><p>To conclude, the critical role of search in e-commerce is undeniable, directly impacting user satisfaction and a company’s bottom line. Tackling the challenge of launching search for new products demands a multi-faceted solution. The most effective strategy integrates a company’s own product data with insights scraped from the web, uses LLMs to generate and refine potential search queries, and relies on human experts to validate and guide the process. This collaborative, AI-augmented approach is the most reliable way to build accurate and powerful search models that deliver a tangible competitive advantage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2c0f54f7e96" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/solving-the-cold-start-problem-in-e-commerce-search-with-llms-f2c0f54f7e96">Solving the Cold Start Problem in E-Commerce Search with LLMs</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling 88% Missing Data for Supervised Learning: Strategies and Techniques]]></title>
            <link>https://medium.com/@faith.ojumah/data-transformation-with-88-missing-data-supervised-learning-12c15bf7bae?source=rss-ea562bca9461------2</link>
            <guid isPermaLink="false">https://medium.com/p/12c15bf7bae</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Onyeka ojumah]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 10:15:32 GMT</pubDate>
            <atom:updated>2023-06-27T10:19:10.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrH4DR-UAgx3b0cmy4AYEg.jpeg" /><figcaption>Missing Values</figcaption></figure><p>As a data scientist, one of the crucial tasks is handling missing data, as it can significantly impact the accuracy and reliability of your data models. In this interactive write-up, we will explore how to handle missing data using the <a href="https://www.kaggle.com/datasets/einsteindata4u/covid19">Covid-19 dataset</a>. Our objective will be to predict severity of <a href="https://www.kaggle.com/datasets/einsteindata4u/covid19">confirmed Covid-19 cases</a>.</p><p>To begin, let’s start by understanding the dataset and the target variable. The target variable represents the admission status of patients and is a combination of three columns: “Patient admitted to intensive care unit,” “Patient admitted to semi-intensive unit,” and “Patient admitted to regular ward.”</p><p>We will be removing the “SARS-Cov-2 exam result” and “Patient ID” columns. Can you think why we are removing them? Take a moment to reflect on the <a href="https://www.kaggle.com/datasets/einsteindata4u/covid19">Kaggle dataset</a> and provide your answer.</p><p>Now, assuming you have downloaded the dataset, create a new notebook and upload it to Google Colab. Google Colab is an excellent platform for coding in Python, with fast loading times and a user-friendly interface.</p><p>Once you have set up your environment, we can start handling the missing data. The steps we will follow are as follows:</p><ol><li>Remove data we do not need: For instance, since we are only interested in positive Covid-19 cases, we can remove rows with negative test results.</li><li>Remove columns with all null values or null values greater than 92%: If a column has a high percentage of missing values, it may not provide meaningful information, and we can safely remove it.</li><li>Remove highly correlated columns: Highly correlated columns may contain redundant information, so we can remove one of them to avoid multicollinearity issues.</li><li>Fill remaining missing values: For categorical data, we will fill the NaN values with the label “missing,” indicating the absence of information. For numerical data, we will use the mean value to fill in the missing values.</li><li>After handling missing data in the <a href="https://www.kaggle.com/datasets/einsteindata4u/covid19">Covid-19 dataset</a>, the next step is to determine the important variables. This is done by utilising modeling techniques to identify feature importance. By training a model and analysing the significance of each feature in relation to the target variable, we can understand which variables have the most influence in predicting the desired outcome. This analysis helps prioritise the most significant variables for further investigation or decision-making.</li></ol><p>Before diving into the coding part, it’s essential to have a foundational knowledge of pandas, as we will be using it extensively. If you’re new to pandas, I recommend checking out a <a href="https://medium.com/@DataSpace.NG/your-first-end-to-end-machine-learning-project-beginner-friendly-c9378b93b0c">beginner-friendly course </a>to get up to speed.</p><p>With our plan in place, let’s get started by downloading the excel file and creating a new notebook in Google Colab. Once we’ve uploaded the dataset, we can proceed with handling missing data and determining the important variables using pandas and other modeling techniques.</p><p>First, we import the necessary libraries.</p><ol><li>Scikit-learn (sklearn) is a popular machine learning library, and the SimpleImputer class is used for handling missing values by filling them with appropriate values.</li><li>RandomForestClassifier is a machine learning algorithm that belongs to the ensemble methods family. It uses an ensemble of decision trees to classify or predict outcomes.</li><li>The numpy library provides support for large, multi-dimensional arrays and mathematical functions. It is widely used for numerical computations in Python.</li><li>Matplotlib is a popular data visualisation library that allows you to create various types of plots and charts.</li><li>The pandas library provides data manipulation and analysis tools in Python. It is commonly used for handling and exploring structured data.</li><li>Seaborn offers a higher-level interface for creating attractive and informative statistical graphics.</li></ol><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import seaborn as sns<br>from sklearn.impute import SimpleImputer<br>from sklearn.ensemble import RandomForestClassifier </pre><p>Next is to define what missing values are and read the dataset using pandas.</p><pre>missing_values = [&quot;n.a.&quot;, &quot;?&quot;, &quot;NA&quot;, &quot;n/a&quot;, &quot;na&quot;, &quot;--&quot;] #define missing values<br>data = pd.read_excel(&quot;/dataset.xlsx&quot;, na_values=missing_values)</pre><p>I always like to remove duplicates.</p><pre>data = data.drop_duplicates()<br>data.head()</pre><p>Next, we calculate the percentage of missing values in the entire dataset.</p><pre>total_cells = data.size  # Total number of cells in the DataFrame<br>total_missing = data.isnull().sum().sum()  # Total number of missing values in the DataFrame<br>percentage_missing = (total_missing / total_cells) * 100  # Calculate the percentage<br>percentage_missing</pre><p>The calculated percentage of missing values in the dataset is 88.06%. This indicates that a significant portion of the data is missing, which can be discouraging. However, don’t worry, as I’m here to assist you through the process.</p><p>To begin addressing this issue, the first step is to focus only on the positive cases since the data aims to predict the severity of Covid-19 cases. By narrowing down the dataset to positive cases, we can slightly reduce the percentage of missing values to 87%. This step allows us to work with a subset of data that is more relevant to our analysis and prediction task.</p><pre>new_data = data[data[&#39;SARS-Cov-2 exam result&#39;] == &#39;positive&#39;]<br>new_data.reset_index(drop=True)</pre><p>Next, I will remove columns that contain a high percentage of missing values, specifically those with all null values or missing values above 92%. These columns will be eliminated as they do not contribute to predicting the dependent variable.</p><pre># Create boolean DataFrame where True indicates a null value<br>null_df = new_data.isnull()<br><br># Find columns where all values are null<br>all_null_cols = null_df.columns[null_df.all()]<br><br>new_data = new_data.drop(columns=all_null_cols)</pre><pre>#code to calculate the percentage of missing values in each column<br>nan_df = pd.DataFrame(new_data.isna().sum()).reset_index()<br>nan_df.columns  = [&#39;Column&#39;, &#39;NaN_Count&#39;]<br>nan_df[&#39;NaN_Count&#39;] = nan_df[&#39;NaN_Count&#39;].astype(&#39;int&#39;)<br>nan_df[&#39;NaN_%&#39;] = round(nan_df[&#39;NaN_Count&#39;] / len(new_data) * 100, 1)<br><br>#code to identify columns with missing values greater than 92%<br>columns_with_92_percent_missing = list(nan_df[nan_df[&#39;NaN_%&#39;] &gt; 92][&#39;Column&#39;])<br>columns_with_92_percent_missing</pre><pre>#code to remove columns with missing values greater than 92%<br>new_data = new_data.drop(columns_with_92_percent_missing, axis=1)<br>new_data.reset_index(drop=True)</pre><p>Next, we remove the “SARS-Cov-2 exam result” and “Patient ID” columns from the dataset. Remember to tell me why I am doing this in the comment section.</p><pre>#removing patient id and SARS-Cov-2 exam result<br>remove_col = [&#39;Patient ID&#39;,&#39;SARS-Cov-2 exam result&#39;]<br>new_data = new_data.drop(remove_col,axis = 1)</pre><p>To identify highly correlated columns, we need to exclude the target variable. In this case, the target variable is spread across three columns: “Patient admitted to intensive care unit” (1=yes, 0=no), “Patient admitted to semi-intensive unit” (1=yes, 0=no), and “Patient admitted to regular ward” (1=yes, 0=no). To address this, we can combine these three columns into a single target variable column.</p><p>To accomplish this, we can write a function that iterates through the three columns and creates a new column representing the target variable. Here’s how this function could be implemented:</p><pre>def multiclass_target(row):<br>    check = 0<br><br>    check += 3 if (row[&#39;Patient addmited to intensive care unit (1=yes, 0=no)&#39;] == 1) else 0<br>    check += 2 if (row[&#39;Patient addmited to semi-intensive unit (1=yes, 0=no)&#39;] == 1) else 0<br>    check += 1 if (row[&#39;Patient addmited to regular ward (1=yes, 0=no)&#39;] == 1) else 0<br>    row[&#39;target&#39;] = check<br>    return row<br><br>new_data = new_data.apply(multiclass_target, axis=1)<br>new_data</pre><p>Now that we have created a new column called ‘target’, we can proceed to drop the three columns used in the combination process. This will allow us to separate the target variable from the independent variables.</p><p>After separating the target variable, we can use a correlation matrix to identify columns that are highly correlated with each other. This will help us identify redundant or highly interdependent variables that may not add significant value to our analysis.</p><p>I wrote a for loop to remove one of the highly interdependent variables but there are more efficient way if you understand Data algorithms. Feel free to suggest better ways.</p><pre>X = new_data.drop(columns=[&#39;Patient addmited to regular ward (1=yes, 0=no)&#39;, <br>&#39;Patient addmited to semi-intensive unit (1=yes, 0=no)&#39;, <br>&#39;Patient addmited to intensive care unit (1=yes, 0=no)&#39;,&#39;target&#39;])<br><br>y=new_data[&#39;target&#39;]<br><br>import seaborn as sns<br># create a correlation matrix<br>corr_matrix = X.corr()<br><br># create a heatmap using seaborn<br>sns.heatmap(corr_matrix, annot=True, cmap=&#39;coolwarm&#39;)<br><br># show the plot<br>plt.show()</pre><pre># Find highly correlated columns<br>high_corr = np.where(np.abs(corr_matrix) &gt; 0.79)<br><br># Loop through the highly correlated pairs and delete one of them<br>for i in range(len(high_corr[0])):<br>    col1 = high_corr[0][i]<br>    col2 = high_corr[1][i]<br>    if col1 &lt; X.shape[1] and col2 &lt; X.shape[1]:<br>        if col1 != col2:<br>            if X.columns[col1] &lt; X.columns[col2]:<br>                X.drop(X.columns[col1], axis=1, inplace=True)<br>            else:<br>                X.drop(X.columns[col2], axis=1, inplace=True)</pre><p>Now that we have removed columns that are highly correlated, the next step is to handle missing values in the categorical columns. We can accomplish this by filling all the missing values in these columns with the value ‘missing’ using the SimpleImputer from scikit-learn.</p><p>SimpleImputer is a class from the scikit-learn library that provides strategies for imputing missing values in a dataset. In this case, we will use the ‘missing’ strategy to fill the missing values in the categorical columns.</p><pre>cat_cols_train = list(X.select_dtypes(include=[&#39;object&#39;]).columns)<br>cat_cols_train</pre><pre>imputer = SimpleImputer(strategy=&#39;constant&#39;, fill_value=&#39;missing&#39;)<br>cat_cols_train = X.select_dtypes(include=[&#39;object&#39;]).columns.tolist()<br># Impute the missing values in the categorical columns with &#39;missing&#39;<br>X[cat_cols_train] = imputer.fit_transform(X[cat_cols_train])</pre><p>To evaluate if using the mean is the optimal strategy for filling missing values in numerical columns, I ran the following code:</p><pre>X.describe()</pre><p>After analysing the range of values in the dataset, I observed that there are no significant differences between the minimum and maximum values. In such cases, filling the missing numeric values with the mean is a suitable approach. However, if there were substantial variations or outliers present in the data, using the median would be a more appropriate option. It is crucial to consider the distribution and characteristics of the data when deciding which imputation strategy, such as mean or median, to employ.</p><pre># compute the median value of each column<br>mean_values = X.mean()<br><br># fill missing values with median value of each column<br>X.fillna(mean_values, inplace=True)</pre><p>Now, to address the issue of imbalanced data, we can utilise the SMOTE (Synthetic Minority Over-sampling Technique) algorithm. Balancing the data is essential to ensure that each class or category in the dataset has a similar representation.</p><p>SMOTE is a popular oversampling technique used to balance imbalanced datasets. It generates synthetic samples for the minority class by interpolating between existing instances. This helps to increase the representation of the minority class and create a more balanced dataset for training our model.</p><p>This is not an important step in addressing missing values but it is nice to have.</p><pre>from imblearn.over_sampling import SMOTE<br><br>smote = SMOTE(random_state=42)<br>X_resampled, y_resampled = smote.fit_resample(X, y)</pre><p>To determine feature importance using a machine learning model, we split the data into training and test sets. I already explain why in step 5 above.</p><pre># Split the data into training and testing sets<br><br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X_resampled,y_resampled, test_size=0.3, random_state=42)</pre><p>To identify the important features contributing to predicting the target variable, we will utilise the RandomForestClassifier along with Recursive Feature Elimination with Cross-Validation (RFECV).</p><p>The RandomForestClassifier is an ensemble machine learning algorithm that constructs multiple decision trees and combines their predictions to make accurate predictions. It is well-suited for feature importance estimation due to its ability to assess the impact of different features on the model’s performance.</p><p>RFECV is a technique that recursively eliminates less important features and selects the optimal subset of features through cross-validation. It assesses the performance of the model with different subsets of features and identifies the most relevant ones based on their contribution to the model’s accuracy.</p><p>By combining the RandomForestClassifier with RFECV, we can iteratively evaluate the importance of each feature and select the subset that maximises the model’s performance. This approach helps us identify the most significant features for predicting the target variable and can provide insights into the underlying relationships within the dataset.</p><pre># perform feature selection using RFECV<br>from sklearn.feature_selection import RFECV<br>from sklearn.ensemble import RandomForestClassifier<br><br><br># Create an instance of RandomForestClassifier<br>rfc = RandomForestClassifier(n_estimators=100, random_state=42)<br><br># Fit the RandomForestClassifier instance to the training data<br>rfc.fit(X_train, y_train)<br><br># Create an instance of RFECV and fit it to the training data<br>selector = RFECV(rfc, step=1, cv=10)<br>selector = selector.fit(X_train, y_train)<br><br><br><br>plt.figure()<br>plt.xlabel(&quot;Number of features selected&quot;)<br>plt.ylabel(&quot;Cross validation score (nb of correct classifications)&quot;)<br>plt.plot(range(1, len(selector.cv_results_[&#39;mean_test_score&#39;]) + 1), selector.cv_results_[&#39;mean_test_score&#39;])<br>plt.show()</pre><pre># get the index of the maximum score<br>idx = np.argmax(selector.cv_results_[&#39;mean_test_score&#39;])<br><br># get the number of selected features<br>num_features = idx + 1<br><br>print(f&quot;Number of selected features: {num_features}&quot;)</pre><p>After applying the RFECV technique, we observe that out of the initial 110+ columns we started with, only 21 columns are deemed relevant for predicting the target variables.By eliminating unnecessary columns, we also remove any associated missing values that may be present.</p><p>The resulting dataset, represented by the new feature matrix X, will now consist of the selected features that are considered important for predicting the target variable. This reduction in the number of features not only simplifies the dataset but also helps to focus the model’s attention on the most influential variables.</p><pre>X_train_select = X_train[selected_features]<br>X_train_select.reset_index(drop=True)</pre><p>To view their level of importance, we write a new code:</p><pre># Use the feature_mask to select the important features<br>importances = rfc.feature_importances_[feature_mask]<br><br><br><br># Sort the features by importance<br>sorted_idx = importances.argsort()[::-1]<br>features_sorted = selected_features[sorted_idx]<br>importances_sorted = importances[sorted_idx]<br><br># Plot the feature importances<br>plt.figure(figsize=(10, 6))<br>plt.title(&quot;Feature Importances&quot;)<br>plt.barh(range(len(importances_sorted)), importances_sorted, align=&#39;center&#39;)<br>plt.yticks(range(len(importances_sorted)), features_sorted)<br>plt.tight_layout()<br>plt.show()</pre><p>Now let us check the percentage of missing values, of course it will be zero.</p><pre>total_cells = X_train_select.size  # Total number of cells in the DataFrame<br>total_missing = X_train_select.isnull().sum().sum()  # Total number of missing values in the DataFrame<br>percentage_missing = (total_missing / total_cells) * 100  # Calculate the percentage<br>percentage_missing</pre><p>The reduction in the number of features through the step 1,2, and 3 assist in handling missing values. When we remove unnecessary columns that are deemed irrelevant for predicting the target variable, we also eliminate any associated missing values in those columns.</p><p>By reducing the dimensionality of the dataset and focusing on the most relevant features, we effectively reduce the complexity of the data. This can simplify the process of handling missing values because we only need to consider and address missing values in the selected subset of features.</p><p>Moreover, working with a reduced set of features allows for more targeted and efficient missing value imputation strategies. With fewer features to consider, we can allocate resources and attention specifically to those variables, making the imputation process more manageable and accurate.</p><p>I do hope you have learnt something new.</p><p>Link to the project on <a href="https://github.com/ojumah20/Data-Transformation-with-88-missing-data--Supervised-Learning">github</a></p><p>Say Hi to me on <a href="https://www.linkedin.com/in/onyekachukwu-ojumah/">linkedIn</a></p><p>Don’t forget to gist with me on <a href="https://twitter.com/Onyeka_Ojumah">twitter</a></p><p>Most importantly practice and post your result, do not just read.</p><p>Cheers!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12c15bf7bae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an ETL Pipeline with Python and PostgreSQL for Data Loading]]></title>
            <link>https://medium.com/@faith.ojumah/building-an-etl-pipeline-with-python-and-postgresql-for-data-loading-3750be1cfcdf?source=rss-ea562bca9461------2</link>
            <guid isPermaLink="false">https://medium.com/p/3750be1cfcdf</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Onyeka ojumah]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 09:24:03 GMT</pubDate>
            <atom:updated>2023-06-23T09:24:03.724Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the jobs of a data engineer is to move data from a source to a data destination (creating and maintenance data pipeline).</p><p>Here is a simple ETL pipeline moving a CSV file to postgreSQL using python although no transformation process was covered but the overall concept was discussed. This is a great starting point to the field of data engineering.</p><p>Abit of familiarity working with VSCode such virtual environment creation and module installation will be helpful.</p><p>Let’s go!!!</p><p>Click the link <a href="https://www.enterprisedb.com/downloads/postgres-postgresql-downloads">https://www.postgresql.org/download/</a>. and select the version to download based on your operating system. I usually go for the lastest version for MacOS, but feel free to go for the one before the lastest version.</p><p>You should get a package like “postgresql-15.3–2-osx.dmg” to be downloaded. Double click on the package after downloading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djxzl8s-FMWRPMcCn0uFPQ.jpeg" /></figure><p>Follow the next buttons until you get to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vx0hOKg3uCnEiGzvOnWfMQ.jpeg" /></figure><p>Set up your password and make sure you do not forget it. it will be very useful.</p><p>Follow the next prompts <strong>Port 5432</strong> until you get to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1dfr_YthjfiUeUvpELoV-Q.jpeg" /></figure><p>To view your new installation, go your computer apps and select the graphical administration tool called pgAdmin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0m_M_ZUIjlfTjG7cPC9m3Q.jpeg" /></figure><p>You should see something like above prompting you to enter the code you set up during installation.</p><p>Next you should see something like the image below. I have two postgreSQL installed (13 and 15) but one is enough so don’t worry if your servers are not two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URVJrMTYlRL91EwxAFV0ag.jpeg" /></figure><p>How let’s send some data to our database. Usually postgreSQL gives you a default database called postgres and default user called postgres.</p><p>We will do something very simple using only pandas and would not transform, just extract and load.</p><p>First create an empty folder on your desktop, move the csv file (<a href="https://github.com/ojumah20/Lecture/blob/master/diabetes.csv">diabetes.csv</a>) in the folder and open the folder on Vscode. Create a file and call it anything you like .ipynb. The file extension .ipynb creates a notebook but you can create a general python file using the extension .py.</p><p>Next we will use Pandas and SQLAlchemy. Pandas is a library that allows you to load, clean, filter, transform, and analyse data efficiently. SQLAlchemy allows you to interact with various database management systems.</p><p>Please read more about these libraries as they will be very important in your data journey.</p><pre>import pandas as pd #import the pandas library<br>data = pd.read_csv(&quot;diabetes.csv&quot;) #read the csv file<br>data.head(10) #view rthe first 10 rows</pre><pre>from sqlalchemy import create_engine #import the library to connect to postgresql<br>#type of database, username, password, host, port, database name                      <br>engine = create_engine(&#39;postgresql://[username]:[password]@localhost:[5432]/[database name]&#39;)<br><br>data.to_sql([&#39;table name&#39;], engine,if_exists= &#39;replace&#39;) #send the data to postgres</pre><p>Now go back to pgAdmin to view the table and data. Remember to replace all elements in the [ ] with your own details eg. username, password and databasename. The table name can be any name of your choice and remeber to put it in quotation mark. Remove all [ ] once you are done.</p><p>If you get an error message saying module not found then use the pip install method to install the module.</p><p>Here is the link to the project on<a href="https://github.com/ojumah20/Lecture"> github</a>.</p><p>I really do hope you have learnt something new. Try it and let me know.</p><p>If you have any issue, drop it in the comment section and I will respond. Cheers!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3750be1cfcdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ChatGPT in Finance]]></title>
            <link>https://medium.com/@faith.ojumah/chatgpt-in-finance-491e4b734096?source=rss-ea562bca9461------2</link>
            <guid isPermaLink="false">https://medium.com/p/491e4b734096</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Onyeka ojumah]]></dc:creator>
            <pubDate>Sun, 05 Feb 2023 20:40:23 GMT</pubDate>
            <atom:updated>2023-02-05T20:40:23.829Z</atom:updated>
            <content:encoded><![CDATA[<p>ChatGPT is here but what does this mean to the Financial Industry? The best way to understand its impact is to ask ChatGPT itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GREuPqD9RpxrJKsuNNmkCg.png" /><figcaption>ChatGPT by OpenAI</figcaption></figure><h3><strong>What is chatGPT?</strong></h3><p>ChatGPT is an advanced language model developed by OpenAI, designed to provide human-like responses to any question on a wide range of subjects. Unlike traditional chatbots, ChatGPT can remember previous conversations, making it feel more like talking to a person than a machine. This feature gives ChatGPT an edge over other chatbots, making it a powerful tool for a variety of applications.</p><p><strong>But how do we techies in finance use this very intelligent Machine to improve our work.</strong></p><p>I conducted research and was unable to find individuals who have utilized ChatGPT in the financial sector. As<strong> an advanced language model </strong>developed by OpenAI, I thought it would be worth inquiring directly with ChatGPT, given its ability to provide informed responses.</p><p><strong>“What can you be used for in the financial space?”Here is an overview of its response.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oc8KrpVWMyrrOyim2rbQ8Q.jpeg" /><figcaption>ChatGPT Response</figcaption></figure><p><strong>1. Analysing financial reports:</strong> ChatGPT can be used to analyze financial reports by providing it with access to relevant data and information. The AI model can then generate summaries of key points and trends, identify discrepancies or anomalies in the data, and provide recommendations based on its understanding of the information and its context. For example, ChatGPT can be utilized to analyze a bank’s financial statements, such as its balance sheet, income statement, and statement of cash flow, to identify trends and patterns and offer suggestions for improving financial performance. It can also be used to compare the bank’s financial performance to <strong>competitors</strong> or industry benchmarks and provide insights for improvement.</p><p>It’s important to note that the use of ChatGPT does not replace the need for <strong>human financial analysts,</strong> but rather enhances their ability to detect potential fraud and make informed decisions quickly through collaboration.</p><p><em>Imagine how beautiful it is to get one-week job done in three minutes.</em></p><p><strong>2. Personalised investment recommendations: </strong>Integrating ChatGPT into your bank’s chatbot can provide personalised investment recommendations tailored to each customer’s unique financial situation, risk tolerance, and investment goals. The ChatGPT model uses data such as individual financial income, expenses, liabilities, assets, risk tolerance, and investment goals to generate recommendations.</p><p>For instance, if a customer wants to increase returns while minimising risk, the ChatGPT-powered chatbot could recommend a diversified portfolio of lower-risk investments such as bonds. For customers who are willing to take on higher risk, the chatbot could suggest investments in stocks. By using this information and the advanced capabilities of ChatGPT, your bank’s chatbot can offer customised and informed investment recommendations to its customers.</p><p><strong>3. Personalised marketing</strong>: ChatGPT can be utilised to deliver personalised marketing messages to customers, tailored to their spending habits and other relevant personal information. This allows for a more targeted and relevant approach to marketing, improving the chances of success and customer engagement. By leveraging the advanced capabilities of ChatGPT, organisations can create highly personalised marketing campaigns that resonate with their audience, ultimately leading to better customer experiences and stronger business outcomes.</p><h3><strong>Where is the risk?</strong></h3><p>The use of ChatGPT carries the risk of generating inappropriate or misleading text. To address this, it’s important to implement measures to filter or censor potentially harmful or false information. This could include using keyword filters to flag text for human review or implementing algorithms to detect and remove offensive content. By taking proactive steps to mitigate these risks, organisations can ensure that their use of ChatGPT aligns with ethical and legal standards and maintains the trust and confidence of their users.</p><h3>So how do we integrate this intelligent partner into our applications?</h3><p>ChatGPT currently lacks official API documentation as the technology is still in the research phase. However, individuals like 1littleCoder have provided insights into what using ChatGPT might be like, which is truly remarkable. It is recommended to explore their lectures and learn more about the exciting potential of ChatGPT.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FS3okwVkxDgA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS3okwVkxDgA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FS3okwVkxDgA%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/f54735fc4ce2a3cb55314b950ae054c0/href">https://medium.com/media/f54735fc4ce2a3cb55314b950ae054c0/href</a></iframe><h3><strong>Conclusion</strong></h3><p>With ChatGPT, it is time to dispel the myth that AI will replace human labor, and instead embrace the idea that humans will collaborate with AI to enhance quality of life. Let’s join forces as tech enthusiasts and turn this vision into a reality. Let’s build the future together.</p><p>Check it out…<a href="https://chat.openai.com/">https://chat.openai.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=491e4b734096" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your First End to End Machine learning Project — Beginner-friendly]]></title>
            <link>https://medium.com/@faith.ojumah/your-first-end-to-end-machine-learning-project-beginner-friendly-c9378b93b0c?source=rss-ea562bca9461------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9378b93b0c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Onyeka ojumah]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 11:29:14 GMT</pubDate>
            <atom:updated>2021-10-15T11:29:14.921Z</atom:updated>
            <content:encoded><![CDATA[<h3>Your First End to End Machine learning Project — Beginner Friendly</h3><p>Venturing into data science with all the numerous articles available can be confusing. Here I have used a simple predictive model to explain the basic concepts needed to get you started.</p><p>Are you ready?</p><h3>What is Machine learning?</h3><p>I was asked this question in my first interview and stuttered; not because I did not understand the concept rather, I did not know how to give a definition. So here is it to help you.</p><p>Machine learning is a field under data science that focuses on the use of data and algorithm to imitate the way humans learn to improve performance and make predictions. Clear, right?</p><h3>So what then is data science?</h3><p>Data science is a field that encompasses all scientific processes used in extracting meaning and insights from data. It involves information technology, business management, and modeling. By this definition, we can see that machine learning is a subset of data science.</p><h3>What are the types of machine learning Methods?</h3><p>There are three main types of machine learning methods.</p><p><strong>Supervised Learning:</strong> This involves labeled datasets to train the algorithm to predict or classify data accurately. It means the dataset used in supervised learning must have input(s) labeled X and an output (labeled Y).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RQ8J3Lte1N-hcTYWkGsSw.jpeg" /><figcaption>Diabetes.CSV</figcaption></figure><p>In the above dataset, the inputs are columns [pregnancies, glucose, blood pressure, skin thickness, insulin, BMI, DiabetesPredigreeFunction, Age], while the output is the column [outcome]. It is a perfect dataset for supervised learning. <br>Some models used in supervised learning include naïve Bayes, linear regression, logistic regression, random forest, support vector machine (SVM), and more.</p><p><strong>Unsupervised Learning: </strong>This uses machine learning algorithms to analyze and cluster unlabeled datasets. Therefore there is no output rather data points are grouped based on similarity.</p><p>The most used model used is K-Mean; others are neural networks and probabilistic clustering methods.</p><p><strong>Reinforcement Learning: </strong>This learning is a behavioral machine learning model similar to supervised learning, but the algorithm is not trained using sample data.</p><p>It uses reward or punishment to train the model. We would not be going into details. You can read up this part on <a href="https://www.ibm.com/cloud/learn/machine-learning.">https://www.ibm.com/cloud/learn/machine-learning.</a></p><p>We will discuss other terms as we move ahead. Now let’s build our first supervised machine learning model.</p><p>I will be using a jupyter notebook in Anaconda. There are other environments such as pycharm; I am more comfortable with jupyter notebook. Since the data volume is not large, there will be no need to use databrick (a cloud platform). Use the link <a href="https://docs.anaconda.com/anaconda/install/windows/">https://docs.anaconda.com/anaconda/install/windows/</a> to install for windows or <a href="https://docs.anaconda.com/anaconda/install/mac-os/">https://docs.anaconda.com/anaconda/install/mac-os/</a> for IOS.</p><p>Here is a great tutorial to help you <a href="https://www.youtube.com/watch?v=5mDYijMfSzs">https://www.youtube.com/watch?v=5mDYijMfSzs</a></p><h3>Loading The Data</h3><p>Once you install, launch the environment and select jupyter notebook. You should see something like the screenshot below. The notebook consists of cells that are run independently. To create a new cell, click the + sign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RG78LvEv3_ixRL4XPCpA1A.jpeg" /></figure><p>We will begin by importing libraries. Copy the below code in a cell and run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImHRmayUGMuVOER8FKev0A.jpeg" /></figure><p>Libraries are pre-written blocks of codes that can be re-used anytime to help simplify the programming process. Some common libraries in python for machine learning are :</p><ol><li>Pandas: For loading and transforming all kinds of structured data.</li><li>Scikit-learn: For building machine learning models. It has tons of tools used for predictive modeling and analysis. It can also be used to cross-validate the accuracy of models and conduct feature importance. For this project, we imported logisticRegression and accuracy_score, and f1_score to check for the accuracy of our model on the data.</li><li>Plotly, Seaborn &amp; matplotlib: For building visuals during exploratory analysis (understanding what is happening in our data).</li><li>Stasmodels: For building statistical models.</li><li>Keras &amp; Tensor flow: For creating deep learning models (advanced machine learning). You will gradually grow into this.</li><li>Pickle: Used for saving the deployment model. We will discuss this in detail later.</li></ol><p>For further read on the libraries in python for data science, you can check out this link <a href="https://www.kdnuggets.com/2021/03/top-10-python-libraries-2021.html">https://www.kdnuggets.com/2021/03/top-10-python-libraries-2021.html</a></p><p>Next, we import our data. I will be using open-source diabetes data from Kaggle (you should check out this platform) and, we want to build a model that will predict the likelihood of a person having diabetes based on some attributes.</p><p>Download the data from <a href="https://www.kaggle.com/pyim59/pyms-diabete">https://www.kaggle.com/pyim59/pyms-diabete</a></p><p>Next, read the data using pandas. First, we create a data frame called diabetes that will store the data. Then we tell pandas to read the CSV file from Onyeka’s laptop, under the desktop, under predictiveproject. The best way to get this information is to look for the properties of the CSV file.<br>diabetes = pd.read_csv(r’C:\Users\Onyeka\Desktop\predictiveproject\diabetes.csv’)<br>Then we call the data frame with the method (head) to print out the first five rows for preview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CE5yaGCITUHYJ7k6Q16a6Q.jpeg" /></figure><h3><strong>Data Preparation</strong></h3><p>First, let’s check the number of rows and columns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96G3Q5FHIqCRX-5THppWXg.jpeg" /></figure><p>The dataset has seven hundred and sixty-eight rows and nine columns. Eight of the columns are our inputs and, the column outcome is the output.</p><p>Next, we replace all empty data in the input columns except pregnancy with 0 then the zero with the median. I prefer median because it prevents data bias especially if <em>the dataset is skewed (not balanced).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6VKnniuo268opVh1LzUwQ.jpeg" /></figure><p>The above code reads the needed columns to a data frame called ‘replace_zero’ then creates a for loop(read on for loop from python).</p><p><em>For each column, replace no data with zero then replace the zero with the median. Can you guess the number of times this for loop will run? Leave your answer in the comment section.</em></p><p>The data are all in numerical values. There will be no need to use one-hot encoding. If we had a column called gender with categorical data (female and male), then one-hot encoding would have converted the male to 1 and female to 0 for easy processing. Read more on this <a href="https://towardsdatascience.com/categorical-encoding-using-label-encoding-and-one-hot-encoder-911ef77fb5bd">https://towardsdatascience.com/categorical-encoding-using-label-encoding-and-one-hot-encoder-911ef77fb5bd</a></p><p>This section involves transforming the data to be suitable for the model.</p><h3>Exploratory analysis (EDA)</h3><p>It involves using visuals to have a better view of your data’s behavior. I will give another detailed tutorial on this. For now, let us check how many people had diabetes as their outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWcjFNgJ37Dm6s2ahXqNtw.jpeg" /></figure><p>From the visual, we can see that fewer people had diabetes in the dataset.</p><h3>Feature Scaling</h3><p>We perform feature scaling when some columns have high numbers compared to others.</p><p>For example, the column [pregancies] has values within 0–10 compared to bloodpressure or Tension with values over 72. If we do not scale, the machine learning model will ignore the column [pregnancies].</p><p>By scaling will bring all the data to an equal range.</p><p>We can either standardized the data or normalize the data.</p><p>Normalizing the data involves scaling the data between 0 and 1 or -1 to 1 using the max and min data.</p><p>Standardization involves using the mean and standard deviation (*smh* this is why learning statistics is necessary. You can get more details here <a href="https://en.wikipedia.org/wiki/Feature_scaling">https://en.wikipedia.org/wiki/Feature_scaling</a>).</p><p>After comparing the accuracy of the normalized and standardized data, I will be using the standardized one.</p><p>First, we split the prepared data into <em>a</em> and <em>b</em>; <em>a</em> will contain the inputs while <em>b</em> will be the output; <em>a</em> <em>train</em> will be used in training the model while ‘a’ test will be used in testing the performance of the model.</p><p>It is at a ratio of 80–20 for train and test.</p><p>The function ‘iloc’ helps us to select specific columns and rows. For data frame <em>a, </em>we have said pick all the rows [ :] then pick column 7 columns [0:8].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXuta7lP5O2xQtx5L3bRag.jpeg" /></figure><p>Then we scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJLVbuRui897cG-eQcCCzw.jpeg" /></figure><p><strong>I have also written the code for normalization but commented it out using the ‘#’ sign. You can play around with it and compare performance.</strong></p><p>Next, we define our model. The code below assigns the logisticRegression to a variable called model and then tells the model to learn on the training dataset. Finally, the model should use a_test to predict b_test and assign the result to b_pred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xh1I1TXilKoJHl13C2qRHw.jpeg" /></figure><p>Next, check the model’s performance by comparing the result of b_pred with the actual b_test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XRA2sDONYiHl0QUGRLRTBA.jpeg" /></figure><p>Our model has an accuracy of 81.1%, not so great but manageable. The f1_score is at 0.65. The closer the f1_score to 1, the better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOgtFPqAzrohMJ-p3mqGwA.jpeg" /></figure><p>Remove all comments plus accuracy testing and save the model for deployment using the code above.</p><p>This is where the fun begins; having your model in production predicting the outcome on the new dataset.</p><p>I used pickle to save the model because the dataset is small. For a large dataset, it is best to use Joblib. It s just a single line of code. <em>joblib.dump(model, open(‘model.pkl’, ‘wb’)).</em> You can read the details here <a href="https://machinelearningmastery.com/save-load-machine-learning-models-python-scikit-learn/">https://machinelearningmastery.com/save-load-machine-learning-models-python-scikit-learn/</a>.</p><p>The model is stored in your system in a document-like format.</p><p>In my next tutorial, I will show you how to build a simple input form using HTML and load the model to the web page using Flask to make predictions.</p><p>In that tutorial, you will enter data for the respective columns using input tags then click on predict to get the outcome. I can not wait to show you.</p><p>Now give yourself a round of applause, super proud of you to have made it this far … cheers!!!!</p><p>Special thanks to <a href="https://medium.com/u/d399d1fbd705">Ekemini Okpongkpong</a> for her assistance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9378b93b0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>