<?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 Daniel Okia on Medium]]></title>
        <description><![CDATA[Stories by Daniel Okia on Medium]]></description>
        <link>https://medium.com/@danielOkia?source=rss-d25706dd7bdf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hmtbjellf3QM4Dd_b2XJ-g.jpeg</url>
            <title>Stories by Daniel Okia on Medium</title>
            <link>https://medium.com/@danielOkia?source=rss-d25706dd7bdf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:31:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielOkia/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[Day 4 — Navigating Unsupervised Learning]]></title>
            <link>https://medium.com/@danielOkia/navigating-unsupervised-learning-3cafd8869ea0?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cafd8869ea0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 06:32:57 GMT</pubDate>
            <atom:updated>2023-08-29T12:05:05.969Z</atom:updated>
            <content:encoded><![CDATA[<p>Unraveling Decision Trees and Random Forests</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPw2rw0XZ_CH9ryMjdr4bw.jpeg" /></figure><p>Welcome to Day 4 of my exciting Machine Learning journey! Today, I immersed myself into the world of unsupervised learning and exploring two dynamic algorithms: Decision Trees and Random Forests. I’ll uncover their definitions, the magic of their applications, and how each operates. I’ll also journey through real-world examples that bring these algorithms to life, showcasing their benefits and highlighting the key differences. And when it comes to Random Forests, I’ll dive into why it’s a game-changer, enhancing accuracy and delivering remarkable results. Let’s expand our understanding of unsupervised learning’s potential!</p><h3>What’s Unsupervised Learning?</h3><p>Unsupervised learning is like unraveling a mystery without any hints — it’s a branch of machine learning where the model dives into unlabeled data to uncover hidden patterns and structures on its own. Just imagine sifting through a box of puzzle pieces without a picture to guide you. In unsupervised learning, the algorithm is the detective, clustering similar data points together or reducing complex dimensions to help us see the bigger picture in uncharted data territory.</p><p><strong>Meet Decision Trees:</strong></p><p>Decision Trees are like virtual detectives. They make decisions by asking yes-or-no questions. Think of them as a flowchart that guides you step by step to a conclusion. In real life, they’re handy for classifying data — like sorting fruits based on color, shape, and size.</p><p><strong>Introducing Random Forests:</strong></p><p>Random Forests bring a crowd of Decision Trees together to vote on the best decision. Imagine you’re making a group decision with friends; you’re likely to get a solid choice. Random Forests use this strength to enhance accuracy. They’re like the “A-team” of machine learning, tackling complex tasks like diagnosing diseases from medical data.</p><p><strong>Benefits and Differences:</strong></p><p>Decision Trees are simple and great for quick answers. Random Forests excel when the going gets tough — they’re less prone to overfitting and deliver robust results. In real-world terms, Decision Trees might predict movie genres based on a single clue, while Random Forests could predict a person’s interests from a mix of clues.</p><p><strong>Real-World Marvels:</strong></p><p>Imagine you’re a botanist with a garden full of flowers. Unsupervised learning can help classify them by color and shape. Decision Trees could determine if a flower is a rose based on its petal count. Now, picture a Random Forest — it’d consult a team of Decision Trees to ensure a reliable identification.</p><p><strong>Why Random Forests Rule:</strong></p><p>Random Forests have a secret sauce: diversity. By combining different Decision Trees, they create a balanced, accurate prediction mechanism. Imagine you’re predicting weather — Decision Trees might guess rain every time clouds appear, but a Random Forest ensures a more precise forecast.</p><h3>Implementation of Decesion Trees and Random Forests:</h3><p>When it comes to implementing Decision Trees and Random Forests, the process shares striking similarities with linear and logistic regression.</p><p><strong>Project: Predicting Kyphosis with Unsupervised Learning</strong></p><p>Let’s embark on a simple yet enlightening project that demonstrates the power of unsupervised learning. Our objective? Predicting the presence of kyphosis, a spinal condition.</p><p>By diving into this project, we’ll uncover how to apply unsupervised learning techniques, like Decision Trees and Random Forests, to make insightful predictions about kyphosis occurrences. This hands-on experience will provide a tangible glimpse into the potential of these algorithms in solving real-world problems.</p><p><em>Download the kyphosis dataset here to follow along:</em></p><p><a href="https://drive.google.com/drive/folders/1FaV91OkTsABJrjnfeeTR4rwLe0mxFHxZ?source=post_page-----7762a6dce185--------------------------------">ML Algorithms dataset - Google Drive</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*ylyzbd8FCZnKVcTfYwK28Q.png" /><figcaption>Importing libraries and loading dataset</figcaption></figure><p>In a Jupyter notebook, the initial steps involve importing essential libraries and loading your dataset. Conducting exploratory data analysis and visualization comes next, allowing you to gain insights into your data’s characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*6zrp7Nl9CstkA5uHBZ7BsQ.png" /><figcaption>Exploratory Data Analysis — bar plot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*32Z2hAdWKPP3dhxe3hw86w.png" /><figcaption>Exploratory Data Analysis — Pair plot visual</figcaption></figure><p>Just like before, you’ll then proceed to extract your independent and dependent variables, the building blocks for your model and further split the data set into training and testing sub sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*uMTgJEzG_gz7z_xNugSQvA.png" /><figcaption>Extracting Independent and Dependent Variables — Splitting data set</figcaption></figure><p>The heart of the operation involves training and predicting, where you’ll employ the scikit-learn library’s appropriate classes — DecisionTreeClassifier for Decision Trees and RandomForestClassifier for Random Forests. Training the models on your training data empowers them to understand patterns and relationships. Now, it&#39;s time to unleash their predictive power on the testing data.</p><p><strong>Decision Trees:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*nxNm_okYRYcavwPy5DCV-Q.png" /><figcaption>Employing Decision Tree Classifier and Prediciting Results</figcaption></figure><p><strong>Random Forests:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*m4EYEbNg8V8HFNVWSar_xQ.png" /><figcaption>Employing Random Forest Classifier and Predicting Results</figcaption></figure><p>And of course, the story wouldn’t be complete without model evaluation. This step involves using metrics like accuracy, precision, and recall to gauge your model’s performance. While the specific metrics might vary, the process of evaluation remains a fundamental cornerstone.</p><p><strong>Decision Tree Model Evaluation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*emN9joBQhEaZY74UVlfhEA.png" /></figure><p><strong>Random Forests Model Evaluation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*RzlhLKCfnShLsCwNchavTw.png" /></figure><p><strong>Model Evaluation Comparison:</strong></p><p>Comparing the results of the two algorithms, the Decision Tree and Random Forests, provides us with valuable insights into their performance. For the Decision Tree model, its precision, recall, and overall accuracy landed at approximately 0.79, 0.64, and 0.64, respectively. On the other hand, the Random Forests model exhibited precision, recall, and accuracy of roughly 0.76, 0.76, and 0.76.</p><p>However, the critical distinction emerges in the real-world impact. The Decision Tree model faced challenges in classifying the “present” category, resulting in low precision, recall, and F1-score values. In contrast, the Random Forests model showcased an accuracy of 0.76, albeit with zero precision and recall for the “present” category.</p><p><strong>Confusion Matrix:</strong></p><p>Finally, looking closely at the results, this echoes our earlier exploration on Day 3, where we delved into the intricacies of the confusion matrix and highlighted its importance in evaluating model effectiveness.</p><p>Comparing the confusion matrix results reveals a substantial disparity in the two models’ performance. The Decision Tree model correctly classified 15 instances as “absent” and struggled with “present,” leading to 7 false labels. In contrast, the Random Forests model excelled, accurately predicting 19 “absent” instances and achieving zero false positives. While the latter encountered challenges with “present,” its ability to curb false positives and enhance overall accuracy showcased the prowess of ensemble methods.</p><p>These outcomes highlight the power of Random Forests in improving accuracy, especially in scenarios where one algorithm might struggle to classify a specific category. This comparison underlines how harnessing the strength of multiple models can ultimately lead to more robust and precise results in the realm of machine learning.</p><h3>Conclusion:</h3><p>The intriguing part is that both Decision Trees and Random Forests can coexist harmoniously within the same notebook and environment. By implementing these methods with different libraries and tailored metrics, you can experience the satisfaction of harnessing their predictive prowess.</p><p>In a nutshell, unsupervised learning, Decision Trees, and Random Forests are tools that transform data chaos into organized insights. And remember, while Decision Trees are reliable for simple tasks, Random Forests are your allies when you need supercharged accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cafd8869ea0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 3: Navigating Logistic Regression]]></title>
            <link>https://medium.com/@danielOkia/day-3-navigating-logistic-regression-7762a6dce185?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7762a6dce185</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 09:30:52 GMT</pubDate>
            <atom:updated>2023-08-24T09:30:52.594Z</atom:updated>
            <content:encoded><![CDATA[<p>Predicting Categorical Outcomes Made Easy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKGP7rgQy8pAu9Kjs_RQwg.jpeg" /></figure><p>Join me on Day 3 of my machine learning journey as we dive into the world of logistic regression. Learn how this algorithm, despite its “regression” label, is a powerhouse for predicting categorical values. We’ll explore real-world applications, delve into the workings of the sigmoid curve, and guide you step by step through implementing logistic regression to predict car purchases based on salary.</p><h3>What is Logistic Regression?</h3><p>At first glance, the term “regression” might mislead you, but Logistic Regression is all about predicting categorical values. Imagine classifying whether an email is spam or not, or determining if a customer will churn — these are the challenges logistic regression tackles with finesse.</p><h3>Real-World Applications:</h3><p>Logistic Regression finds its stride across industries:</p><ul><li><strong>Medical Diagnostics</strong>: Identifying the presence of a disease based on various factors.</li><li><strong>Credit Risk Assessment:</strong> Evaluating the likelihood of a customer defaulting on a loan.</li><li><strong>Marketing</strong>: Predicting whether a customer will make a purchase based on their online behavior.</li></ul><p>The Sigmoid Curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*_ia4aai-NrYI_Rcy-QGTSQ.png" /></figure><p>The core of logistic regression lies in the sigmoid curve, which transforms linear combinations into values between 0 and 1 — representing probabilities. Another crucial aspect is the <strong>threshold </strong>value. If the calculated probability is above the threshold (usually 0.5), we predict the positive class; otherwise, we predict the negative class.</p><p>For instance consider predicting car purchases based on age and salary. If the predicted probability of buying a car is above 0.5, the model predicts a purchase; otherwise, it predicts no purchase.</p><h3>Implementation: Predicting Car Purchases</h3><p>Today, we’re set to harness the power of logistic regression in a straightforward project. Our goal? Predicting purchases by tapping into the variables of age and salary. Let’s dive right into this insightful endeavor!</p><p>Download the <em>SocialNetworkAds.csv</em> dataset here:</p><p><a href="https://drive.google.com/drive/folders/1FaV91OkTsABJrjnfeeTR4rwLe0mxFHxZ">ML Algorithms dataset - Google Drive</a></p><p><strong>Key Steps:</strong></p><p><strong>Import Libraries and Dataset:</strong> Arm yourself with the necessary tools and the dataset that holds the key to predictions.</p><pre>#Importing dataset<br>data = pd.read_csv(&#39;SocialNetworkAds.csv&#39;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*C0_5IcSDQmbEIbzTPZU4BA.png" /><figcaption>Sample of dataset</figcaption></figure><p>Prior to dividing our dataset into training and testing subsets, it’s necessary to separate the independent variables (features) from the dependent variable (target). This separation is crucial because the independent variables serve as inputs to the model, while the dependent variable is what we’re trying to predict.</p><pre>#Extracting independent variables<br>X = data.iloc[:, [2,3]].values<br><br>#Extracting dependent variables<br>y = data.iloc[:, 4].values</pre><p><strong>Data Splitting: </strong>Divide the dataset into training and testing subsets for accurate evaluation as explained in day 2 of our journey in machine learning algorithms</p><pre>#Splitting dataset<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.25, random_state = 0)</pre><p><strong>Feature Scaling:</strong> Standardize the features to ensure equal importance. Feature scaling is important in logistic regression to ensure that all input features have the same scale. Logistic regression estimates the coefficients for each feature to determine their influence on the outcome.</p><pre>#Feature scaling<br>from sklearn.preprocessing import StandardScaler<br>sc_X = StandardScaler()<br>X_train = sc_X.fit_transform(X_train)<br>X_test = sc_X.fit_transform(X_test)</pre><p>If features are on different scales, larger scale features might dominate the learning process, leading to biased results. Scaling features to a common scale (often between 0 and 1 or with a mean of 0 and standard deviation of 1) helps the algorithm converge faster and gives equal importance to all features, leading to better model performance.</p><p><strong>Train and Test the Model:</strong> Let the magic happen as you train and test the logistic regression model. The training set is used to teach the model the underlying patterns in the data, while the testing set is reserved to evaluate the model’s performance on data it hasn’t seen before.</p><pre>#Fitting logistic regression model into the training dataset<br>from sklearn.linear_model import LogisticRegression<br>classifier = LogisticRegression(random_state=0)<br>classifier.fit(X_train, y_train)</pre><p>Without proper training and testing, you risk overfitting, where the model fits the training data too closely and performs poorly on new data, or underfitting, where the model doesn’t capture the data’s patterns sufficiently.</p><pre>y_pred = classifier.predict(X_test)<br>y_pred</pre><p><strong>Model Evaluation using the confusion matrix: </strong>The confusion matrix provides a comprehensive overview of how well the model is performing in terms of true positives, true negatives, false positives, and false negatives. These metrics help assess the model’s accuracy, precision, recall, and F1-score.</p><pre>#Evaluation using the consusion matrix<br>from sklearn.metrics import confusion_matrix<br>cm = confusion_matrix(y_test, y_pred)<br>cm</pre><p>Accuracy tells us the overall correctness of the model’s predictions, precision informs about the proportion of true positive predictions among all positive predictions, recall measures the proportion of actual positives that were correctly predicted, and the F1-score combines both precision and recall into a single metric.</p><p><strong>Confusion Matrix:</strong></p><p>This is an essential tool to evaluate model performance. It’s like a report card showing correct and incorrect predictions.</p><p>Understanding Confusion Matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*P9t-i1PSatg8Qm3YPuhWdg.jpeg" /></figure><ul><li>True Positives (TP): Correctly predicted positive instances.</li><li>True Negatives (TN): Correctly predicted negative instances.</li><li>False Positives (FP): Incorrectly predicted positive instances.</li><li>False Negatives (FN): Incorrectly predicted negative instances.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*b2eFlTJkvwpgFaOm3AufpQ.png" /><figcaption>Results from the confusion matrix</figcaption></figure><p>From the results shown above, the confusion matrix provided is a representation of the performance of the classification model, particularly in the context of binary classification. The matrix is organized into four values, which are as follows:</p><p><strong>True Positive (TP): 63</strong></p><p>This indicates that 63 instances were correctly predicted as the positive class (e.g., the class of interest).</p><p><strong>False Positive (FP): 5</strong></p><p>This indicates that 5 instances were incorrectly predicted as the positive class when they actually belong to the negative class.</p><p><strong>False Negative (FN): 8</strong></p><p>This indicates that 8 instances were incorrectly predicted as the negative class when they actually belong to the positive class.</p><p><strong>True Negative (TN): 24</strong></p><p>This indicates that 24 instances were correctly predicted as the negative class.</p><p>These values are used to compute various evaluation metrics for the classification model. Let’s break down some of these metrics:</p><p><strong>Accuracy:</strong> The accuracy of the model is the ratio of correctly predicted instances (TP + TN) to the total number of instances. In this case: (63 + 24) / (63 + 5 + 8 + 24) = 87 / 100 = 0.87 or 87%.</p><p><strong>Precision:</strong> Precision is the ratio of correctly predicted positive instances (TP) to the total predicted positive instances (TP + FP). In this case: 63 / (63 + 5) = 0.926 or 92.6%.</p><p><strong>Recall (Sensitivity or True Positive Rate):</strong> Recall is the ratio of correctly predicted positive instances (TP) to the total actual positive instances (TP + FN). In this case: 63 / (63 + 8) = 0.887 or 88.7%.</p><p><strong>F1-Score:</strong> The F1-score is the harmonic mean of precision and recall, providing a balanced measure between the two. It’s especially useful when there’s an uneven class distribution. It’s calculated as: 2 * (Precision * Recall) / (Precision + Recall).</p><h3>Conclusion</h3><p>As Day 3 draws to a close in my exploration of machine learning algorithms, I’ve immersed myself into the remarkable realm of logistic regression. I’ve shattered misconceptions about its name, witnessed its prowess in predicting categorical outcomes, and taken my first steps in implementing this invaluable tool.</p><p>With real-world examples and hands-on experience, I’ve opened the door to a world of predictive modeling possibilities. Stay tuned for more enlightening chapters ahead as I continue my learning journey through the captivating landscape of machine learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7762a6dce185" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 2: Mastering Linear Regression]]></title>
            <link>https://medium.com/@danielOkia/day-2-mastering-linear-regression-a5ae07ddd17e?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5ae07ddd17e</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 14:23:08 GMT</pubDate>
            <atom:updated>2023-08-22T14:23:08.662Z</atom:updated>
            <content:encoded><![CDATA[<p>Join me on Day 2 of my machine learning journey as we dive into the captivating world of linear regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ugX-Nc-8UF5p_ctZ4b5syw.jpeg" /></figure><p>Welcome back to my machine learning journey! Today, we’re delving into the cornerstone of predictive modeling — Linear Regression. This powerful approach allows us to uncover relationships between variables, predict outcomes, and make informed decisions. Let’s explore the history, concepts, and implementation of linear regression, step by step.</p><h3>The Genesis of Linear Regression</h3><p>The roots of linear regression trace back to the 19th century? Francis Galton, a pioneer in statistics, set the stage by studying the heights of fathers and sons. He aimed to predict a son’s height based on his father’s height — a remarkable endeavor given the era’s limited technology. By leveraging the principle of Mean Square Error, Galton derived the “best line of fit” to predict a son’s height using his father’s stature. This marked the birth of linear regression.</p><h3>The Essence of Linear Regression</h3><p>At its core, linear regression seeks to establish a relationship between independent variables (predictors) and a dependent variable (target). The goal is to minimize the error between data points and the regression line. This line of best fit encapsulates the relationship’s essence, enabling us to make accurate predictions.</p><h3>Navigating Implementation: A Step-by-Step Guide</h3><p>In this section, we’ll embark on an exciting journey of building a simple linear regression model from scratch. Each step we take is a building block that brings us closer to unlocking the predictive power of our data. But it’s not just about the how — we’ll also explore the why behind each step, understanding its significance in the grand scheme of creating accurate predictions.</p><p>In this step-by-step guide, I’ll be using Jupyter Notebooks to build our simple Linear Regression Model.</p><h3><strong>Download Dataset</strong></h3><p>Before we dive in, make sure to grab the essential tool for our project — the salary dataset. This dataset will be the backbone of our exploration, allowing us to predict an employee’s salary based on their years of experience. You can download the salary dataset by clicking the link below;</p><p><a href="https://drive.google.com/drive/folders/1FaV91OkTsABJrjnfeeTR4rwLe0mxFHxZ">ML Algorithms dataset - Google Drive</a></p><p><strong>Import Libraries and dataset:</strong></p><p>Begin by installing and importing the necessary libraries — your toolkit for creating the model. Libraries like NumPy and scikit-learn provide tools to simplify complex operations.</p><pre>import pandas as pd<br>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><p>Using pandas, lets import and display the dataset into Jupyter Notebook</p><pre>#Importing dataset<br>data = pd.read_csv(&#39;Salary_data.csv&#39;)<br>data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*yBCcDnzTQUQd16F5W8yEEQ.png" /><figcaption>Salary Dataset</figcaption></figure><p><strong>Extract Variables:</strong></p><p>Identify your independent and dependent variables. In our example, we’re predicting employee salaries (<em>dependent</em>) based on years of experience (<em>independent</em>). Identifying predictors and targets lays the foundation for understanding your model’s purpose.</p><pre>#Extracting dependent and independent variables<br>X = data.iloc[:, :-1].values<br>y = data.iloc[:, 1].values</pre><p>In the above code, if you’re building a predictive model, typically X represents our input features or independent variables, and y represents our target variable or dependent variable that we&#39;re trying to predict. The iloc function is used to index the data by its location, allowing us to select specific rows and columns from the dataset.</p><p><strong>Data Splitting:</strong></p><p>Divide your dataset into training and testing subsets. This separation ensures your model’s evaluation is unbiased. Separating the data also ensures your model doesn’t “memorize” and can generalize to new data.</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 1/3, random_state = 0)</pre><p>The code above uses the train_test_split function from the sklearn.model_selection module to split a dataset into training and testing subsets for both independent and dependent variables. This separation into training and testing sets is pivotal for training our machine learning model on one subset and assessing its performance on unseen data. This methodology helps us gauge how well our model can generalize to new data, a fundamental aspect of model evaluation.</p><p><strong>Model Fitting:</strong></p><p>Fit the linear regression model using your training data. This step allows the model to learn the underlying relationship. This step allows the algorithm to learn and capture patterns from your training data.</p><pre>from sklearn.linear_model import LinearRegression<br>lr = LinearRegression()<br>lr.fit(X_train, y_train)</pre><p>The code above is using the LinearRegression class from the sklearn.linear_model module to create and train a linear regression model. The code utilizes the scikit-learn library to implement a linear regression model. It imports the LinearRegression class, initializes an instance of it as lr, and then fits the model using the training data (X_train and y_train). This process trains the model to establish the optimal relationship between independent and dependent variables, enabling it to make accurate predictions based on new data.</p><p><strong>Prediction:</strong></p><p>Apply the trained model to your test dataset to predict employee salaries based on experience. This provides actionable insights for decision-making.</p><pre>y_pred = lr.predict(X_test)<br>y_pred</pre><p>The above provided code calculates predicted values (y_pred) using the trained linear regression model (lr) on the testing subset (X_test). This generates predictions for the target variable based on the independent variables. The resulting y_pred array holds these predictions, which can be further analyzed or compared to the actual testing data.</p><p><strong>Residuals Exploration:</strong></p><p>Examine residuals — the differences between predicted and actual values. This step helps in evaluating model performance. Analyzing residuals helps uncover areas where the model might be lacking.</p><pre>from sklearn import metrics<br>print(&#39;MAE: &#39;, metrics.mean_absolute_error(y_test, y_pred))<br>print(&#39;MSE: &#39;, metrics.mean_squared_error(y_test, y_pred))<br>print(&#39;RMSE: &#39;, np.sqrt(metrics.mean_absolute_error(y_test, y_pred)))</pre><p>The code above leverages scikit-learn and numpy libraries to assess the performance of a linear regression model’s predictions.</p><ul><li>The metrics.mean_absolute_error(y_test, y_pred) computes the average absolute difference between predicted and actual values, conveying the typical prediction error.</li><li>metrics.mean_squared_error(y_test, y_pred) calculates the average squared difference.</li><li>np.sqrt(metrics.mean_absolute_error(y_test, y_pred)) yields the Root Mean Squared Error (RMSE), presenting a more understandable error measure in the same units as the target variable.</li></ul><p>These metrics collectively help gauge the accuracy of the model&#39;s predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*bxBQ2ADqdoBOOnMwYow5CA.png" /></figure><p>From the results obtained from gauging the accuracy of the model’s prediction;</p><ul><li>MAE: 3426.43 (On average, predictions are off by approximately $3426.43 from the actual values.)</li><li>MSE: 21026037.33 (The average squared difference between predictions and actual values is around 21026037.33.)</li><li>RMSE: 58.54 (The RMSE value of 58.54 indicates the typical error magnitude in the original units of the target variable, suggesting that predictions are off by about $58.54 on average.)</li></ul><p>As I conclude Day 2 of my journey into the world of machine learning, I’ve explored the foundational concepts and implementation of linear regression. From its historical origins to building and evaluating my first model, I’ve uncovered and explored the power of predictive modeling.</p><p>But my adventure is far from over! In the upcoming chapter, I delve even deeper as I dive into the details of logistic regression. Get ready to unravel how this method enables us to tackle classification challenges with precision and insight. Stay tuned for an exciting exploration of logistic regression in our next chapter!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5ae07ddd17e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 1: A Beginner’s Guide to Machine Learning]]></title>
            <link>https://medium.com/@danielOkia/day-1-a-beginners-guide-to-machine-learning-7565c2383bd0?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7565c2383bd0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 17:54:13 GMT</pubDate>
            <atom:updated>2023-08-21T17:54:13.856Z</atom:updated>
            <content:encoded><![CDATA[<p>Unveiling the Basics and Real-World Applications</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*57xU-K0SNkgv1Pho" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to my Day 1 journey into the fascinating realm of machine learning! In this beginner’s guide, I’ll take you on an exploratory ride through the core concepts of machine learning, its essential processes, various types, and some of the most popular algorithms that drive its magic. Additionally, we’ll delve into real-world applications that showcase how machine learning is transforming industries around the globe.</p><h3>What is Machine Learning?</h3><p>At its heart, machine learning is a subset of artificial intelligence that enables computers to learn from data without being explicitly programmed. This groundbreaking technology equips computers to recognize patterns, make informed decisions, and improve their performance over time.</p><h3>Real-World Applications of Machine Learning</h3><p>Machine learning’s real-world applications have permeated nearly every facet of our lives, revolutionizing industries and enhancing our experiences. From weather forecasting that aids in planning outdoor activities to financial institutions employing fraud detection algorithms to secure our transactions, machine learning is at work.</p><p><strong>Weather Forecasting: </strong>Imagine accurate weather predictions that help you plan your day. Machine learning algorithms analyze historical data to forecast weather conditions, ensuring we stay informed and prepared.</p><p><strong>Fraud Detection:</strong> Banks and financial institutions employ machine learning to detect fraudulent transactions in real-time, safeguarding our assets and preventing unauthorized activities.</p><p><strong>Medical Research: </strong>Machine learning algorithms analyze vast amounts of medical data to identify trends and potential treatments, revolutionizing healthcare research and diagnostics.</p><p><strong>Facial Recognition:</strong> Social media platforms and security systems use facial recognition powered by machine learning to identify individuals, enhancing user experience and security protocols.</p><p><strong>Gaming:</strong> Machine learning techniques enable sophisticated AI opponents in video games, creating immersive and challenging gaming experiences.</p><h3>The Machine Learning Process</h3><h3>1. Data Gathering</h3><p>The journey begins with collecting relevant data. For instance, to predict ice cream sales based on temperature, historical sales and temperature data are essential.</p><h3>2. Data Pre-processing</h3><p>Raw data is often messy and incomplete. Pre-processing involves cleaning, transforming, and organizing data for effective analysis.</p><h3>3. Choosing a Model</h3><p>Selecting the right algorithm is crucial. Linear regression, logistic regression, decision trees, and more are available options, each suitable for different scenarios.</p><h3>4. Training the Model</h3><p>This phase involves feeding the algorithm with labeled data, allowing it to learn patterns and relationships within the data.</p><h3>5. Testing the Model</h3><p>Testing assesses the model’s performance on new, unseen data. This step ensures the model’s reliability and generalization ability.</p><h3>6. Tuning the Model</h3><p>Fine-tuning optimizes the model’s performance by adjusting hyperparameters to achieve better results.</p><h3>7. Prediction</h3><p>After successful training and testing, the model is ready for real-world predictions. For example, it can predict employee salaries based on experience.</p><h3>Types of Machine Learning</h3><h3>Supervised Learning</h3><p>Supervised learning involves training a model on labeled data, where the algorithm learns patterns to make predictions or classifications. For example, predicting house prices based on features.</p><p>Methods of supervised learning include:</p><ul><li><strong>Regression:</strong> Predicting outcomes within a continuous range, like forecasting weather or assessing risk.</li><li><strong>Classification:</strong> Categorizing data into predefined classes, such as fraud detection or email spam filtering.</li></ul><h3>Unsupervised Learning</h3><p>Unsupervised learning, on the other hand, deals with unlabeled data, clustering similar data points or discovering relationships between variables, such as grouping customer segments for targeted marketing.</p><p>Methods of unsupervised learning include:</p><ul><li><strong>Clustering:</strong> Grouping similar data points, used in medical research to identify patient clusters with similar conditions.</li><li><strong>Association:</strong> Discovering relationships between variables, applied in market basket analysis to suggest product bundles.</li></ul><h3>Reinforcement Learning</h3><p>This type focuses on training models to make sequences of decisions, as seen in robot navigation, gaming AI, and optimizing industrial processes like stock trading.</p><h3>Popular Machine Learning Algorithms</h3><p><strong>Linear Regression:</strong> Predicting values based on linear relationships, as demonstrated by predicting ice cream sales from temperature.</p><p><strong>Logistic Regression:</strong> Used for classification tasks, like determining whether an email is spam or not.</p><p><strong>Decision Trees: </strong>Representing decisions and their possible consequences, beneficial for various applications, including medical diagnosis.</p><p><strong>Random Forest:</strong> An ensemble method of decision trees, offering enhanced accuracy and preventing overfitting.</p><p><strong>K Nearest Neighbours (KNN):</strong> Assigning a class label to an item based on its neighbors, employed in recommendation systems and image classification.</p><h3><strong>Conclusion</strong></h3><p>In my Day 1 journey into the realm of machine learning, I’ve uncovered the fundamental concepts, processes, types, and algorithms that power this revolutionary technology. Armed with this knowledge, you should now be equipped to delve deeper into the world of machine learning, where countless opportunities await across diverse industries.</p><p>In the upcoming chapters, get ready to take a deep dive into the practical realm of machine learning. We’re not just stopping at theory — we’re rolling up our sleeves and delving into project-based learning. Brace yourself for an immersive experience where we’ll actually build machine learning models from the ground up. So, fasten your seatbelts and prepare for a hands-on journey that will equip you with the skills to bring your ideas to life through real-world applications of machine learning. Stay engaged for an enlightening and empowering adventure!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7565c2383bd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cultivating Success: Optimizing Crop Selection through Climate and Soil Analysis]]></title>
            <link>https://medium.com/@danielOkia/cultivating-success-optimizing-crop-selection-through-climate-and-soil-analysis-90a146c5bbf?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a146c5bbf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sustainable-farming]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Mon, 15 May 2023 15:39:04 GMT</pubDate>
            <atom:updated>2023-05-15T15:46:01.505Z</atom:updated>
            <content:encoded><![CDATA[<h3>Harnessing Data-Driven Insights for Sustainable Agricultural Decision-Making.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjAkkAfa1jYfwVduuN6VcQ.jpeg" /></figure><h3>Introduction</h3><p>In the ever-evolving world of agriculture, the quest for optimal productivity and sustainability has become increasingly crucial. As the global population grows and climate change introduces unpredictable variables, the need for precise agricultural optimization has never been more crucial. The ability to predict and recommend the most suitable crops to cultivate based on climatic and soil conditions can unlock a number of possibilities, empowering farmers to make informed decisions and maximize their yield potential.</p><blockquote>This project investigates into the fascinating world of agricultural optimization, showcasing the development of a <strong>predictive model</strong> that harnesses the power of data analysis to revolutionize crop selection and pave the way for a more resilient and prosperous agricultural future.</blockquote><h3>Tools:</h3><p><strong>Python and Jupyter Notebooks:</strong></p><p>Python and Jupyter notebooks are invaluable tools in data analytics due to their versatility, extensive libraries, interactive capabilities, and collaborative nature. Their combined usage empowers analysts and data scientists to efficiently process data, derive meaningful insights, and communicate findings effectively. Embracing Python and Jupyter notebooks can significantly enhance the analytical workflow, promoting reproducibility, and facilitating collaboration in the worldof data analytics.</p><h3>Project Methodology:</h3><ul><li>Data Importing</li><li>Exploratory Data Analysis</li><li>Insights, Patterns and Visualization</li><li>Building Model</li></ul><p><strong>Data Importing:</strong></p><p>This is the process of bringing data into a system for analysis, enabling further investigation and manipulation. In this project, I will be importing the dataset I am going to use into Jupyter Notebooks.</p><p>Before importing the dataset into jupyter notebooks, we need to import the pandas library for the task as well as all the necessary libraries required for this project as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*5PJRPxB7Hb928W4tX6yowg.png" /></figure><p>Then I will import the dataset using the pandas library and display the top 5 rows using the head () function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*qdeUezM7kEU1oAhk9dfwTw.png" /></figure><h3><strong>Exploratory Data Analysis:</strong></h3><p>This is an initial examination of data to understand its characteristics, identify patterns, and gain insights before formal analysis.</p><pre>data[&#39;label&#39;].unique()<br>data.shape<br>data.info()<br>data.describe()<br>data[&#39;label&#39;].value_counts()</pre><p>The above code blocks serve crucial purposes in exploratory data analysis (EDA). <strong>data[‘label’].unique()</strong> helps identify unique categories, <strong>data.shape</strong> provides dataset size, <strong>data.info()</strong> reveals column information such as the columns and their specific data types. <strong>data.describe()</strong> gives statistical insights, and <strong>data[‘label’].value_counts()</strong> helps understand class distribution — a comprehensive understanding of the dataset during EDA.</p><p><strong>Insights, Patterns, and Visualization:</strong></p><p>This is where we uncover meaningful information and trends in data through analysis techniques and presenting them visually for easier comprehension.</p><ul><li>Let’s start by finding the Average of the available climatic and soil conditions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*RDwAcYu8OxEM312LcdY2CA.png" /></figure><p>Finding the mean of each column in the dataset can provide valuable insights to gain a quantitative understanding of the prevailing conditions in their region for agricultural planning and decision-making forinstance:</p><ol><li><strong>Average Ratio of Nitrogen (N), Phosphorus (P), and Potassium (K) in the soil:</strong> These measures indicate the average nutrient levels available in the soil. Farmers can use this information to assess whether the nutrient levels meet the requirements of specific crops. Adjustments can be made, such as adding fertilizers, to optimize the nutrient composition for better crop growth and yield.</li><li><strong>Average Temperature in Celsius</strong>: Temperature plays a crucial role in determining the suitable growing conditions for various crops. Knowing the average temperature helps farmers understand the climatic conditions and choose crops that thrive in specific temperature ranges. It aids in planning planting schedules, selecting appropriate varieties, and managing potential temperature-related challenges.</li><li><strong>Average Relative Humidity in </strong>%: Humidity affects the moisture levels in the environment and influences crop growth and disease susceptibility. Monitoring the average humidity helps farmers assess the likelihood of excessive moisture, fungal diseases, or dry conditions. It enables them to implement appropriate irrigation strategies and disease prevention measures.</li><li><strong>Average PH Value of the soil:</strong> The pH value is a measure of the acidity or alkalinity of a substance, such as soil, water, or a solution. The pH level of soil significantly impacts nutrient availability to plants. By determining the average pH value, farmers can identify whether the soil is acidic, neutral, or alkaline. This information assists in selecting suitable crops and making adjustments to optimize soil pH through methods like soil amendments or acidification.</li><li><strong>Average Rainfall in mm:</strong> Rainfall patterns are critical for water availability, irrigation planning, and drought management. The average rainfall measurement helps farmers assess the water supply, make decisions on irrigation schedules, and plan for potential water scarcity or excess during specific periods.</li></ol><p><strong>Summary statistic for each crop:</strong></p><p>summary statistics for soil and climatic conditions provide vital information for crop suitability, optimal crop management, risk assessment, research, and data-driven decision making. They enable farmers to make informed choices, adapt to prevailing conditions, and maximize agricultural outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*xbFAvDMIkh3OvCT878zaLA.png" /></figure><p>The above code defines a function called “summary” that takes a list of crop names as an input parameter. It uses the input crop names to filter the dataset and extract data specific to each crop. The function then calculates and displays summary statistics for three soil nutrient variables: Nitrogen (N), Phosphorus (P), and Potassium (K). For each nutrient, it prints the minimum, average, and maximum values required by the selected crops.</p><p>The above code is incomplete as it does not show the summary statistics for the climatic conditions temperature, humidity, ph and rainfall which must be added as well. This information is important for farmers and agricultural practitioners as it helps them understand the range of nutrient levels needed for optimal crop growth and productivity as well as insights into the preferred ranges of temperature, humidity, and rainfall for different crops.</p><p><strong>Comparing the average requirement for each crop with the average required conditions:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*9DkVPy43X67pKU5m3rFHmQ.png" /></figure><p>The above code defines a function called “compare” that takes a list of conditions as input, representing different soil and climatic variables. It then compares the average values of these conditions across different crops in the dataset.</p><p>The function first calculates and prints the overall average value for the specified conditions across all crops in the dataset. It then proceeds to print the average values for each condition specific to individual crops, such as rice, maize, chickpea, kidney beans, and so on.</p><pre>def compare(conditions = [&#39;N&#39;,&#39;K&#39;,&#39;P&#39;,&#39;temperature&#39;,&#39;humidity&#39;,&#39;ph&#39;,&#39;rainfall&#39;]):<br>    print(&quot;Crops which require greater than Average&quot;, conditions,&#39;\n&#39;)<br>    print(data[data[conditions] &gt; data[conditions].mean()][&#39;label&#39;].unique())<br>    print(&quot;----------------------------------------------------------------&quot;)<br>    print(&quot;Crops which require less than Average&quot;, conditions, &#39;\n&#39;)<br>    print(data[data[conditions] &lt;= data[conditions].mean()][&#39;label&#39;].unique())</pre><p>The above code identifies crops that have specific requirements above or below the average values for the given conditions. It helps in highlighting crops that have distinct needs compared to the overall average, allowing farmers to focus on crops with unique characteristics or adapt their cultivation practices accordingly.</p><p>This information assists farmers in customized crop management, resource allocation, targeted crop selection, and implementing precision agriculture practices for optimal farming outcomes.</p><h3><strong>Distribution:</strong></h3><p>The distribution plots show the frequency distribution of each variable, providing insights into the spread and shape of their values. The x-axis represents the range of values for each variable, while the y-axis represents the frequency or probability density.</p><pre>plt.rcParams[&#39;figure.figsize&#39;] = (15,7)<br><br>plt.subplot(2,4,1)<br>sns.distplot(data[&#39;N&#39;], color = &#39;lightgrey&#39;)<br>plt.xlabel(&#39;Ratio of Nitrogen&#39;, fontsize = 12)<br>plt.grid()<br><br>plt.subplot(2,4,2)<br>sns.distplot(data[&#39;P&#39;], color = &#39;lightblue&#39;)<br>plt.xlabel(&#39;Ratio of Phosphorous&#39;, fontsize = 12)<br>plt.grid()<br><br>plt.subplot(2,4,3)<br>sns.distplot(data[&#39;K&#39;], color = &#39;skyblue&#39;)<br>plt.xlabel(&#39;Ratio of Potassium&#39;, fontsize = 12)<br>plt.grid()<br><br>plt.subplot(2,4,4)<br>sns.distplot(data[&#39;temperature&#39;], color = &#39;brown&#39;)<br>plt.xlabel(&#39;Temperature&#39;, fontsize = 12)<br>plt.grid()<br><br>plt.subplot(2,4,5)<br>sns.distplot(data[&#39;humidity&#39;], color = &#39;lightgreen&#39;)<br>plt.xlabel(&#39;Humidity&#39;, fontsize = 12)<br>plt.grid()<br><br>plt.subplot(2,4,6)<br>sns.distplot(data[&#39;ph&#39;], color = &#39;yellow&#39;)<br>plt.xlabel(&#39;PH&#39;, fontsize = 12)<br>plt.grid()<br><br>plt.subplot(2,4,7)<br>sns.distplot(data[&#39;rainfall&#39;], color = &#39;orange&#39;)<br>plt.xlabel(&#39;Rainfall&#39;, fontsize = 12)<br>plt.grid()</pre><p>The above code utilizes the Matplotlib and Seaborn libraries to create a grid of subplots, each displaying a distribution plot for a specific variable in the dataset as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*mtxDrG1VV44FPRZw5Xbc9Q.png" /></figure><p><strong>Impact of different conditions on the crops:</strong></p><pre><br>plt.rcParams[&#39;figure.figsize&#39;] = (15, 7)<br><br>plt.subplot(2, 4, 1)<br>sns.barplot(data[&#39;N&#39;], data[&#39;label&#39;])<br>plt.ylabel(&#39; &#39;)<br>plt.xlabel(&#39;Ratio of Nitrogen&#39;, fontsize = 10)<br>plt.yticks(fontsize = 10)<br><br>plt.subplot(2, 4, 2)<br>sns.barplot(data[&#39;P&#39;], data[&#39;label&#39;])<br>plt.ylabel(&#39; &#39;)<br>plt.xlabel(&#39;Ratio of Phosphorous&#39;, fontsize = 10)<br>plt.yticks(fontsize = 10)<br><br>plt.subplot(2, 4, 3)<br>sns.barplot(data[&#39;K&#39;], data[&#39;label&#39;])<br>plt.ylabel(&#39; &#39;)<br>plt.xlabel(&#39;Ratio of Potassium&#39;, fontsize = 10)<br>plt.yticks(fontsize = 10)<br><br>plt.subplot(2, 4, 4)<br>sns.barplot(data[&#39;temperature&#39;], data[&#39;label&#39;])<br>plt.ylabel(&#39; &#39;)<br>plt.xlabel(&#39;Temperature&#39;, fontsize = 10)<br>plt.yticks(fontsize = 10)<br><br>plt.subplot(2, 4, 5)<br>sns.barplot(data[&#39;humidity&#39;], data[&#39;label&#39;])<br>plt.ylabel(&#39; &#39;)<br>plt.xlabel(&#39;Humidity&#39;, fontsize = 10)<br>plt.yticks(fontsize = 10)<br><br>plt.subplot(2, 4, 6)<br>sns.barplot(data[&#39;ph&#39;], data[&#39;label&#39;])<br>plt.ylabel(&#39; &#39;)<br>plt.xlabel(&#39;pH of Soil&#39;, fontsize = 10)<br>plt.yticks(fontsize = 10)<br><br>plt.subplot(2, 4, 7)<br>sns.barplot(data[&#39;rainfall&#39;], data[&#39;label&#39;])<br>plt.ylabel(&#39; &#39;)<br>plt.xlabel(&#39;Rainfall&#39;, fontsize = 10)<br>plt.yticks(fontsize = 10)<br><br>plt.suptitle(&#39;Visualizing the Impact of Different Conditions on Crops&#39;, fontsize = 15)<br>plt.show()</pre><p>The above code creates a visual representation of the impact of different conditions on various crops. It uses the Seaborn library to create bar plots for each condition against the crop labels as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*fOfLC70djMXLg__Pk56Ycw.png" /></figure><p>This provides a quick overview of how different conditions contribute to the growth and development of various crops, aiding in the identification of patterns and relationships between conditions and crop types.</p><h3><strong>Patterns</strong></h3><p>Below are some interesting facts</p><pre>print(&quot;Interesting Patterns&quot;)<br>print(&quot;------------------------------------------------------------&quot;)<br>print(&quot;Crops that require high ratio of Nitrogen content in soil : &quot;, data[data[&#39;N&#39;] &gt; 120][&#39;label&#39;].unique())<br>print(&quot;Crops that require high ratio of Phosphorous content in soil : &quot;, data[data[&#39;P&#39;] &gt; 100][&#39;label&#39;].unique())<br>print(&quot;Crops that require high ratio of Potassium content in soil : &quot;, data[data[&#39;K&#39;] &gt; 200][&#39;label&#39;].unique())<br>print(&quot;Crops that require Very high rainfall  : &quot;, data[data[&#39;rainfall&#39;] &gt; 200][&#39;label&#39;].unique())<br>print(&quot;Crops that require Very low Temperature: &quot;, data[data[&#39;temperature&#39;] &lt; 10][&#39;label&#39;].unique())<br>print(&quot;Crops that require very High Temperature : &quot;, data[data[&#39;temperature&#39;] &gt; 40][&#39;label&#39;].unique())<br>print(&quot;Crops that require Very Low Humidity : &quot;, data[data[&#39;humidity&#39;] &lt; 20][&#39;label&#39;].unique())<br>print(&quot;Crops that require Very Low PH : &quot;, data[data[&#39;ph&#39;] &lt; 4][&#39;label&#39;].unique())<br>print(&quot;Crops that require Very High PH : &quot;, data[data[&#39;ph&#39;] &gt; 9][&#39;label&#39;].unique())</pre><p>The above code identifies and prints crops that have certain requirements or characteristics beyond a certain threshold for example:</p><ul><li><strong>Crops that require high ratio of Nitrogen content in soil:</strong> This shows the crops that need a nitrogen content in the soil higher than 120.</li><li><strong>Crops that require high ratio of Phosphorous content in soil</strong>: This lists the crops that require a phosphorous content in the soil greater than 100 as shown below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*cY-BONVnoytQJSGWHgIj4A.png" /></figure><p>These patterns provide insights into the specific requirements of different crops, allowing farmers and researchers to understand the conditions that are ideal for their growth.</p><p>Let’s identify Summer, Winter and Rainy crops.</p><pre>print(&quot;Summer Crops&quot;)<br>print(data[(data[&#39;temperature&#39;] &gt; 30) &amp; (data[&#39;humidity&#39;] &gt; 50)][&#39;label&#39;].unique())<br>print(&quot;--------------------------------------------------------------------------&quot;)<br><br>print(&quot;Winter Crops&quot;)<br>print(data[(data[&#39;temperature&#39;] &lt; 20) &amp; (data[&#39;humidity&#39;] &gt; 30)][&#39;label&#39;].unique())<br>print(&quot;----------------------------------------------------------------------------&quot;)<br><br>print(&quot;Rainy Crops&quot;)<br>print(data[(data[&#39;rainfall&#39;] &gt; 200) &amp; (data[&#39;humidity&#39;] &gt; 30)][&#39;label&#39;].unique())</pre><p>The above code prints the categories of crops based on specific climatic conditions. The given thresholds used define the specific climatic conditions for each category of crops. These thresholds are based on the general knowledge and requirements of crops during different seasons. By using these thresholds, the code filters and identifies the crops that fall within the specified conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*CQcFh4G_2Hzk6LVJ-39Wpw.png" /></figure><p>This information can be valuable for farmers and agricultural practitioners as it helps them determine which crops are suitable to be grown during different seasons. It assists in making informed decisions regarding crop selection and planning based on the prevailing climatic conditions, ultimately optimizing agricultural productivity and yield.</p><h3><strong>Clustering Analysis</strong></h3><p>This is a technique used to classify the data points into relative groups called clusters. In clustering analysis, data points are grouped together based on their similarities in terms of features or attributes.</p><p>To perform clustering analysis for this project I will use sci-kit learn(sk-learn) a popular machine learning library in python which provides a wide range of clustering algorithms such as k-means.</p><p><em>Lets prepare the data for clustering by selecting relevant columns and organizing them in a new DataFrame. This provides flexibility, clarity, and control over the specific subset of data we want to work with hence enabling focused analysis and facilitating subsequent data processing steps.</em></p><pre>from sklearn.cluster import KMeans<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br><br>x = data.loc[:, [&#39;N&#39;,&#39;P&#39;,&#39;K&#39;,&#39;temperature&#39;,&#39;ph&#39;,&#39;humidity&#39;,&#39;rainfall&#39;]].values<br>print(x.shape)<br><br>x_data = pd.DataFrame(x)<br>x_data.head(5)</pre><p>First, we import the KMeans class from the sklearn.cluster module and the warnings module in Python. It then sets a filter to ignore any warning messages.</p><p>We then extract specific columns (’N’, ‘P’, ‘K’, ‘temperature’, ‘ph’, ‘humidity’, ‘rainfall’) from the data DataFrame and assigns them to the variable x. The values of these columns are stored as a NumPy array.</p><p>Then, a new DataFrame named <strong>x_data </strong>is created using the extracted values from x. This DataFrame contains the selected columns and can be utilized for clustering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*SRzpKP59yDbDJZLnqpiY_Q.png" /></figure><p><strong>Determining the number of clusters.</strong></p><p>Determining the number of clusters is an essential step in clustering analysis. Clustering algorithms, such as K-means, require us to specify the number of clusters beforehand. The goal is to partition the data into groups or clusters based on similarity, where data points within a cluster are more similar to each other compared to those in different clusters.</p><p>In this project, I used the elbow method. In this approach, the within-cluster sum of squares (WCSS) is calculated for different values of K (number of clusters). The WCSS measures the compactness of the clusters. The plot of WCSS against K forms an “elbow” shape. The number of clusters is chosen at the point where adding more clusters does not significantly reduce the WCSS. The Elbow Method is a common technique used to determine the optimal number of clusters by examining the plot of WCSS against the number of clusters. The idea is to choose the value of K at the “elbow” point, where adding more clusters does not significantly reduce the WCSS.</p><pre>plt.rcParams[&#39;figure.figsize&#39;] = (10,4)<br><br>wcss = []<br>for i in range(1,11):<br>    km = KMeans(n_clusters = i, init = &#39;k-means++&#39;, max_iter = 300, n_init = 10, random_state = 0)<br>    km.fit(x)<br>    wcss.append(km.inertia_)<br>    <br>#Plot<br>plt.plot(range(1,11), wcss)<br>plt.title(&quot;Elbow Method&quot;, fontsize = 20)<br>plt.xlabel(&quot;Number of clusters&quot;)<br>plt.ylabel(&quot;wcss&quot;)<br>plt.show()</pre><p>The above code identifies the “elbow” or “knee” point in the plot, which represents the optimal number of clusters. The elbow point is the value of i where the rate of decrease in WCSS significantly slows down. The plot helps in selecting an appropriate number of clusters that balances the compactness of clusters (low WCSS) with the simplicity of the model (fewer clusters).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*4vkIVi1hOTPgvZJip91xWQ.png" /></figure><p>In the above plot, the x-axis represents the number of clusters, while the y-axis represents the within-cluster sum of squares (WCSS). The WCSS measures the compactness or the sum of squared distances of data points within each cluster. The elbow point refers to the point of inflection where the rate of decrease in WCSS significantly slows down. This point is usually chosen as an indication of the optimal number of clusters. Therefore, the rate of decrease in WCSS slows down at the elbow point when the number of clusters is 4.</p><p>Hence, based on the plot and the observed elbow point, 4 clusters are appropriate for the given dataset.</p><p><em>Lets implement the K means algorithm to perform clustering analysis with the code below.</em></p><pre>km = KMeans(n_clusters = 4, init = &#39;k-means++&#39;, max_iter = 300, n_init = 10, random_state = 0)<br>y_means = km.fit_predict(x)<br><br>a = data[&#39;label&#39;]<br>y_means = pd.DataFrame(y_means)<br>z = pd.concat([y_means, a], axis = 1)<br>z = z.rename(columns = {0: &#39;cluster&#39;})<br><br>#Clusters for each crops<br>print(&quot;Checking Results after applying the k means clustering analysis \n&quot;)<br>print(&quot;Crops in first cluster: &quot;, z[z[&#39;cluster&#39;] == 0][&#39;label&#39;].unique())<br>print(&quot;------------------------------------------------------------------&quot;)<br><br>print(&quot;Crops in Second cluster: &quot;, z[z[&#39;cluster&#39;] == 1][&#39;label&#39;].unique())<br>print(&quot;------------------------------------------------------------------&quot;)<br><br>print(&quot;Crops in Third cluster: &quot;, z[z[&#39;cluster&#39;] == 2][&#39;label&#39;].unique())<br>print(&quot;------------------------------------------------------------------&quot;)<br><br>print(&quot;Crops in Fourth cluster: &quot;, z[z[&#39;cluster&#39;] == 3][&#39;label&#39;].unique())</pre><p>The above code groups similar crops into clusters based on their features (N, P, K, temperature, ph, humidity, rainfall) using K-means clustering. By assigning crops to clusters, it allows for better understanding and organization of the crops based on their similarities in the given features as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*la8YsbyBeCvroVcmsR6tAg.png" /></figure><h3>Buiding Model</h3><p>Building a model involves selecting an appropriate algorithm or technique that can capture the underlying patterns in the data and generalize from it. The model is trained using a labeled dataset, where the input data and corresponding output (or target) values are provided. During training, the model learns the relationships between the input features and the target variable, adjusting its internal parameters to minimize the prediction errors.</p><p>In this project, Logistic Regression was employed to build the model.</p><p><strong>Importing necessary libraries.</strong></p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import classification_report</pre><p><strong>Splitting the Dataset.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*uIIsp9HxdYJQLI1H1nqhJw.png" /></figure><p>The above code separates the input features (x) and the target variable (y) from the original data DataFrame, allowing them to be used for model training and evaluation.</p><p><strong>Training and Testing the Dataset.</strong></p><pre>#Creating Training and Testing sets<br><br>x_train,x_test, y_train, y_test = train_test_split(x,y, test_size = 0.2, random_state = 0)<br>print(&quot;Shape of x_train: &quot;, x_train.shape)<br>print(&quot;Shape of x_test: &quot;, x_test.shape)<br>print(&quot;Shape of y_train: &quot;, y_train.shape)<br>print(&quot;Shape of y_test: &quot;, y_test.shape)</pre><p>The above code splits the data into training and testing sets, which is a common practice in machine learning to assess the model’s performance on unseen data.</p><p><strong>Creating a predictive model</strong></p><pre>model = LogisticRegression()<br>model.fit(x_train,y_train)<br>y_pred = model.predict(x_test)</pre><p>The above code is using logistic regression for classification using the LogisticRegression class from scikit-learn library.</p><p>The logistic regression algorithm uses a sigmoid function to map the input features to the target variable, estimating the probabilities of each class. During the training phase, the model adjusts its parameters to optimize the likelihood of predicting the correct class label. Then, during the prediction phase, the trained model applies these learned parameters to new data (x_test) to predict the corresponding class labels (<strong>y_pred</strong>).</p><p><strong>Model Evaluation</strong></p><p>Model evaluation plays a critical role in assessing performance, comparing models, identifying weaknesses, optimizing models, and building trust in machine learning applications. It enables informed decision-making and helps ensure the model’s effectiveness and reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*fMcncBR8kjxqzE8RL7sGxw.png" /></figure><p>The model seems to have performed well in classifying the crops based on the given features. It also seems that the model has achieved high accuracy and good performance across most of the classes. Here are some key observations:</p><p>. . The overall accuracy of the model is 0.97, indicating that it correctly predicted the crop labels for 97% of the instances in the test set.</p><ul><li>The precision, recall, and F1-scores for most of the classes are very high, often reaching 1.00, which indicates that the model performed well in correctly predicting those classes. This suggests that the model has learned the patterns and characteristics specific to those crops.</li><li>Some classes, such as blackgram, cotton, jute, lentil, mothbeans, and rice, have slightly lower precision, recall, and F1-scores compared to others. This may indicate that the model had some difficulty distinguishing those classes from similar ones, resulting in slightly lower performance.</li><li>The support values indicate the number of instances available for each class. The dataset appears to be well-balanced, with a similar number of instances for most of the classes.</li></ul><p><strong>Let’s make some predictions based on the model to test its accuracy.</strong></p><pre>prediction = model.predict((np.array([[90,42,43,20.9,82,6.5,202.9]])))<br>print(&quot;Suggested crop is: &quot;, prediction)</pre><p>The above code is making a prediction using the trained model. It takes a single data instance represented as a NumPy array [[90, 42, 43, 20.9, 82, 6.5, 202.9]], which contains the values for the features &#39;N&#39;, &#39;P&#39;, &#39;K&#39;, &#39;temperature&#39;, &#39;ph&#39;, &#39;humidity&#39;, and &#39;rainfall&#39; for a specific crop.</p><p>The expected prediction as shown below should be rice as in the 1st row of the sample data set below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*M-KT1Yc8Dv6p7hOik9xUKA.png" /></figure><p><em>We can see that the model predicted rice.</em></p><p>Let’s do that again with different values.</p><pre>prediction = model.predict((np.array([[20,7,9,29,92,7,111.2]])))<br>print(&quot;Suggested crop is: &quot;, prediction)</pre><p>The above code allows you to input specific values for the features of a crop, and the model predicts the most likely crop based on those feature values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*-7blfwPBez5YU_pXR0NH2w.png" /></figure><p>The model once again made the correct prediction for the suggested crop which is <strong>oranges</strong>.</p><h3><strong>Conclusion</strong></h3><p>The agricultural optimization project has provided valuable insights and tools for optimizing crop selection and improving agricultural practices. By analyzing various environmental conditions such as nutrient levels, temperature, humidity, pH, and rainfall, we have successfully identified key factors that significantly influence crop growth and yield.</p><p>Through exploratory data analysis, we observed distinct patterns and distributions of these environmental factors across different crop types. This allowed us to understand the specific requirements of each crop, enabling farmers to make informed decisions about crop selection based on their local conditions.</p><p>Using clustering analysis, we grouped crops into clusters based on their similarity in environmental requirements. This clustering approach facilitates targeted agricultural planning and resource allocation, as crops within the same cluster exhibit similar needs. Farmers can now optimize their crop choices, tailor fertilizer application, and create favorable conditions to enhance productivity and sustainability.</p><p>The logistic regression model built on the dataset further enhanced our understanding of the relationship between environmental factors and crop classification. With an impressive accuracy of 97%, the model proved reliable in predicting the appropriate crop type based on given environmental inputs.</p><p>Overall, this project empowers farmers and agricultural stakeholders with valuable knowledge and tools for optimizing crop selection, resource management, and decision-making. By leveraging these insights, we can strive towards a more efficient, sustainable, and productive agricultural system, ultimately contributing to food security and economic growth in the agricultural sector.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a146c5bbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering the Hidden Emotions: Analyzing WhatsApp Chats with Python]]></title>
            <link>https://medium.com/@danielOkia/uncovering-the-hidden-emotions-analyzing-whatsapp-chats-with-python-f5edef3e1202?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5edef3e1202</guid>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[data-exploration]]></category>
            <category><![CDATA[data-insights]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 12:08:40 GMT</pubDate>
            <atom:updated>2023-03-23T15:45:07.262Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Exploring Sentiment Analysis of WhatsApp Chats through EDA.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nGRqRhc8KBiECJsp" /><figcaption>Photo by <a href="https://unsplash.com/@solomin_d?utm_source=medium&amp;utm_medium=referral">Dima Solomin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>The objective of this project was to analyze WhatsApp conversations of a WhatsApp group I belonged to using Python and different libraries such as Pandas, Seaborn, Matplotlib, Vader and NLTK. This analysis aimed to extract insights such as the most active users and time of day for the conversations, the sentiment of the messages, and the sentiment scores for each user.</p><p>In this project, I walked through the entire process of analyzing WhatsApp conversations, starting from importing, cleaning, modeling to exploring the data in Python.</p><h3><strong>Setting up the Environment</strong></h3><p>To set up the Python environment for this project, you will need to install Anaconda and Python 3.</p><p>We then create a new folder as our working directory to store our WhatsApp.txt file. In anaconda prompt, change directory to your working directory and run the code below to create a new environment.</p><pre>conda create -n whatsap python = 3.10 </pre><p>The above code creates a new environment named “whatsap” and specifies the python version. To activate our “hive” environment, run the code below.</p><pre>conda activate whatsap</pre><p>To get started, install jupyter and the following libraries:</p><ul><li><strong>pandas</strong>: For data manipulation and analysis</li><li><strong>matplotlib</strong>: For data visualization</li><li><strong>seaborn</strong>: For data visualization</li><li><strong>nltk</strong>: For natural language processing</li><li><strong>afinn and vader</strong>: For sentiment analysis</li></ul><p>You can install these libraries using pip, which is the package installer for Python. Open your terminal or command prompt and type the following commands:</p><pre>pip install pandas<br>pip install matplotlib<br>pip install seaborn<br>pip install nltk<br></pre><p>Once you have installed these libraries, you can open a Python IDE or Jupyter Notebook to start working on the project. In the notebook, you will need to import the libraries by adding the following lines of code.</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import nltk<br>from nltk.sentiment import SentimentIntensityAnalyzer<br></pre><h3><strong>Data Extraction and Cleaning:</strong></h3><p>In this section, we will describe how to extract and clean the WhatsApp chat data.</p><p><strong>Extracting or exporting Whatsapp Chats:</strong></p><p>First, open the WhatsApp chat on your phone that you want to analyze, and click on the three dots on the top right corner. Select “More” and then “Export Chat”. You can choose to export the chat with or without media, depending on your preference. I exported mine without media.</p><p>The next step is to read the text file into a Pandas DataFrame.</p><h3><strong>Data Preparation:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ae1SEjsZMOngDacN" /><figcaption>Photo by <a href="https://unsplash.com/ko/@dkfra19?utm_source=medium&amp;utm_medium=referral">Dimitri Karastelev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><pre>import re<br><br># define regex pattern for chat line<br>pattern = r&#39;^(\d{2}\/\d{2}\/\d{4}),\s(\d{2}:\d{2})\s-\s(.*?):\s(.*)$&#39;<br><br># create empty dataframe<br>df = pd.DataFrame(columns=[&quot;date&quot;, &quot;time&quot;, &quot;user&quot;, &quot;message&quot;])<br><br># read file line by line<br>with open(&quot;HQ.txt&quot;, encoding=&#39;utf-8&#39;) as f:<br>    for line in f:<br>        # match regex pattern with line<br>        match = re.match(pattern, line)<br>        if match:<br>            # extract groups from match<br>            groups = match.groups()<br>            # add row to dataframe<br>            df = df.append({&quot;date&quot;: groups[0], &quot;time&quot;: groups[1], &quot;user&quot;: groups[2], &quot;message&quot;: groups[3]}, ignore_index=True)<br><br># print dataframe<br>df</pre><p>The above code reads the “HQ.txt” file line by line using a for loop, and tries to match the regular expression pattern with each line. If the pattern matches, the code extracts the matching groups and adds them to a pandas DataFrame as a new row with columns for the date, time, user, and message. The ignore_index=True parameter ensures that the new row is appended with a unique index.</p><p><strong>Breaking down the regular expression patterns:</strong></p><p>This is really important towards reading txt files, data extraction and structuring our data.</p><pre>pattern = r&#39;^(\d{2}\/\d{2}\/\d{4}),\s(\d{2}:\d{2})\s-\s(.*?):\s(.*)$&#39;</pre><p>The regular expression pattern can be used to match and extract specific patterns in strings. In this case, the pattern is designed to match the format of each line in the WhatsApp chat text file, which follows the pattern:</p><p>“date, time — user: message”</p><p>Note that the regular expression pattern varries depending on the format of your whatsapp.txt file. Forinstance, a group pattern that matches the time in the format “HH:MM” with 2 digits for hours and minutes is different from the one that matches the time in the format “HH:MM am”. The above regular expression pattern matches the time in the format ““HH:MM””.</p><h3><strong>Data Cleaning:</strong></h3><p>Next, we need to clean the data. This involves removing any unwanted characters, filtering out any system messages, checking for blanks and handling missing values.</p><p>The code below converts the date column to a datetime object and extracts the year and month from the date column.</p><pre># Convert the date column to a datetime object<br>df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;], format=&#39;%d/%m/%Y&#39;)<br><br># Extract the year and month from the date column<br>df[&#39;year&#39;] = df[&#39;date&#39;].dt.year<br>df[&#39;month&#39;] = df[&#39;date&#39;].dt.month</pre><pre># Remove any unwanted characters from the message column<br>df[&#39;message&#39;] = df[&#39;message&#39;].str.replace(&#39; +&#39;, &#39; &#39;, regex=True)<br>df[&#39;message&#39;] = df[&#39;message&#39;].str.strip()<br><br># Handle missing values<br>df.dropna(subset=[&#39;message&#39;], inplace=True)</pre><p>The above code removes any unwanted characters from the message column, and drops any rows with missing values.</p><p>With the data cleaned, we can now move on to the analysis.</p><h3><strong>Exploratory Data Analysis:</strong></h3><p><strong>Most Active Users</strong></p><pre>df[&#39;user&#39;].value_counts().plot(kind = &#39;barh&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*6dByWzm7RQB0qU-W-_PFcg.png" /><figcaption>Most Active Users</figcaption></figure><p><strong>Number of Messages by hour of the day:</strong></p><pre># extract hour from time column<br>df[&#39;hour&#39;] = pd.to_datetime(df[&#39;time&#39;]).dt.hour<br><br># group by hour and count number of messages<br>hourly_counts = df.groupby(&#39;hour&#39;)[&#39;message&#39;].count()<br><br># plot results<br>plt.plot(hourly_counts.index, hourly_counts.values)<br>plt.title(&#39;Number of messages by hour of day&#39;)<br>plt.xlabel(&#39;Hour of day&#39;)<br>plt.ylabel(&#39;Number of messages&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*7HQYWd5q1mqKqwj9QRLvLg.png" /></figure><h3><strong>Sentiment Analysis:</strong></h3><p>Sentiment analysis is a natural language processing technique that involves identifying and classifying opinions and emotions expressed in a piece of text. It can be used to determine whether a particular sentiment expressed in the text is positive, negative, or neutral.</p><h3><strong>Vader:</strong></h3><p>In this project, we’ll be using <strong>vader, </strong>a model used for text sentiment analysis. Vader stands for Valence Aware Dictionary for sEntiment Reasoning, a rule-based sentiment analysis tool that uses a lexicon of words and their associated sentiment scores to determine the sentiment of a given piece of text. Vader is sensitive to both polarity (positive and negative) and intensity (strength) of emotions. It is available in the NLTK package and can be applied directly to unlabeled text data.</p><p><strong><em>So let’s apply vader to our raw whatsapp texts.</em></strong></p><p>First thing we need to do is import the nltk package and download vader lexicon using the code snippets below.</p><pre>import nltk</pre><pre>nltk.download(&#39;vader_lexicon&#39;)</pre><p>We then Import vader and create an instance of it using the code snippets below.</p><pre>#importing vader<br>from nltk.sentiment.vader import SentimentIntensityAnalyzer</pre><pre>#creating an instance of vader<br>sentiment_analyzer = SentimentIntensityAnalyzer()</pre><p>Vader sentiment intensity analyzer takes on a string and returns a dictionary of scores in four categories namely negative, positive, neutral and the compound score. The compound score is computed by normalizing the other categories as shown in the visual below.</p><p>Vader is intelligent enough to understand basic context of words, as well as capitalizations and punctuations. Let’s test that out below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*g8wXeoOv8UUuIMJ6hGTSAw.png" /></figure><p>Now let’s try to add scores and labels to our whatsapp chat dataframe. We shall be applying the polarity scores to every single message in our dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTDSuGHIRJ1JWHxBuB8koQ.png" /></figure><p>The above visual shows code snippets on how I applied polarity scores to every single message, extracted the compound scores from the dictionary in our scores column and created a new column to show sentiment of every text in the message column. The final output is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTpxfpxEAaNGvvXUbYGiGQ.png" /></figure><p><strong>Sentiment Distribution:</strong></p><pre>df[&#39;Sentiment&#39;].value_counts().plot(kind = &#39;pie&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*ZX4arlQeA9FnMUXIcZxc1g.png" /></figure><h3>Hidden Emotions:</h3><p>In this section, I’ll be identifying the most positive, neutral or negative users in the whatsap chat dataframe. To gain insights on how each user generally communicates in terms of sentiment, I started calculated the average sentiment score for each user.</p><pre>year_month = df.groupby([&#39;user&#39;,&#39;month&#39;, &#39;year&#39;]).mean().reset_index()<br>year_month</pre><p>The above code creates a variable “year_month” which groups our dataframe by user, month and year and later calculates the mean value of each group. The code also resets the index of our dataframe. This is useful for analyzing patterns and trends of sentiment scores for different users, months, and years.</p><pre>nB= year_month[year_month[&#39;user&#39;] == &#39;N B&#39;][&#39;Score&#39;].values</pre><p>The above code generates the average sentiment score for each user using the year_month variable. We do that for all the users and plot the values for the average sentiment score for all the users over time on a line chart.</p><pre>plt.figure(figsize = (20,10))<br>plt.plot(nB, label=&#39;N B&#39;)<br>plt.plot(dannie3, label=&#39;Dannie3&#39;)<br>plt.plot(oA, label=&#39;O A&#39;)<br>plt.plot(eIP, label=&#39;E I P&#39;)<br>plt.plot(Sa Ga, label=&#39;Sa Ga&#39;)<br>plt.plot(rP, label=&#39;R P&#39;)<br>plt.plot(oJ, label=&#39;O J&#39;)<br>plt.plot(shaeks, label=&#39;Sh@eks&#39;)<br>plt.plot(eE, label=&#39;E E&#39;)<br>plt.plot(dC, label=&#39;D C&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dm0DjzJ7mzisTX89F9viEQ.png" /></figure><p>The above line plot shows the average sentiment scores for each user over time.</p><h3><strong>Conclusion:</strong></h3><p>After reading this article, I am sure you have gained skills on how to perform sentiment analysis on any text data, including how to use regular expressions to extract relevant information from unstructured data, and how to perform exploratory data analysis to gain insights from the data.</p><p>By analyzing the sentiment of WhatsApp chats, individuals can gain valuable insights into the emotions and opinions of the people involved in the conversation. This can be useful in a variety of contexts, such as analyzing customer feedback, understanding employee sentiment, or monitoring public opinion. The skills gained through out this project can also be applied to a wide range of data analysis projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5edef3e1202" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleaning up a “Messi” Dataset: The FIFA 21 Data Cleaning Challenge]]></title>
            <link>https://medium.com/@danielOkia/cleaning-up-a-messi-dataset-the-fifa-21-data-cleaning-challenge-85af0df06f59?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/85af0df06f59</guid>
            <category><![CDATA[data-preparation]]></category>
            <category><![CDATA[data-wrangling]]></category>
            <category><![CDATA[data-transformation]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 14:07:41 GMT</pubDate>
            <atom:updated>2023-03-22T14:07:41.116Z</atom:updated>
            <content:encoded><![CDATA[<p>A step by step guide on how I tackled a messy dataset that needed some serious cleaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*4GoP0LfIO7qIn5GFMXaVzw.jpeg" /></figure><h3><strong>Introduction:</strong></h3><p>Welcome to the step by step FIFA 21 data cleaning challenge. In the spirit of cleaning, I have enlisted the help of none other than Lionel Messi himself, to clean up this messy dataset and turn it into a work of art.</p><p>This was a twitter data cleaning challenge that thousands of data analysts and data scientists partcicipated in.</p><p><strong>Tools and Methodology:</strong></p><p>In this data cleaning challenge, I used Python and pandas as my favorite data cleaning tools. Python, with its vast ecosystem of libraries, provides an excellent platform for data cleaning. Pandas, a library built on top of NumPy, is one of the most popular and powerful tools for data manipulation in Python.</p><p>Throughout this article, we will explore various data cleaning techniques using pandas and Python. I will provide you with code snippets and visual aids to help you understand and implement each technique effectively.</p><p>In this guided article, I won’t be going through any preparations. We will jump straight into the data cleaning process with code snippets and visuals.</p><p><strong><em>Here is a link to the dataset:</em></strong></p><p><a href="https://www.kaggle.com/datasets/stefanoleone992/fifa-21-complete-player-dataset">FIFA 21 complete player dataset</a></p><p>Lets dive right in!</p><p><strong>Dataset description:</strong></p><p>Before we describe our dataset, first thing you need to do is install and import necessary libraries. From their on, you can read your dataset into your IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*kkHSUzgZ27cyF_iCMBg2WQ.png" /></figure><p>Our dataset had a total of 18,979 rows and 77 columns. To save time, we won’t be going through the hustle of describing all the 77 columns either. I will instead be going through the messy columns that needed cleaning.</p><p><strong>Data Cleaning:</strong></p><p>Data cleaning is the most important and crucial step of any data analysis or data science project. With clean and consistent data we are able to produce high quality data that can lead to more accurate analysis, predictions and decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTx0rfWzWztG3SnjdE7ySA.png" /></figure><p>First thing you want to do is take a look at all your columns and exploring them one by one to check for any inconsistencies in the values. With the help of google, next thing I did was to rename all abbreviated columns to make good sense of the columns using the pandas .“rename ”function.</p><p><strong>Messy Columns:</strong></p><p>There were couple of messy columns and in this section, I will be going through each of the columns and how I was able to clean them up.</p><ol><li><strong>The Club Column</strong></li></ol><p>This column consists of clubs each single player belongs to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*7qU_Vh3Ja1Zk8VOCljGtbA.png" /></figure><p>We can see that the club column had row values with unwanted white spaces and characters at the beginning of the club names that we needed to get rid of.</p><pre>fifa21_V2[&#39;Club&#39;] = fifa21_V2[&#39;Club&#39;].str.strip().str.replace(&#39;\n&#39;, &#39;&#39;)<br>fifa21_V2[&#39;Club&#39;].head(20)</pre><p>The above code removes all the leading white spaces and replaces (‘\n’) with an empty string in all rows in the club column as shown in the visual above.</p><p><strong>2. The Contract Column:</strong></p><p>This column consists of player’s contract status. The start and end of their contracts, loan status or whether the player is out of contract represented by “free”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*CiOXcMmZr07TOcRv_NXz6A.png" /><figcaption>Unique Sample of Values in the contract column</figcaption></figure><p>The above visual shows some of the unique values in the contract column. To clean this column, I created two new columns to represent the start of player’s contract and the other to represent when the player’s contract will be ending. Players with (‘Jan 3, 2021 On Loan’) entries were represented as players on loan in both columns. This is because the year does not represent whether it was the start or end of their contract.</p><pre>import re<br>#defining function to represent start of contract<br><br>def contract_start_year(contract):<br>    if contract == &quot;Free&quot;:<br>        return &quot;Free&quot;<br>    elif &quot;On Loan&quot; in contract:<br>        return &quot;On Loan&quot;<br>    else:<br>        match = re.search(&#39;(\d{4})\s*&#39;, contract)<br>        if match:<br>            return match.group()<br>        else:<br>            return None<br>fifa21_V2[&#39;Contract Start Year&#39;] = fifa21_V2[&#39;Contract&#39;].apply(contract_start_year)<br><br>#defining function for end player&#39;s contract<br>def contract_end_year(contract):<br>    if contract == &quot;Free&quot;:<br>        return &quot;Free&quot;<br>    elif &quot;On Loan&quot; in contract:<br>        return &quot;On Loan&quot;<br>    else:<br>        match = re.search(&#39;\d{4}$&#39;, contract)<br>        if match:<br>            return match.group()<br>        else:<br>            return None<br><br>fifa21_V2[&#39;Contract End Year&#39;] = fifa21_V2[&#39;Contract&#39;].apply(contract_end_year)</pre><p>I used the above functions to extract the years for the start, end and contract statuses for each player. Each function first checks if the contract is “free” and returns free if it. If the value in the column contains “On Loan”, it also returns On Loan. If none of the above conditions are met, the function goes onto the regular expressions and extracts the contract start and end year. Similarly, if no match is found, the function will return none.</p><p><em>The output is shown below;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*NfsHFOPHwKrZtFXKraMHDg.png" /></figure><p><strong>3. The Height Column:</strong></p><p>This column represents the height of the players.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*5L_gfTyootferm0EIMXZ9A.png" /></figure><p>We can see that the height column had some of the values represented in feet and inches. To ensure consistency in this column, I had to make sure there was one unit of measurement by converting feet and inches to cms.</p><pre># #1 foot = 30.48cms and 1 inch = 2.54cms<br># Defining a function to convert heights to centimeters<br>def height_to_cm(height):<br>    if &#39;\&#39;&#39; in height:<br>        feet, inches = height.split(&#39;\&#39;&#39;)<br>        cm = round(int(feet) * 30.48 + int(inches.strip(&#39;&quot;&#39;)) * 2.54,2) # Converting height from feet and inches to centimeters<br><br>    else:<br>        cm = int(height.strip(&#39;cm&#39;))<br>    return cm<br><br># Apply the conversion function to the &#39;Height&#39; column<br>fifa21_V2[&#39;Height&#39;] = fifa21_V2[&#39;Height&#39;].apply(height_to_cm)</pre><p>The above code defines a function to convert values of the height column to cms. The function first checks if the values contain single quotes and if so, separates them into two parts and then converts them to centimetres. The result is rounded off to 2 decimal places.</p><p>In the next part, if the values have no single quotes, the function assumes the values are already in centimetres and only strips “cm” from the values. We finally apply the height_to_cm to our Height column in the fifa21_V2 dataframe.</p><p><strong>4. The Weight Column:</strong></p><p>This column represents the weight of the players.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*pdNkdEVtp71Rk6lyBidyWg.png" /></figure><p>We can also see that the weight column has some of its values represented in pounds(lbs). We do exactly what we did with the height column, converting lbs to kgs to ensure consistency.</p><pre># Convert weight to kg<br>def weight_to_kg(weight):<br>    if &#39;kg&#39; in weight:<br>        kg = float(weight.strip(&#39;kg&#39;))<br>    elif &#39;lbs&#39; in weight:<br>        lbs = float(weight.strip(&#39;lbs&#39;))<br>        kg = round(lbs / 2.2046,2)<br>    else:<br>        kg = float(&#39;nan&#39;)<br>    return kg<br><br>fifa21_V2[&#39;Weight&#39;] = fifa21_V2[&#39;Weight&#39;].apply(weight_to_kg)</pre><p>The above code defines a function that converts lbs to kgs.</p><p><strong>5. The IR — International Rating, Weakfoot_rating and Skill_Moves Columns:</strong></p><p>This column represented the rating of each player at international level playing for their respective countries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*tOrqQONdg-QJAzN799GEdw.png" /></figure><p>The IR column was represented by 5 star ratings as shown in the visual above. To clean this column, I got rid of the ★ symbol using the pandas replace function and replaced it with empty space. I also converted the column to a numeric data type.</p><p>I did the same for the skill_moves and weakfoot_rating columns to get rid of the ★ symbol.</p><h3><strong>6. The Load Date End Column:</strong></h3><p>This column represented the end date of a player’s Span on loan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*VKSNIiyhWgsTEZGxHXLByw.png" /></figure><p>We can see from the above visual that out of 18979 entries, only 1013 players were on Loan. I got rid of this column as 99% of its data was missing.</p><pre>fifa21_V2 = fifa21_V2.drop(&#39;Loan Date End&#39;, axis=1)</pre><h3><strong>7. Value, Wage, Hits and Release Clause columns</strong></h3><p><strong>Value </strong>— This represented the value of a player in euros</p><p><strong>Wage</strong>- This represented the weekly salary of each player in euros</p><p><strong>Release Clause</strong> — This is the value a buying club will have to pay to offload a player still on contract with the current club.</p><p><strong>Hits — </strong>This refers to the number of times the player’s profile has been viewed on the website.</p><p><strong>The Value Column:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*uom4mth3zBENVC-ndsN_QQ.png" /><figcaption>Sample of Unique values in the value column</figcaption></figure><p>The value column is represented by the price of each player in athousands and million euros as shown above.</p><pre>def value_to_numeric(value):<br>    multiplier = 1<br>    if value.endswith(&#39;M&#39;):<br>        multiplier = 1000000<br>    elif value.endswith(&#39;K&#39;):<br>        multiplier = 1000<br>    value = value.replace(&#39;€&#39;, &#39;&#39;).replace(&#39;M&#39;, &#39;&#39;).replace(&#39;K&#39;, &#39;&#39;)<br>    value = float(value) * multiplier<br>    return value<br><br>fifa21_V2[&#39;Value&#39;] = fifa21_V2[&#39;Value&#39;].apply(value_to_numeric)</pre><p>To clean this column, I got rid of the unwanted characters at the beginning and at the end of the row values for each player by replacing these characters with an empty space. Values that ended with “K” were multiplied by 1000 and those with “M” by 1000000. To make sense of the value column, I renamed the column to Value in Euros as shown below.</p><pre>fifa21_V2 = fifa21_V2.rename(columns={&#39;Value&#39;: &#39;Value (Euros)&#39;})</pre><p>I did the same for the Wage and Release Clause columns.</p><p><strong>The Hits Column:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*dxrGUORPF0WeNYBAsd9SGQ.png" /></figure><p>This column also had a few values with unwanted characters “k” at the end of some values. To clean this column, I used the pandas replace function to get rid of the “k” characters at the end of the values in the column and multiplied these values with 1000.</p><pre>def hits_to_numeric(hits):<br>    multiplier = 1<br>    hits = str(hits)<br>    if pd.isna(hits):<br>        return 0<br>    elif hits.endswith(&#39;K&#39;):<br>        multiplier = 1000<br>    hits = hits.replace(&#39;K&#39;, &#39;&#39;)<br>    hits = round(float(hits) * multiplier,2)<br>    return hits<br><br>fifa21_V2[&#39;Hits&#39;] = fifa21_V2[&#39;Hits&#39;].apply(hits_to_numeric)</pre><p>The above code defines a function that replaces the unwanted characters “k” with an empty space, multiplies these values by athousand. The function is then applied to our Hits column in our fifa21_V2 dataframe.</p><h3><strong>Conclusion:</strong></h3><p>In conclusion, the FIFA 21 Data Cleaning Challenge was a valuable exercise for anyone working with data in pandas and Python. The challenge required participants to use various string and character manipulation techniques to clean up a messy dataset containing player information.</p><p>By completing the challenge, I was able to develop my skills in data cleaning, string manipulation, and working with pandas dataframes. This challenge highlighted the importance of thorough data cleaning and how even small errors or inconsistencies can lead to inaccurate conclusions.</p><p>Overall, the FIFA 21 Data Cleaning Challenge provided a valuable learning opportunity for me and demonstrated the power of Python and pandas in managing and cleaning large datasets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85af0df06f59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Stunning Website Portfolio and Host it for Free in 2 Simple Steps]]></title>
            <link>https://medium.com/@danielOkia/create-a-stunning-website-portfolio-and-host-it-for-free-in-2-simple-steps-6e8b86bd3379?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e8b86bd3379</guid>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 06:05:44 GMT</pubDate>
            <atom:updated>2023-03-05T06:38:47.642Z</atom:updated>
            <content:encoded><![CDATA[<p>Unleash Your Creativity with Portfolio Boilerplates and jumpstart your online presence today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C-AlIxqZUVclNxRo" /><figcaption>Photo by <a href="https://unsplash.com/@clarktibbs?utm_source=medium&amp;utm_medium=referral">Clark Tibbs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are looking for a way to showcase your projects and skills to potential clients or employers, creating a website portfolio is an excellent solution! In this article, I’ll guide you through the simple steps to create a stunning website portfolio and host it for free.</p><p>In today’s digital age, having an online portfolio is crucial for showcasing your work and skills to potential clients or employers. A portfolio website allows you to present your projects, achievements, and personality in a way that sets you apart from the competition. However, building a website from scratch can be daunting and time-consuming, especially for those who are not familiar with web development. That’s where HTML5up and Github Pages come in handy. HTML5up provides a range of visually appealing and responsive templates, while Github Pages offers free hosting and easy deployment of your website.</p><p>Combining these two tools, you can create a professional and stunning portfolio website without spending a dime or wasting hours on coding.</p><p><strong>Step 1: Choose a Template from Html5up</strong></p><p>Alright, so you’re ready to create a killer portfolio website? Well, the first step is crucial — you gotta choose a template that won’t make your eyes bleed! Lucky for you, I’ve got just the solution — HTML5up. Not only is it free (Yay, more money for whatever tickles your fancy!), but the templates are so user-friendly that even someone who isn’t tech-savvy could easily navigate them.. Plus, the best part? They’re reusable and customizable, so you won’t have to start from scratch every time you need a new website.</p><p><strong><em>Trust me, it’s worth it.</em></strong></p><p>Html5up offers a wide range of beautiful and responsive templates that are perfect for creating a portfolio website. Follow these steps to choose and download a template:</p><ul><li>Visit the Html5up website and browse through the available templates.</li></ul><p><a href="https://html5up.net/">HTML5 UP</a></p><ul><li>Choose a template that suits your needs and preferences.</li><li>Click on the template to view the details and features.</li><li>Click the “Download” button to download the template.</li></ul><p>Congratulations on choosing your template! The next step is to extract the template files into a folder and open it with any text editor of your choice. Don’t be afraid to dive in and start making changes that align with your interests and style.</p><p>If you’re not familiar with coding, don’t worry! I’m here to help. Simply reach out to me and I’ll be more than happy to assist you every step of the way. Creating a portfolio website should be a fun and rewarding experience, and I’m excited to be a part of your journey!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vx4icM5ne2ausE_A" /><figcaption>Photo by <a href="https://unsplash.com/es/@goian?utm_source=medium&amp;utm_medium=referral">Ian Schneider</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Step 2: Host your Website on Github Pages</strong></p><p>Github Pages is a free hosting service that allows you to host your website on Github’s servers. Follow these steps to host your website:</p><p><a href="https://github.com/">GitHub · Change is constant. GitHub keeps you ahead. · GitHub</a></p><ul><li>Create a Github account if you don’t have one already.</li><li>Create a new repository and name it “username.github.io” where “username” is your Github username.</li><li>Upload the template files you downloaded from Html5up to your new repository.</li><li>Visit your repository’s settings and scroll down to the “Github Pages” section.</li><li>Choose the “main” branch as your source and click “Save”.</li><li>Your website is now live and can be accessed at “username.github.io”.</li></ul><p>That’s it! You now have a stunning website portfolio that is hosted for free on Github Pages. Customize the template to showcase your projects and skills, and start sharing it with potential clients, employers or even friends and colleagues.</p><h3><strong>Conclusion</strong></h3><p>Well, that’s it guys— you now have all the tools to create a killer portfolio website. Whether you want to impress potential clients or just show off to your friends, HTML5up and Github Pages have got you covered.</p><p><strong><em>Good luck, and may the coding gods be ever in your favor!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e8b86bd3379" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project-Based Learning for Data Analysts: The Fun Way to Build Skills]]></title>
            <link>https://medium.com/@danielOkia/project-based-learning-for-data-analysts-the-fun-way-to-build-skills-d17f52e561db?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d17f52e561db</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[skills-development]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 13:33:38 GMT</pubDate>
            <atom:updated>2023-03-05T06:20:30.213Z</atom:updated>
            <content:encoded><![CDATA[<p>Build Your Data Analytics Portfolio with Project-Based Learning (PBL)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0ABqMbBCEWt_43wN" /><figcaption>Photo by <a href="https://unsplash.com/@octadan?utm_source=medium&amp;utm_medium=referral">Octavian Dan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction:</strong></p><p>Are you tired of the same old methods of learning that don’t excite or inspire you? Do you want to gain new skills while enjoying the process? Look no further than project-based learning! As a self-motivated data analyst, PBL can provide you with the experience and expertise necessary to thrive in this industry.</p><p>Personally, I strongly advocate for the use of project-based learning and its effectiveness in learning data analytics. By the end of this article, I will share some useful recommendations to help you get started on your own project-based learning journey in the field of data analytics so, let’s dive into the world of PBL and discover how to build your skills in the most enjoyable way possible!</p><p>If you are a self-starter looking to break into the world of data analytics then you have to consider project-based learning (PBL) as a way to gain the skills and experience you need to succeed in this field?</p><p>PBL involves working collaboratively on a project that engages you in solving a real-world problem or answering a complex question. As a self-starter, PBL can be an effective way to gain hands-on experience, build your portfolio, and develop the skills that employers are looking for in a data analyst.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kXrgTT50jXXcxDjj" /><figcaption>Photo by <a href="https://unsplash.com/@cutinamoment?utm_source=medium&amp;utm_medium=referral">Cut in A Moment</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To embark on PBL as a self-starter, you can start by identifying a problem or question that you are passionate about and that relates to the field of data analytics. Next, gather the data you need to answer the question or solve the problem, and then start analyzing the data using the tools and techniques you have learned.</p><p>Throughout the project, it’s important to stay organized, communicate with your team (if you have one), and be open to feedback and new ideas. This will help you stay on track and ensure that you are producing quality work that meets the needs of your stakeholders.</p><p><strong>Benefits of Project-Based Learning:</strong></p><p><strong>Deeper Learning:</strong> PBL allows you to learn by doing, which leads to a deeper understanding of the subject matter. When you work on a project, you are actively engaged in the learning process, which makes it easier for you to retain the information you are learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waW8SZK5TXY8V_a0" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@edenconstantin0?utm_source=medium&amp;utm_medium=referral">Eden Constantino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Improved Critical Thinking</strong>: PBL encourages one to think critically and solve problems independently. When one works on a project, they must analyze the problem, develop a plan, and execute it. This process helps you develop your critical thinking skills and learn how to solve complex problems.</p><p><strong>Improved Collaboration</strong>: Sometimes PBL requires learners to work together in teams to complete a project. This collaboration helps them develop important social skills, such as communication, teamwork, and leadership.</p><p><strong>Real-World Connections</strong>: One of the benefits of PBL is that it helps you see the connection between what you are learning wherever and the real world. By working on projects that are relevant to your lives, you can better understand how the concepts you are learning can be applied in the real world.</p><p>The benefits of PBL for self-starters are numerous. Not only will you gain valuable skills and experience, but you will also develop a portfolio of work that you can showcase to potential employers. This can be particularly valuable for young prospects trying to enter the data analytics industry, as it demonstrates your ability to apply your skills in a real-world context.</p><h3><strong>Recommendations:</strong></h3><p>Below are some of the easily accessible and free websites I would recommend to self-starter data analysts that are looking to kick start their journey in <strong>project-based </strong>learning<strong>.</strong></p><p><strong>Kaggle</strong>: This is a popular platform for data scientists and analysts to collaborate on projects, compete in challenges, and showcase their work. Kaggle offers a variety of datasets and projects to choose from, ranging from beginner to advanced levels.</p><p>Personally, I use kaggle to download datasets.</p><p><a href="https://www.kaggle.com/">Kaggle: The World&#39;s AI Proving Ground</a></p><p><strong>TheForage</strong>.<strong>com</strong>: This is an online platform that provides real-world data analytics projects for learners to practice and showcase their skills. The platform offers a range of projects in different industries, such as finance, healthcare, and retail, allowing learners to gain experience in various domains.</p><p><a href="https://www.theforage.com/">Forage</a></p><p>From my experience, I’ve had the opportunity to work with Forage on the Accenture Data Analytics and Visualization project. This has allowed me to showcase my skills in exploratory data analysis and visualization. I must say that working with Forage is an excellent way to sharpen your data analytics skills. Currently, I am working on several other projects and excited to continue honing my skills.</p><p><strong>check out my Accenture Data Analytics and Visualization project here:</strong></p><p><a href="https://medium.com/@danielOkia/accenture-data-analytics-and-visualization-virtual-experience-cfa2c9fcc6bb">Accenture Data Analytics And Visualization Virtual Experience</a></p><p><strong>Data</strong>.<strong>gov</strong>: This is a repository of publicly available data sets that cover a wide range of topics, including climate, education, health, and transportation. Data analysts can use these datasets to develop their own projects and gain valuable experience in data cleaning, manipulation, and analysis.</p><p><a href="https://www.data.gov/">Data.gov</a></p><p><strong>UCI Machine Learning Repository</strong>: This is a collection of datasets, algorithms, and tools for machine learning and data mining research. The repository contains a variety of datasets that can be used for projects in data analytics, such as predicting customer churn or analyzing social media sentiment.</p><p><a href="https://archive.ics.uci.edu/ml/index.php">https://archive.ics.uci.edu/ml/index.php</a></p><p>These resources provide a wealth of opportunities for self-starters to gain hands-on experience in data analytics as well as data science and build their portfolios. By working on real-world projects and collaborating with other data professionals, self-starters can develop the skills and experience that employers are looking for in a competitive job market.</p><p><strong>Conclusion:</strong></p><p>If you’re a self-starter looking to break into the field of data analytics, project-based learning can be an effective way to gain the skills and experience you need to succeed. By identifying a problem or question that you are passionate about, gathering and analyzing data, and staying organized and open to feedback, you can produce quality work that demonstrates your abilities and helps you stand out in a competitive job market. And who knows, you might even have a little fun along the way!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d17f52e561db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accenture Data Analytics And Visualization Virtual Experience]]></title>
            <link>https://medium.com/@danielOkia/accenture-data-analytics-and-visualization-virtual-experience-cfa2c9fcc6bb?source=rss-d25706dd7bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfa2c9fcc6bb</guid>
            <category><![CDATA[virtual-internship]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-exploration]]></category>
            <category><![CDATA[data-insights]]></category>
            <category><![CDATA[career-development]]></category>
            <dc:creator><![CDATA[Daniel Okia]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 14:04:58 GMT</pubDate>
            <atom:updated>2023-03-09T04:21:21.132Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Unlocking the Secrets of Social Media Engagement:</strong> A Data-Driven Exploration of the Best Performing Content Categories</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPkY7eGbwaRDPmBcO-rwYg.jpeg" /></figure><p>Accenture’s Data Analytics and Visualization Virtual Experience is an interactive online program designed to provide learners with practical experience in data analytics and data visualization. Through this program, learners will have the opportunity to work on real-world data analytics projects, using popular tools like <strong>Power BI </strong>and <strong>Excel</strong>.</p><p>This is a great opportunity for individuals looking to develop their data analytics and visualization skills.</p><p>If you are a data analyst and looking to build your data analyst portfolio through project based learning or even looking to practice and showcase your skills, I would recommend theforage.com as it offers a wide range of projects in different industries.</p><p><a href="https://theforage.com/">Forage</a></p><p><strong>Project Methodology:</strong></p><p>The project was approached by first downloading and analyzing 7 datasets to determine which were relevant. The chosen datasets (Reaction.csv, Reaction Type.csv, and Content.csv) were then cleaned in Excel by removing irrelevant columns and checking for blanks and duplicates. The cleaned data was then exported to a CSV file and used for data modeling and exploratory data analysis (EDA) in Python. Adhoc and EDA were also performed in SQL to compare results with Python. Finally, the insights were visualized using Power BI for clear communication of the findings. This approach provided a comprehensive understanding of the data and helped in identifying the top-performing content categories.</p><p><strong>Project and Business Understanding: </strong>This involves understanding the problem at hand and in the Accenture Data Analytics Virtual Experience, the problem at hand required to be completed by the data analyst that was me in charge involved an In-Depth Audit of Big Data Practices and Content Category Analysis to Uncover the Top 5 Performing Categories for <strong>Social Buzz.</strong></p><p><strong>Social Buzz</strong> is a Social Media and Content creation Company. Over the past 5 years, Social Buzz has reached over 500 million active users each month. They have scaled quicker than anticipated and need the help of an advisory firm to oversee their scaling process effectively.</p><p><strong>Here are some key facts about this program:</strong></p><ul><li>You are working as a Data Analyst at Accenture.</li><li>You work within a larger team, where each member has a different role and level of responsibility.</li><li>Your team has been assigned a new project for a client called <strong>Social Buzz.</strong></li></ul><h3><strong>Brief from Social Buzz</strong></h3><p>My first task was to read the brief from Social Buzz.</p><p><strong>Link</strong>: Here is the link to the Social Buzz Brief.</p><p><a href="https://github.com/Danni3-256/Machine-Learning/blob/main/Social%20Buzz/Data_Analytics%20Client%20Brief.pdf">https://github.com/Danni3-256/Machine-Learning/blob/main/Social%20Buzz/Data_Analytics%20Client%20Brief.pdf</a></p><p><strong>Read the brief to:</strong></p><ul><li>Understand the client and business problem at hand.</li><li>Identify the requirements that need to be delivered for this project.</li><li>Identify which tasks you should focus on as a Data Analyst.</li></ul><p><strong>Gathering, Cleaning and Modelling Data: </strong>In the initial stage of the project, I downloaded 7 datasets to investigate Social Buzz’s big data practice. However, upon closer inspection, I realized that not all of the datasets were necessary for the task at hand. After carefully reviewing the data, I decided to focus on three specific tables — Reaction.csv, Reaction Type.csv, and Content.csv — which contained the relevant information needed to carry out the analysis.</p><p>The <strong>Content</strong>.<strong>csv </strong>Table contained information about social media content and had 4 columns namely:</p><ul><li><strong>Content ID</strong>: A unique identifier for each content.</li><li><strong>Content Type</strong>: The type of content, which can be either a photo or a video.</li><li><strong>Category</strong>: The category or topic of each content.</li><li><strong>URL: </strong>The link associated with the content.</li></ul><p>The <strong>Reaction Types</strong>.<strong>csv </strong>data contained information about user reactions to content, 4 columns and with each row representing a single reaction:</p><ul><li><strong>Content ID</strong>: A unique identifier for the content that the user is reacting to.</li><li><strong>Reaction Type</strong>: The type of reaction made by the user, which can be disgust, dislike, scared, or interested.</li><li><strong>Datetime</strong>: The date and time when the reaction was made.</li><li><strong>UserId: </strong>A unique identifier for the users.</li></ul><p>And Lastly the <strong>Reactions.csv </strong>table contained information about reaction types with 3 columns:</p><ul><li><strong>Type</strong>: The type of reaction, which can be heart, want, disgust, hate, or interested.</li><li><strong>Sentiment</strong>: The sentiment of the reaction, which can be positive or negative.</li><li><strong>Score</strong>: A score associated with the reaction type.</li></ul><p>After selecting the relevant datasets, I cleaned them in Excel by removing irrelevant columns like the URL column in the content.csv table and the UserId column in the Reaction.csv table. I also checked for blanks and duplicate values, particularly in the content.csv table. To ensure data quality, I deleted rows with missing values in the Reaction.csv table. These steps were necessary to prepare the data for analysis and ensure that our results were accurate and reliable.</p><p><strong>Data Modeling With Python:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj_WejUqEpFUVUMbkEttxQ.png" /><figcaption>Reading content Data set and Importing necessary libraries</figcaption></figure><p>This code reads the ‘Content.csv’ file and creates a pandas dataframe called ‘content’. The .head(5) function is then used to display the first five rows of the dataframe to give an idea of the data structure and content. We do the same for the other files, reaction.csv and reaction types.csv files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdN5_Fv1j4dtoVH50Ksrng.png" /><figcaption>Renaming Column</figcaption></figure><p>In data modeling, I started by merging the three cleaned datasets in Python using a common key, the ContentId column, which was present in all three datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FP7CZgnRijOgkMhIw7RsLg.png" /><figcaption>Merging Datasets</figcaption></figure><p>After cleaning and merging the relevant datasets in Excel, I selected relevant columns necessary for me to complete this project.</p><pre>final_data = final_data.loc[:, [&#39;Content ID&#39;, &#39;Content Type&#39;, &#39;Category&#39;,&#39;Type&#39;,&#39;Datetime&#39;,&#39;Sentiment&#39;,&#39;Score&#39;]]<br>final_data.head()</pre><p>This code selects a subset of columns from the final_data dataframe, which includes only the columns for Content ID, Content Type, Category, Type, Datetime, Sentiment, and Score. The loc function is used to locate the rows and columns by label, and the [:, ...] syntax is used to select all rows and the specified columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yphEi_yrXWSee7wF3Obi1A.png" /></figure><p>I then exported the resultant dataset to my local machine in CSV format.</p><pre>final_data.to_csv(&#39;clean_data.csv&#39;, index=False)</pre><p>This line of code exports the final cleaned and merged dataset as a CSV file named “clean_data.csv” to the current working directory.</p><p>This was done to prepare the dataset for further analysis through adhoc and exploratory data analysis in SQL Server Management Studio (SSMS). This step was necessary to gain insights into the data and identify patterns and trends that could inform future decision-making.</p><p>I also performed EDA in Python to draw insights. I will be using this to compare with the results generated from performing AdHoc and EDA in SSMS using SQL. Some of the questions I answered include;</p><p><strong>Exploratory Data Analysis in Python:</strong></p><ul><li><strong>Which content type received the most reactions?</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*MwjchP2ZwoUBEuFAOd0NSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*OVrOxsFm_6R3cEqtoaUFww.png" /></figure><p><strong>. What Were The Top 5 Categories</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*eX_4-OpA25dK-Ai6ir_hIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*8UX3VPFL-p4tuiSHG6nyCw.png" /></figure><p><strong>Sentiment Distribution:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*4ZswPoLqu309Q65Sb7Y2QQ.png" /><figcaption>Sentiment Distribution</figcaption></figure><p><strong>Trends and Distributions over time:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*1inhO1La_vaAtw-UGQWwhw.png" /><figcaption>Monthly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*zsTsL7m_mNjq4pWDCSbfZw.png" /><figcaption>Yearly</figcaption></figure><p><strong>Data Analysis and Insights: </strong>Data Analysis and Insights involve exploring and examining the data set to uncover patterns, relationships, and trends that can provide valuable insights into the problem at hand. In this stage, I used SQL queries to perform exploratory data analysis and generate insights from the merged and cleaned data set.</p><p>These insights provided a better understanding of Social Buzz’s big data practice and helped to identify areas for improvement. The results of the analysis were visualized using various charts and graphs such as line charts, histograms, and pie charts.</p><p><strong>EDA and AdHoc Analysis with SQL:</strong></p><p>Get ready to meet SQL, the powerful and sophisticated detective that can help you unveil hidden insights from your data! With SQL.</p><p>To get started with SQL Server Management Studio(SSMS), I followed these steps:</p><ul><li><strong>Connecting to a Server:</strong> Open SSMS and click on “Connect” to open the “Connect to Server” window. Enter the server name, authentication type, and login credentials to connect to the server.</li><li><strong>Importing Flat Files:</strong> Right-click on the database in the Object Explorer and select “Tasks” -&gt; “Import Flat File” to import the flat file. Follow the Import Wizard to specify the source file, destination table, and column mappings.</li><li><strong>Running Queries</strong>: Open a new query window by clicking on “New Query” in the toolbar or by pressing Ctrl+N. Write a SQL query in the query editor window and execute it by clicking on “Execute” in the toolbar or by pressing F5.</li></ul><p><strong>Link to EDA with SSMS in SQL:</strong></p><p><a href="https://github.com/Danni3-256/Machine-Learning/blob/main/Social%20Buzz/social%20Buzz%20EDA.sql">https://github.com/Danni3-256/Machine-Learning/blob/main/Social%20Buzz/social%20Buzz%20EDA.sql</a></p><p><strong>Which content type received the most reactions?</strong></p><pre>SELECT Content_Type, COUNT(Type) AS Count<br>  FROM [socialBuzz_dbase].[dbo].[social_buzz ]<br>  GROUP BY Content_Type<br>  ORDER BY 2 DESC  -- Photos are dominating</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*P9aCa46gW88JrQZcoVOj3w.png" /></figure><blockquote>Just as we saw from our EDA with Python, Content type “Photo “ received the most reactions.</blockquote><p><strong>What Were The Top 5 Categories:</strong></p><pre>-- #What is the most popular Category<br>SELECT Category, COUNT(Category) AS [Category Count]<br>  FROM [socialBuzz_dbase].[dbo].[social_buzz ]<br>  GROUP BY Category<br>  ORDER BY 2 DESC   </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*_o7UO6B7SH0lmqChrGNg8w.png" /></figure><p>We can see that the results of the Top 5 categories from SQL do not match those from Python and they are slightly different as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*eX_4-OpA25dK-Ai6ir_hIQ.png" /></figure><p>If the top 5 categories obtained from Python do not match those obtained from SQL, it could be due to several reasons such as differences in data cleaning and preparation methods, variations in SQL query syntax, or even different versions of software used.</p><p><strong>Results from Power BI:</strong></p><p>Link to my social Buzz report in pdf format.</p><p><a href="https://github.com/Danni3-256/Machine-Learning/blob/main/Social%20Buzz/Social%20Buzz%20Report.pdf">https://github.com/Danni3-256/Machine-Learning/blob/main/Social%20Buzz/Social%20Buzz%20Report.pdf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*TRZSusUxdNj4wawPLFPpvQ.png" /></figure><p>We can see that our Top 5 categories from Power BI and SQL are the same match. It is important to thoroughly investigate and understand the reasons for such discrepancies to ensure accurate and reliable results. This is why conducting EDA and AdHoc Analysis with both Python and SQL can provide a more comprehensive understanding of the data and help to identify any potential issues or inconsistencies.</p><p><strong>Sentiment Distribution :</strong></p><pre>SELECT Sentiment, COUNT(sentiment) As Count<br>  FROM [socialBuzz_dbase].[dbo].[social_buzz ]<br>  GROUP BY Sentiment<br>  ORDER BY 2 DESC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*Nd7Yh5OieTsOx1yTef6Xmw.png" /></figure><p><strong>Trends and Distribution for Year and Month:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*E2VhhNieQI5E98i33Y3zxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*NXrLYqGip1WLSZ-oWfsIYQ.png" /></figure><h3><strong>Conclusion:</strong></h3><p>In conclusion, this project has explored social media engagement by analyzing the best-performing content categories on a given platform. Through data cleaning and preparation in Excel, data modeling and exploratory data analysis with Python and SQL, and visualization with Power BI, I identified the top-performing content categories and their trends over time.</p><p>The insights gained from this analysis can be used to inform content creation strategies and improve engagement on social media platforms. Additionally, the discrepancies found between the results from Python and SQL highlight the importance of thorough data exploration and the potential for inconsistencies in different analytical tools. Overall, this project demonstrates the power of data analytics in uncovering insights and driving informed decision-making.</p><h3><strong>Github Repository:</strong></h3><p>All the work, data sets, SQL code, Python and Power BI report for the project “Unlocking the Secrets of Social Media Engagement: A Data-Driven Exploration of the Best Performing Content Categories” can be found in the link to my GitHub repository below.</p><p><a href="https://github.com/Danni3-256/Machine-Learning/tree/main/Social%20Buzz">https://github.com/Danni3-256/Machine-Learning/tree/main/Social%20Buzz</a></p><p>You can access all the files in their original format as well as in PDF format for easy viewing and sharing. The repository is organized in a clear and concise manner, making it easy to navigate and find the specific files you are interested in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfa2c9fcc6bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>