<?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 Riri on Medium]]></title>
        <description><![CDATA[Stories by Riri on Medium]]></description>
        <link>https://medium.com/@jamesriri?source=rss-376641da0201------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JldsSuI0jKyRnMDR0Xrbcg.jpeg</url>
            <title>Stories by Riri on Medium</title>
            <link>https://medium.com/@jamesriri?source=rss-376641da0201------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:48:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jamesriri/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[Unfolding a Machine Learning Classification Problem: A Step by Step Guide.]]></title>
            <link>https://jamesriri.medium.com/machine-learning-classification-problem-step-by-step-guide-c0b5241c495c?source=rss-376641da0201------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0b5241c495c</guid>
            <category><![CDATA[classification-models]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[titanic-dataset]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Riri]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 18:03:38 GMT</pubDate>
            <atom:updated>2023-05-03T12:33:33.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeQhYrSC-NpK9fJFUO2nPA.jpeg" /></figure><p>A classification problem in machine learning involves forecasting the class or category of an input sample based on its features or attributes. For instance, you want to build a machine learning model that can be able to distinguish a cat from a dog, the goal of this model will be to accurately predict the classes of new and unseen images of cats and dogs and assign each image its respective class. As such, this problem is classified as a classification problem.</p><p>Similar to other machine learning tasks, building a classification model involves a number of steps to achieve its primary objective. These steps include collecting and preprocessing the data, dividing it into training and testing sets, selecting a suitable model, training the model on the data, evaluating the performance of the model, optimizing the model, and finally deploying it in real-world applications such as web services, mobile apps, or APIs.</p><p>Some common applications of machine learning classification that you’ve probably interacted with include spam detection which I’ve just mentioned above, sentiment analysis, fraud detection, image classification, and medical diagnosis. This shows the classification technique have a wide pool of practical applications across various domains.</p><h4>Types of Classification Approaches.</h4><p>There exists three MAIN types of classification approaches, they include:</p><ul><li><em>Binary Classification:</em></li></ul><p>In binary classification, the goal is to classify instances into one of two classes or categories.These classes are assigned class labels — either 0 or 1. Class label 0 is mostly associated with the “normal state” of the category and vice versa.</p><p>Examples include a classifier determining if an email is spam or not, or if a person has a disease or not.</p><p>Some popular algorithms used in this type of classification problem include SGD classifier (very powerful esp when handling large datasets), K-Nearest Neighbors, and SVM.</p><ul><li><em>Multi-class Classification:</em></li></ul><p>In multiclass classification (also called multinomial classification), the goal is to classify instances into one of several possible classes or categories.</p><p>Examples include classifying images of animals into different types of species, or classifying news articles into different topics.</p><p>Random Forest and Naive Bayes classifiers usually perfom exceptionally well in this scenario. However, some binary classifiers such as SVM and Linear classifiers can also be used but in such a case, two strategies are used to train the classifier; either <em>One-Versus-All </em>or <em>One-Versus-One.</em></p><ul><li><em>Multi-label Classification:</em></li></ul><p><em>O</em>n the other hand we have multi-label classification, whereby the goal is to assign one or more labels to each instance. This is different from multiclass classification, where each instance is assigned to only one class.</p><p>Examples include tagging documents with relevant keywords, or classifying images with multiple labels such as “sunset,” “beach,” and “ocean”.</p><p>A common application of this is the face-recognition classifier which attaches a single tag per person in an image containing a number of people.</p><h3>End-End Classification Task.</h3><p>In this section, we will focus on the core of machine learning and build classification models using the Titanic dataset which can be found on this <a href="https://www.kaggle.com/c/titanic">Kaggle competition</a>. The optimal goal is to predict whether or not a passenger survived the infamous 1912 ship disaster based on various features such as age, sex, class, and so on.</p><p>Let&#39;s roll.</p><p><strong>Loading dependencies and downloading the dataset.</strong></p><p>For the specific purpose of this article, we&#39;ll be using the sklearn library so let’s go ahead and import all the necessary tools that we will be using, but before that make sure you’ve downloaded and unzipped the dataset.</p><pre>%matplotlib inline<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import pandas as pd<br>import numpy as np<br><br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.svm import SVC<br>from xgboost import XGBClassifier<br>from sklearn.neural_network import MLPClassifier<br>from sklearn.model_selection import cross_val_score<br>from sklearn.pipeline import Pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder<br>from sklearn.compose import ColumnTransformer</pre><p>All that is left is to load the dataset, let’s go ahead and do that.</p><pre>train=pd.read_csv(&quot;titanic/train.csv&quot;)<br>test=pd.read_csv(&quot;titanic/test.csv&quot;)<br><br>print(f&quot;Train Dataset shape: {train.shape}\n\nTest Dataset shape: {test.shape}&quot;)</pre><p>Now that we’ve stored both train and and test .csv files into a pandas dataframe we can print the shape of both dataframes.</p><ul><li>The train dataframe have 891 samples and 12 features, on the other hand the test dataframe have 418 samples and 11 features. The train dataframe have an additional feature which we will use it as our target class.</li></ul><p>Let’s display the first five rows both for trainand test .</p><pre>train.head()<br><br>test.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*290LAH9-N3Xea2AtSdx3ww.png" /><figcaption>Train and Test Dataframe.</figcaption></figure><h4>Data Analysis and EDA.</h4><p>To make things easier, let&#39;s join both the train and test dataframes to create a single dataset.</p><pre>dataset=pd.concat(objs=[train, test], axis=0)<br>dataset=dataset.set_index(&quot;PassengerId&quot;)</pre><ul><li>The set_index method is called on dataset to set the index column as &quot;PassengerId&quot;.</li></ul><blockquote>It is important to note that test dataset should not be used in this way during training, as it is meant to be used as a separate dataset to evaluate the performance of the trained model on unseen data. In practice, we should not include the test data in the training dataset, and instead only use it for testing and evaluation purposes.</blockquote><p>Let’s display the first and the last few rows of the concatenated dataset.</p><pre>dataset.head()<br><br>dataset.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*nP57LCF8sfdVathGtXa8hQ.png" /><figcaption>Concatenated Dataset.</figcaption></figure><p>Let’s familiarize ourselves with the kind of dataset we’re working with.</p><pre>dataset.info()</pre><ul><li>From the output, the dataset has 1309 entries and 11 columns — 3 columns are of type float, 3 columns are of type integer, and 5 columns are categorical columns of type object. Some of the columns have missing values. The Survived column has only 891 non-null values, which means that there are missing values in this column for the test set but keep in mind that this column was not present in the test dataset, and so we won&#39;t fill these missing values.</li></ul><h4><strong>About the features.</strong></h4><p>The column attributes have the following meaning:</p><ul><li><strong>PassengerId</strong>: a unique identifier for each passenger.</li><li><strong>Survived</strong>: that’s the target, 0 means the passenger did not survive, while 1 means he/she survived.</li><li><strong>Pclass</strong>: passenger class.</li><li><strong>Name</strong>, <strong>Sex</strong>, <strong>Age</strong>: Self-explanatory.</li><li><strong>SibSp</strong>: how many siblings and spouses of the passenger aboard the Titanic.</li><li><strong>Parch</strong>: how many children &amp; parents of the passenger aboard the Titanic.</li><li><strong>Ticket</strong>: ticket id.</li><li><strong>Fare</strong>: price paid (in pounds).</li><li><strong>Cabin</strong>: passenger’s cabin number.</li><li><strong>Embarked</strong>: where the passenger embarked the Titanic.</li></ul><p>Next Up: statistical summary.</p><pre>dataset.describe().T</pre><p>This will provide the statistical summary of the numerical columns in the dataset. The .T function transposes the table to make it more readable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*9XaWaDn7SPorU5thPcdiVg.png" /><figcaption>Statistical Summary.</figcaption></figure><ul><li>The mean age was 29.88, and the oldest person was 80 yrs.</li><li>The mean fare was 33.30 pounds.</li><li>The survival rate was only 38%, quite sad 😢 .</li></ul><h4>Visualizations.</h4><p>Let’s now visualize the distribution of some key features.</p><pre>#Target class<br>sns.set(style=&quot;white&quot;, color_codes=True)<br>ax=sns.catplot(&quot;Survived&quot;, data=dataset, kind=&quot;count&quot;, hue=&quot;Sex&quot;, height=5)<br>plt.title(&quot;Survival Distribution&quot;, weight=&quot;bold&quot;)<br>plt.xlabel(&quot;Survival&quot;, weight=&quot;bold&quot;, size=14)<br>plt.ylabel(&quot;Head Count&quot;, size=14)<br>ax.set_xticklabels([&quot;Survived&quot;, &quot;Didn&#39;t Survive&quot;], rotation=0)<br>plt.show(); </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*nFA6LWjpl1wKWgXLhBCHMA.png" /><figcaption>Survival by Gender.</figcaption></figure><ul><li>From the generated categorical plot, we can see most men survived as compared to those who didn&#39;t. On the other hand, most women/female didn’t survive as compared to those who survived. This is quite an interesting visual.</li></ul><p>Let’s continue uncovering these relationships:</p><pre>sns.set(style=&quot;white&quot;, color_codes=True)<br>ax=sns.catplot(&quot;Survived&quot;, data=dataset, kind=&quot;count&quot;, hue=&quot;Embarked&quot;, height=5)<br>plt.title(&quot;Survival Distribution by boarding Place&quot;, weight=&quot;bold&quot;)<br>plt.xlabel(&quot;Survival&quot;, weight=&quot;bold&quot;, size=14)<br>plt.ylabel(&quot;Head Count&quot;, size=14)<br>ax.set_xticklabels([&quot;Survived&quot;, &quot;Didn&#39;t Survive&quot;], rotation=0)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*pQ8HbWT48qRFklemgTgwwQ.png" /><figcaption>Survival by place of boarding.</figcaption></figure><p>The Embarked column in this dataset indicates the port of embarkation of each passenger. The values represents:</p><ul><li>C: Cherbourg</li><li>Q: Queenstown</li><li>S: Southampton</li></ul><p>Interestingly, the survival rate of those who embarked the ship at Southampton was way more higher as compared to the rest.</p><p>Let’s look at a few more:</p><pre>sns.set(style=&quot;white&quot;, color_codes=True)<br>ax=sns.catplot(&quot;Survived&quot;, data=dataset, kind=&quot;count&quot;, hue=&quot;Pclass&quot;, height=5)<br>plt.title(&quot;Survival Distribution by Passenger Class&quot;, weight=&quot;bold&quot;)<br>plt.xlabel(&quot;Survival&quot;, weight=&quot;bold&quot;, size=14)<br>plt.ylabel(&quot;Head Count&quot;, size=14)<br>ax.set_xticklabels([&quot;Survived&quot;, &quot;Didn&#39;t Survive&quot;], rotation=0)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*gf4oktD7ZUqJdpZb-vwpnQ.png" /><figcaption>Survival by Passenger Class.</figcaption></figure><ul><li>If a passenger happened to be in the 3rd class, the chances were higher that he/she would survive the incident. Paradoxically, most people who were in the first class didn’t survive compared to those who survived in both 1st and 2nd classes.</li></ul><p>To further understand the distribution of the survival outcomes, let’s create a new colum age_dec that bins the Age column into decades.</p><pre> dataset[&#39;age_dec&#39;]=dataset.Age.map(lambda Age:10*(Age//10))<br><br>sns.set(style=&quot;white&quot;, color_codes=True)<br>ax=sns.catplot(&quot;Survived&quot;, data=dataset, kind=&quot;count&quot;, hue=&quot;age_dec&quot;, height=5)<br>plt.title(&quot;Survival Distribution by Age Decade&quot;, weight=&quot;bold&quot;)<br>plt.xlabel(&quot;Survival&quot;, weight=&quot;bold&quot;, size=14)<br>plt.ylabel(&quot;Head Count&quot;, size=14)<br>ax.set_xticklabels([&quot;Survived&quot;, &quot;Didn&#39;t Survive&quot;], rotation=0)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*Mrl9HBALpaTu6_QUYpJnfw.png" /><figcaption>Survival by age decade.</figcaption></figure><ul><li>The plot shows that passengers in their 20s and 30s had the highest survival rate, while those in their 1s and 60s had the lowest.</li></ul><p>Finally, let&#39;s create a violin plot that shows the distribution of passengers by age decade and passenger class, with the hue representing the passenger’s sex.</p><pre>sns.violinplot(x=&quot;age_dec&quot;, y=&quot;Pclass&quot;, hue=&quot;Sex&quot;,data=dataset,<br>               split=True, inner=&#39;quartile&#39;,<br>               palette=[&#39;lightpink&#39;, &#39;lightblue&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*qV0KC_faFXiGa5Qy3pp1Uw.png" /></figure><ul><li>The plot shows the distribution of passenger ages by decade and class, with the violins representing the density of passengers at different ages. The split violins allow for easy comparison of the distributions for male and female passengers within each age and class group.</li></ul><h4>Preprocessing.</h4><p>Time to preprocess the data before feeding it into our models. But first, how many missing values do we have? and while we’re at it, let’s create a pandas dataframe containing the percentages of the missing values of each column.</p><pre>dataset.isnull().sum()<br><br>#percentage missing<br>p_missing= dataset.isnull().sum()*100/len(dataset)<br>missing=pd.DataFrame({&quot;columns &quot;:dataset.columns,<br>                     &quot;Missing Percentage&quot;: p_missing})<br>missing.reset_index(drop=True, inplace=True)<br>missing</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*NrnR2CBAIU2hhgoD5uubPQ.png" /><figcaption>Missing Values.</figcaption></figure><ul><li>About 20% is missing both in Age and age_dec columns, the Cabin column have 77% of its values missing.</li></ul><p>Next we need to identify which columns we will be dropping, and then split the columns into numerical and categorical columns.</p><pre>col_drop=[&#39;Name&#39;,&#39;Ticket&#39;, &#39;Cabin&#39;]<br>print(f&quot;Dataset shape before dropping: {dataset.shape}&quot;)<br>dataset=dataset.drop(columns=col_drop)<br>print(f&quot;Dataset shape after dropping: {dataset.shape}&quot;)<br><br>#Numerical and Categorical columns<br>cat=[col for col in dataset.select_dtypes(&#39;object&#39;).columns]<br>num=[col for col in dataset.select_dtypes(&#39;int&#39;, &#39;float&#39;).columns if col not in [&#39;Survived&#39;]]<br>print(cat)<br>print(num)</pre><ul><li>The code is dropping the Name, Ticket, and Cabin columns from the dataset DataFrame, and then creating two lists cat and num.</li><li>cat list contains the names of categorical columns in the dataset which are of object datatype while num list contains the names of numerical columns which are of int and float datatype except Survived column which is our target feature.</li></ul><p><strong>Split the dataset.</strong></p><pre>train=dataset[:891]<br>test=dataset[891:].drop(&quot;Survived&quot;, axis=1)<br></pre><ul><li>The train dataframe contains the first 891 rows of the original dataset, which corresponds to the training data for the Titanic survival prediction problem. The test dataframe contains the remaining rows of the original dataset, which corresponds to the test data for the problem. The Survived column is dropped from the test dataframe because this is the target variable that we are trying to predict, and it is not present in the test data.</li></ul><h4>Transformation Pipelines.</h4><p>To prepare the data for machine learning algorithms, we need to convert the data into a format that can be processed by these algorithms. One important aspect of this is to transform categorical data into numerical data, and to fill in any missing values in the data. To automate these tasks, we can create data pipelines that perform these operations for us. These pipelines will help to transform our data into a format that can be used by machine learning algorithms.</p><pre>num_pipeline=Pipeline([<br>    (&quot;imputer&quot;, SimpleImputer(strategy=&quot;median&quot;)),<br>    (&quot;scaler&quot;, StandardScaler())<br>])<br><br>cat_pipeline=Pipeline([<br>    (&quot;imputer&quot;, SimpleImputer(strategy=&quot;most_frequent&quot;)),<br>    (&quot;encoder&quot;, OneHotEncoder())<br>])<br><br>full_pipeline=ColumnTransformer([<br>    (&quot;cat&quot;, cat_pipeline, cat),<br>    (&quot;num&quot;, num_pipeline, num)<br>])</pre><ul><li>The num_pipeline first applies a SimpleImputer to fill in missing values with the median value of the column, and then standardizes the data using StandardScaler(). The cat_pipeline applies a SimpleImputer to fill in missing values with the most frequent value of the column, and then encodes the categorical variables using OneHotEncoder().</li><li>The ColumnTransformer is then used to apply these pipelines to the respective columns in the dataset. The cat and num lists created earlier are used to specify which columns belong to each pipeline.</li></ul><pre># Transform the train dataset<br>X_train = full_pipeline.fit_transform(train[cat+num])<br>X_train</pre><ul><li>The code above applies the full_pipeline ColumnTransformer to the concatenated train dataset (train[cat+num]) that contains both categorical (cat) and numerical (num) columns. The output is a Numpy array that contains the transformed features.</li></ul><p>Let’s now use the fitted full_pipeline to transform the test set.</p><pre>X_test=full_pipeline.transform(test[cat+num])<br>X_test</pre><p>By calling the transformmethod, the same transformations that were applied to the training data are applied to the test data. The resulting transformed test data X_test is what we will use as an input to our trained model to make predictions.</p><blockquote>Note: The full_pipeline object SHOULD only be fitted to the training data to avoid data leakage.</blockquote><p>Identify the target class.</p><pre>y_train=train[&quot;Survived&quot;]</pre><h3>Classification Models.</h3><ul><li><strong>Random Forest Classifier.</strong></li></ul><pre>rf=RandomForestClassifier(n_estimators=200, random_state=42)<br>rf.fit(X_train, y_train )<br>y_pred=rf.predict(X_test)<br><br>scores=cross_val_score(rf, X_train, y_train, cv=20)<br>scores.mean()</pre><ul><li>The above code fits the random forest classifier to the training dataset and predicts the target variable for the test dataset, later it performs 20-fold cross-validation on the training dataset by taking the random forest classifier, the predictor variables X_train, the target variable y_train, and the cv=20 parameter. It returns the accuracy score for each fold. scores.mean() returns the mean accuracy score across all the folds.</li></ul><p>Wow, the model performed amazingly — 80.01% is quite a satisfying performance considering this is our first run.</p><ul><li><strong>XGBoost Classifier.</strong></li></ul><p>Let’s try out a gradient boosting classifier and see how well it performs.</p><pre>model = XGBClassifier(<br>    n_estimators=100,<br>    max_depth=8,<br>    n_jobs=-1,<br>    random_state=42<br>)<br><br>model.fit(X_train, y_train)<br>y_pred=model.predict(X_test)<br><br>scores=cross_val_score(model, X_train, y_train, cv=20)<br>scores.mean()</pre><ul><li>Not bad, 79% is somehow better — remember this is our first time executing these models and we’re doing so without any feature engineering or hypeparameter tuning techniques.</li></ul><p>Let’s try two more extra models; a support vector one and a neural-network one to see if our performance improves.</p><ul><li><strong>Support Vector Machine.</strong></li></ul><pre>svm=SVC(gamma=&quot;auto&quot;)<br>svm.fit(X_train, y_train)<br>y_pred=svm.predict(X_test)<br><br>scores=cross_val_score(svm, X_train,y_train, cv=20)<br>scores.mean()</pre><p>Hooray!!! our perfomace just impoved by 1%, now we’re at 81% — it might seem subtle but it’s quite a massive win considering the kind of task we’re handling.</p><p>This model seems promising and would be highly recommend for further development.</p><ul><li><strong>Multi-Layer Perceptron Classifier.</strong></li></ul><p>Lastly, let’s create a neural network classifier to tackle the problem. MLPC classifier is a neural network algorithm mostly used for classification tasks.</p><pre>nn=MLPClassifier(hidden_layer_sizes=(20,15,25))<br>nn.fit(X_train, y_train)<br>nn.predict(X_test)<br><br>scores=cross_val_score(nn, X_train, y_train, cv=15)<br>scores.mean()</pre><ul><li>Not disappointing, the model gave us an 80.15% perfomance.</li></ul><p>Overall, our models performed better with an average score of 80%.</p><p><em>PS: Your scores might be different from those herein but that&#39;s not something to worry about.</em></p><blockquote>Fun Fact: Looking at the <a href="https://www.kaggle.com/c/titanic/leaderboard">leaderboard</a> for the Titanic competition on Kaggle, our scores would’ve been among the top 3%, ain’t that not mind-blowing?.🤩😎.</blockquote><blockquote>But wueh, some kagglers achieved 100% score, yeah you heard me right, 100%…that’s nuts, special respect to all of them. 👏</blockquote><p>Tips to Improve performance:</p><ul><li><em>Hyperparameters tuning using GridSearch and Cross validation.</em></li><li><em>Feature Engineering, eg, try to add some attributes such as </em><em>SibSP and </em><em>Parch .</em></li><li><em>Identify parts of names that correlate well with the </em><strong><em>Survived</em></strong><em> attribute.</em></li></ul><p>And with that, we’re done with our classification model development. Let&#39;s connect on <a href="https://www.linkedin.com/in/riri-njaramba/"><em>LinkedIn</em></a> and <a href="https://twitter.com/icy_riri"><em>Twitter</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0b5241c495c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Detection and Classification: A Brief Deep Learning and CNN Overview.]]></title>
            <link>https://jamesriri.medium.com/object-detection-and-classification-a-brief-deep-learning-and-cnn-overview-37569325332b?source=rss-376641da0201------2</link>
            <guid isPermaLink="false">https://medium.com/p/37569325332b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <dc:creator><![CDATA[Riri]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 20:53:21 GMT</pubDate>
            <atom:updated>2023-04-12T05:12:37.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*e9OO4DcvZMX6A1cq.jpg" /></figure><p>Object Detection is quite a melodic term that always catches my attention whenever it’s mentioned. I remember the first time I encountered the term I had no clue what it entails so I had to do a quick Google search to know the exact meaning of the term, and just from that simple Google search, I knew the concept would become my favorite area of interest, and true to my words here I am, five years later, writing my first-ever article on Object Detection.</p><p>In this article, I’ll be discussing the basic Object Detection concept and it’s my hope you’ll get something valuable out of it.</p><h4>What is Object Detection?</h4><p>Object detection is a technique used in the wider concept of computer vision to identify objects within an image. Whenever an object detection algorithm identifies an object in an image, a bounding box is drawn around that particular object, and the respective class is assigned to the object.</p><p>The power of object detection can be leveraged in several diverse use cases which include but not limited to: -</p><ul><li>Healthcare.</li><li>Autonomous mobility.</li><li>Video surveillance and Drone technology.</li><li>Agriculture…etc.</li></ul><p>Often, Object Detection is confused with other techniques such as image classification, object localization, object recognition, and object segmentation. Let’s differentiate these four computer vision tasks from Object detection.</p><p><em>Image Classification: You have an image that has 3 goats in it, an image classification algorithm will identify this image as one “goat image” so it will assign the class “goat” to that particular image, on the other hand, an object detection algorithm will identify 3 goats (objects) in that image.</em></p><p><em>Object Localization: There’s a very thin line between object localization and detection. Object localization identifies the location of an object in an image and draws a bounding box around it, whereas Object detection identifies the location of the object, draws a bounding box around it, and then identifies the classes of each object.</em></p><p><em>Object Recognition: The difference is subtle yet very evident. Object recognition is a technique that identifies the presence of objects in an image. Object detection is a subset of Object Recognition.</em></p><p><em>Object Segmentation: Also referred to as Semantic Segmentation, it highlights the identified objects in an image using specific pixels instead of coarse bounding boxes.</em></p><p>By now I’m assuming you’ve grabbed something about our topic subject, let’s now dig an inch deeper.</p><h4>Deep Learning and Convolutional Neural Networks.</h4><p>Deep Learning is just like any other machine learning technique but the uniqueness of this technique is the fact that it uses Artificial Neural Networks (ANNs). It’s quite a complex yet very efficient technique compared to the other simpler machine learning techniques.</p><p>A neural network mimics the complex human brain that uses a network of neurons to process information. A neural net is made up of an input layer, one or more hidden layers, and an output layer. A convolutional neural network or just CNN also referred to as ConvNet is a feed-forward neural network that is mostly used in object detection due to its excellent performance with image inputs. It’s made up of three main layers: -</p><ul><li>Convolutional layer.</li><li>Pooling layer.</li><li>Fully connected layer.</li></ul><p>Check out this <a href="https://www.superannotate.com/blog/guide-to-convolutional-neural-networks">blog</a> for more detailed information about these layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*WCgG-iO9dtwew7rf78ovHQ.png" /><figcaption>A feed-forward neural net.</figcaption></figure><h4>Object Detection with Deep learning models.</h4><p>There exist several deep learning techniques which we will discuss in this part. They are classified into two main groups; the R-CNN Family and the YOLO family.</p><p><strong>R-CNN model Family.</strong></p><p>The R-CNN family models belong to the Multi-stage Object Recognition Neural Network Architecture which as the name suggests, involves two separate stages; first, the model starts by extracting/ identifying key “Regions of Interest” (ROI) in an image through the use of bounding boxes, later, it assigns classes to these regions to obtain the final output and thus the name Region-Based Convolutional Neural Networks (R-CNN).</p><p>This family includes three respective object recognition and localization techniques: -</p><p>i. R-CNN.</p><p>ii. Fast R-CNN.</p><p>iii. Faster R-CNN.</p><p>Let’s have a close-up of each one of them.</p><h4>R-CNN</h4><p>Developed in 2014 making it the first member of the R-CNN family. Its successful application to the problem of object localization, detection, and segmentation was by then one of a kind. The model is comprised of the following modules:</p><p><strong><em>i. Region Proposal</em></strong></p><p>Involves extracting independent regions from an image/video by using a selective search algorithm for object recognition. It works by applying a segmentation algorithm to an image to find blobs, later, it combines all extracted regions into one big region to make up 2,000 areas which are up for an “investigation” to find out which ones are objects and which ones aren’t.</p><p>ii <strong><em>Feature Extractor</em></strong></p><p>This module involves using a Convolutional Neural Network to extract features from each independent region identified in the previous module.</p><p><strong><em>iii. Classifier</em></strong></p><p>Using an SVM classifier and a bounding box regressor, the model classifies the features identified in the preceding module into their respective classes.</p><blockquote>The downside of this approach is that it’s very slow.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Fd1aKgpl4nz5LyVaubKYOg.png" /><figcaption>Architechture of a R-CNN model.</figcaption></figure><h4>Fast R-CNN.</h4><p>An improved version of R-CNN which seeks to alleviate the limitations of the R-CNN Model. This approach uses the structure of R-CNN alongside SPPnets (Spatial Pyramid Pooling networks.), a speed-up technique, to make the slower R-CNN model faster.</p><p>The “RoI pooling layer” which was introduced in Fast R-CNN, provides the corresponding features for each region in an image, this is after taking in the CNN feature maps and Region of interest for the image. This “innovation” significantly improved the performance of the Fast R-CNN model in comparison to R-CNN.</p><p>Although Fast R-CNN performed better at a great performance, the model still required the regions of the image to be extracted and provided to the model as the input which meant the model couldn’t be relevant in real-time object detection tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YBXPktAt6ygWYzg0Z9hnPA.png" /><figcaption>The architecture of a Fast R-CNN model.</figcaption></figure><h4><strong>Faster R-CNN.</strong></h4><p>Introduced in 2016, the model performed very well at a record-breaking speed both in training and detection as compared to its predecessors. The model could take an image as an input and return the corresponding bounding boxes and their respective classes and this was due to its ability to integrate feature extraction techniques into the object detection network. <br>The researchers proposed a neural network region proposal network (RPN) which enabled the efficient extraction of features from the image and by doing so, the model achieved an optimal near-real-time object detection speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*JwJU_iVv0Mj--iCHZiwfCw.jpeg" /><figcaption>Faster R-CNN Architechture.</figcaption></figure><h4>YOLO Model Family.</h4><p>Proposed in 2015 by a group of Researchers from Washington University, Allen Institute for AI, and Facebook AI Research under the collective name — YOLO or rather “You Only Look Once”. This family of models is quite popular as they’re very fast, much faster than R-CNN models, achieving object detection in real time.</p><p>Unlike the R-CNN models, YOLO models only take a single pass through an image to generate ROI and their respective classes and thus the name “You Only Look Once”. The models work by subdividing an image into equal grids, whereby each grid is responsible for predicting a bounding box if the center of the bounding box falls within the said grid cell. However, the accuracy for the detected objects is much lower due to the exceptional speed of these models.</p><p>YOLO Models include: -</p><ul><li>YOLOv1, 2015.</li><li>YOLOv2, 2016.</li><li>YOLOv3, 2018.</li><li>YOLOv4, 2020.</li><li>YOLOv5, 2020.</li></ul><h4>SSD.</h4><p>It’s also good to mention a thing about SSD which is an acronym for “Single Shot MultiBox Detector”. Together with YOLO models, they belong to the Single-Stage Object Recognition Network Architecture whereby classification and localization tasks are carried out concurrently contrary to multi-stage detectors.</p><p>SSD uses pre-trained Neural net models such as VGG16, VGG19, AlexNet, or ResNet.</p><blockquote>VGG16 is used as the baseline model.</blockquote><p>With that, we’re done with the first article based on Object Detection. In the coming few weeks, I’m optimistic I’ll be in a position to publish more articles based on the same.</p><p>Meanwhile, you can check this GitHub repo for a simple convolutional network using the CIFAR10 dataset.</p><p><a href="https://github.com/Njaramba-Riri/Object-detection/tree/main/CIFAR-10">Object-detection/CIFAR-10 at main · Njaramba-Riri/Object-detection</a></p><p>Let’s connect on <a href="https://www.linkedin.com/in/riri-njaramba/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37569325332b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Version Control for Data Scientists.]]></title>
            <link>https://jamesriri.medium.com/version-control-for-data-scientists-6b48a4ded687?source=rss-376641da0201------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b48a4ded687</guid>
            <category><![CDATA[git-bash]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Riri]]></dc:creator>
            <pubDate>Wed, 29 Mar 2023 19:30:21 GMT</pubDate>
            <atom:updated>2023-04-03T10:39:58.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*oi5PkBcXsFn7JpANQc1vzQ.jpeg" /></figure><p>Also referred to as Source Control, Version Control enables one to efficiently keep track, share, and manage their source code or any other files in a secure, efficient manner. With version control you can be able to undo some changes in your files and revert back to your previous version of your — let’s say mobile or web application. While working as a team, Version control systems enables everyone in that team to see who and when the last file modifications were made, so it becomes really easy to manage any conflicts that might come along while working on the project.</p><p>In this comprehensive guide, we’ll cover different aspects of version control systems and how to use them effectively as a data scientist.</p><h4>Is there a need to use a VCS?</h4><p>Absolutely yes!.</p><p>As you get deeper into your tech career, you&#39;ll realize that delivery of different software solutions is highly prioritized in almost every organization, this is achieved through the help of the DevOps who oversee the whole project process — from problem definition, software development, to implementation. In such a case, you’ll find that there’re various individuals working on the same project, how do DevOps facilitate efficient collaboration and sharing of resources across the whole development team?, that&#39;s where Version Control Systems comes in. VCS enables the team to work in a distributed and asynchronous environment, manage changes in the code, manage different versions of the application being worked on. Also, it’s good to mention that VCS offer pretty impressive and easier ways to solve project’s conflicts and related anomalies.</p><h4>VCS Lingo.</h4><p>Before we proceed any further, let’s familiarize ourselves with some of the common terms used in VCS.</p><ul><li><strong><em>Repository:</em></strong></li></ul><p>Also referred to as repo, it’s a central location where all the code and the metadata for a project is stored, think of it a database. As we’ll see in the next part of this article, in a centralized VCS, there is a single, centralized repository, while in a distributed VCS, each developer has their own copy of the repository on their local machine.</p><ul><li><strong><em>Branch:</em></strong></li></ul><p>A branch is a separate line of development that diverges from the main line, or trunk, of development. Developers can create branches to work on new features or experiments without affecting the main codebase. Once the changes in a branch are complete and tested, they can be merged back into the main branch.</p><ul><li><strong><em>Merge:</em></strong></li></ul><p>Merging is the process of combining changes from one branch into another. When developers merge changes from a branch into the main branch, it brings those changes into the main codebase.</p><ul><li><strong><em>Commit:</em></strong></li></ul><p>A commit is a record of changes made to a file or set of files in the repository. Each commit includes a message describing the changes made, and a timestamp.</p><ul><li><strong><em>Conflict:</em></strong></li></ul><p>A conflict occurs when two or more developers make changes to the same file or set of files at the same time, and those changes cannot be automatically merged.</p><ul><li><strong><em>Pull:</em></strong></li></ul><p>Pulling is the process of downloading changes from a remote repository to a local repository.</p><ul><li><strong><em>Push</em></strong></li></ul><p>Pushing is the process of uploading changes from a local repository to a remote repository.</p><ul><li><strong><em>Checkout:</em></strong></li></ul><p>Checkout is the process of updating the local copy of a repository to the latest version of the files.</p><ul><li><strong><em>Revert:</em></strong></li></ul><p>Reverting is the process of undoing changes made to a file or set of files. In a VCS, this is typically done by rolling back to a previous version of the file or codebase.</p><ul><li><strong><em>Pull Request:</em></strong></li></ul><p>A pull request is a feature specific to distributed VCS, and is used to propose changes to a remote repository.</p><ul><li><strong><em>Fork:</em></strong></li></ul><p>A fork is a copy of a repository that is made by a developer or organization. Forking is often used in distributed VCS as a way for developers to work on changes to a project independently, without affecting the main codebase. Once changes are complete and tested, they can be merged back into the main codebase through a pull request.</p><ul><li><strong><em>Issue:</em></strong></li></ul><p>An issue is a problem that needs to be addressed in a project. Issues can be used to track bugs, feature requests, or other tasks related to the project.</p><h4>Types of Version Control Systems (VCS).</h4><p>There are three VCS; Local, Centralised, or distributed version control systems. Let’s have a brief look at each one of these.</p><ul><li><strong><em>Local Version Control Systems.</em></strong></li></ul><p>A Local VCS as the name suggests, stores the source files within a local machine or network.Typically they&#39;re used by individuals or small teams that don’t require the collaboration features of a centralised or distributed vcs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*VCyH3tOgiCrH3QeEG4emsQ.png" /><figcaption>Visual diagram of a Local Version Control.</figcaption></figure><ul><li><strong><em>Centralised Version Control Systems.</em></strong></li></ul><p>In a Centralised VCS, a central repository contains all the files and metadata associated with a certain project. The developers working on the project check out files from the central repository, make changes, and then committhose changes back to the central repo.This central server can be located on a server or on a developer’s local machine. Repo admins/owners can control who has access to the repository in this setup, but the fact that the repository is centralized makes it vulnerable to failure, which could prevent anyone from accessing the files in the repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*gBrlSGn1-t5eyq_WL4Ntzw.png" /><figcaption>Visual diagram of a Centralised VCS.</figcaption></figure><ul><li><strong><em>Distributed Version Control Systems.</em></strong></li></ul><p>In DVCS there is no central repository. Instead, each developer has a complete copy of the repository on their local machine. Developers make changes to their local copy, commit those changes, and then push those changes to a remote repository. DVCSs are often used by developers who need to work on projects from multiple computers or who need to collaborate with other developers remotely.</p><p>Examples of DVCS include Git, Mercurial, and SVN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*CaTs7tXj7ExKM_u9ig_Y-Q.png" /><figcaption>DVCS diagram.</figcaption></figure><h3>Data Science and VCS.</h3><p>For quite a number of years, Data Scientists didn’t use some software development tools like VCS but as the complexity of data science projects keeps on growing making the source code to become so much sophisticated, there have been a need for data scientists to learn how to work with VCS tools like SVN. Version Control Systems tools are very essential for data scientists to manage code, data, and models throughout the development process.</p><h4>Optimizing the usefulness of VCS tools in the context of Data Science.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hQXvS7JWAiPaiGUkfoXkQ.jpeg" /></figure><p>As a data scientist, you’re likely familiar with the challenge of managing complex code in Jupyter Notebooks. Functions to clean up data or perform specific tasks can quickly clutter the notebook and make it difficult to find critical parts. One solution is to break the functions into separate Python files that can be called into the main notebook. However, when working on complex projects with multiple files, it can be challenging to keep everything in sync. This is where version control systems like Git can be valuable. Git allows you to make changes to your code and commit your files simultaneously, keeping everything organized and up-to-date.</p><p>With that said, how can you, as a data scientist optimize the usefulness of VCS in your projects?. Here are some specific use cases: -</p><p><strong>i. Code management</strong></p><p>Data science projects typically involve writing code in multiple programming languages, such as Python, R, and SQL. VCS tools such as Git and SVN can manage your code versions, allowing you to track changes made to the codebase over time. If need arises, you can as well revert back to a previous version of your code.</p><p><strong>ii.Data Management.</strong></p><p>It’s very common that sometimes you find yourself working with large datasets which to be very honest are very difficult to manage. By using a tool like the Data Version Control, you can be able to efficiently track and manage changes to your data files. This tool ensures that you&#39;re working with the correct version of the data.</p><p><strong>iii. Model Management.</strong></p><p>You can&#39;t say “machine learning model” without mentioning “data scientist” or “ML Engineer” because both go hand in hand. MLflow a VCS tool provides an efficient way to track changes to models and compare different model versions. This helps you to ensure that you are using the best model for the task at hand and that you can reproduce the results of the model at a later stage.</p><p><strong>iv. Collaboration.</strong></p><p>Data science projects often involve multiple team members working together. GitHub in that case, comes in handy to provide a platform where you and your team members can collaborate on the same project, making it easy for each one of you to work on different parts of the project simultaneously and eventually merge changes together seamlessly.</p><h4>Git Overview.</h4><p>As I had mentioned earlier, Git is a Distributed Version Control System that was created in 2005 by the famous Linus Torvalds who also development the Linux Kernel System. As a data scientist/ developer Git allows you to track changes to your source code over time, collaborate with others, and maintain different versions of your code.</p><p>Git is free and open sourced which makes it more popular among the developers, also, it&#39;s good to mention that Git is very easy to learn and has a “tiny footprint with lightning-fast performance”. It has been designed with high performance, security, and robust flexibility in mind.</p><blockquote>Often, most people confuse between Git and Github. While it’s true that they are both related, they&#39;re very distinct tools. Git is a version control system that allows users to manage changes to their code over time. GitHub is a web-based hosting service that provides a platform for collaborative software development using Git.</blockquote><h4>Using Git:</h4><p>To successfully use Git there are several basic steps you can follow. Let’s discuss them:-</p><ul><li><strong><em>Install Git:</em></strong></li></ul><p>To get started, you first need to install Git on your local machine. You can download Git from the <a href="https://git-scm.com/downloads">official website</a> and install it based on your operating system.</p><ul><li><strong><em>Create a new repository:</em></strong></li></ul><p>Once Git is installed, you can create a new repository on your local machine. This is the main directory that will contain all the files and folders related to your project.</p><p>Launch Git Bash and navigate to your prefered directory where you want to create the new repo.</p><pre>cd desktop<br>mkdir demoapp<br>cd demoapp</pre><ul><li><strong><em>Initialize the repo:</em></strong></li></ul><p>To start using Git, you need to initialize the repository by running the git init command in the root directory of your project.</p><pre>git init</pre><ul><li>Git clone:</li></ul><p>After initializing, create a copy of a remote repo on your local machine.</p><pre>git clone https://github.com/username/repository.git</pre><ul><li><strong><em>Add files to the repository:</em></strong></li></ul><p>After initializing and cloning the repository, you can start adding files to it. You can add files using the git add command followed by the file name or directory.</p><pre>git add app.py #adds a specific file<br>git add . #adds everything in the current directory.</pre><ul><li><strong><em>Commit changes:</em></strong></li></ul><p>Once you have added files to the repository, you need to commit the changes using the git commit command. This creates a new snapshot of the files and saves it to the repository.</p><pre>git commit -m &quot;first commit&quot;</pre><ul><li><strong><em>Create branches:</em></strong></li></ul><p>Git allows you to create branches to work on different parts of your project simultaneously. You can create a new branch using the git branch command followed by the branch name.</p><pre>git branch -M main</pre><ul><li><strong><em>Push changes to a remote repository:</em></strong></li></ul><p>Git allows you to push your changes to a remote repository, such as GitHub, to collaborate with others. It’s now time to upload commits to the remote repo.</p><pre>git push origin main</pre><ul><li><strong><em>Pull changes from a remote repository:</em></strong></li></ul><p>To keep your local repository up-to-date with changes made by others, you can pull changes from a remote repository using the git pull command.</p><pre>git pull origin main</pre><p>For more Git commands:</p><p><a href="https://git-scm.com/docs/git#_git_commands">Git - git Documentation</a></p><p>Further resources:</p><p><a href="https://www.atlassian.com/git">How to Use Git? Tutorials, Workflows &amp; Commands | Atlassian</a></p><p>Let’s connect on<a href="https://www.linkedin.com/in/riri-njaramba/"> LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b48a4ded687" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis: What is it? How to do it?.]]></title>
            <link>https://jamesriri.medium.com/sentiment-analysis-what-is-it-how-to-do-it-881dc648118?source=rss-376641da0201------2</link>
            <guid isPermaLink="false">https://medium.com/p/881dc648118</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Riri]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 20:49:40 GMT</pubDate>
            <atom:updated>2023-03-24T15:30:34.305Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ym-dBm53ilpdoEYR.jpg" /></figure><p>At one instance in your life you’ve probably left a review for a product you bought online, a hotel you stayed during your vacation, or a movie you watched over the weekend, and if not, there&#39;s a high chance that you&#39;ve made a textual online post or comment on your social media profiles; be it be on Tweeter, Instagram, Reddit, LinkedIn… name it!. Have you ever asked yourself, “Where do all this data ends up to?” or “How can one benefit from all this information?”, if you have ever, good!! — and if not, I’m guessing by now you’ve probably started thinking about it. There&#39;s a high probability that sentiment analysis algorithms have interacted with your textual online posts and extracted some valuable information from it.</p><p>Most decision making processes in large businesses solely depend on the information extracted from this textual data to improve their general customer-business relations, which eventually translates to enhanced customer satisfaction and high profits for the business. Considering the fact that most data is in form of digital formats, businesses, through the application of NLP and ML techniques can be able to leverage the advantages that comes with this technology.</p><p>Let’s look at a real-world application of Sentiment Analysis; a movie have been released on Netflix or any other online movies’ platform and to the surprise of the stakeholders the movie doesn&#39;t do so well, the stakeholders wants to know what went wrong so that such a mistake won&#39;t be repeated in future. What do the stakeholders do? they get a data scientist who dives right into the movie reviews maybe on IMDb or he/she might decide to scrap the textual data addressing the said movie let&#39;s say from Tweeter. At the end of the day, the scientist will have some valuable data that he/she will later apply some NLP techniques to draw key information that will help the stakeholders understand the reasons behind the movie being unsuccessful.</p><h4><strong>What is Sentiment Analysis?</strong></h4><p>In this article, we’ll take a deep dive into sentiment analysis but first things first, what is sentiment analysis? “It is the use of natural language processing, text analysis, computational linguistics, and biometrics to systematically identify, extract, quantify, and study affective states and subjective information”, Wikipedia. Well, that&#39;s too much to digest, right?. In layman’s language, Sentiment Analysis is just a technique that is used to identify and extract information from a text. Technically, what Sentiment Analysis does is it tries to identify the emotional tone behind a text data.</p><p>Sentiment Analysis categorizes a sentiment into either: -</p><p>i. positive sentiment: eg., “I really liked that TV show.”</p><p>ii. Negative sentiment: eg., “I hate this character.”</p><p>iii. Neutral sentiment: eg., “The new restaurant in town has a variety of dishes on their menu.”</p><p>With that said, let&#39;s roll….</p><h4><strong>Getting started with NLP: How to do it?</strong></h4><p>By now you&#39;re probably saying, “okay, I get it, but when are we getting to the interesting part?”, well, say no more!. We’re going to develop various Sentiment Analysis models and see which one performs the best and later we will print it’s classification report to see how reliable it can be in predicting unseen data. But before that, it&#39;s good to keep in mind that this article doesn&#39;t get down to the nitty-gritty aspect of how to scrap the data for the sentiment analysis process, I recommend this<a href="https://brightdata.com/blog/how-tos/web-scraping-with-python?gspk=c3VuaWxzYW5kaHUzNzU2&amp;gsxid=gm069NpCWwLZ&amp;pscd=get.brightdata.com&amp;utm_source=affiliates&amp;utm_campaign=c3VuaWxzYW5kaHUzNzU2"> blog</a> for a step-step introduction to web scrapping, also, it’s good to note that sentiment analysis can sometimes become an up-hill challenge due to the flexibility and complexity of one’s language when it comes to expressing their emotions.</p><p>I will be using a dataset containing scrapped tweets, it can be found on this <a href="https://www.kaggle.com/competitions/nlp-getting-started/overview">Kaggle competion</a>. I recommend joining the competion if you’re enthusiastic about NLP, also, it’s an amazing plaform to practice your machine learning skills. The dataset is relatively smaller but we will use it regardless.</p><h4><strong>Analysing Disaster Tweets with NLP.</strong></h4><p>By analyzing tweets related to a disaster event, it’s possible to gain insights into the types of messages being shared, the geographic spread of the event, and the sentiment of the messages.</p><p><strong><em>About the data.</em></strong></p><p>It contains two sets of datasets, train and test data. It is made up of the following columns:</p><ul><li>id: unique tweet identifier.</li><li>keyword: specific word from the tweet.</li><li>location: where the tweet was sent from.</li><li>text: the actual tweet.</li><li>target: only present in the train dataset, it denotes the sentiment of the tweet, (1) for disaster and (0) for non-disaster.</li></ul><p><em>Loading the necessary packages:</em></p><pre>%matplotlib inline<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import numpy as np<br>import seaborn as sns<br><br>import re<br>import string<br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>import nltk<br>from nltk.corpus import stopwords<br>from wordcloud import WordCloud<br><br>import xgboost as xgb<br><br>from sklearn.svm import LinearSVC<br>from sklearn.naive_bayes import BernoulliNB<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import classification_report, f1_score, confusion_matrix<br>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer</pre><p><em>load the dataset:</em></p><pre>train=pd.read_csv(&quot;train.csv&quot;)<br>test=pd.read_csv(&quot;test.csv&quot;)</pre><p><strong>EDA:</strong></p><pre>#display the first five train data rows<br>train.head()<br><br>#display the first five test data rows<br>test.head()<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*I3NHPcxD4P9FNbCIS5FUdw.png" /><figcaption>Train set, first five rows.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*JpRm22Pc_cewZegJOYwBuw.png" /><figcaption>Test set, first five rows.</figcaption></figure><pre>#shape of each dataset<br>print(f&quot;The train data shape is: {train.shape}\nThe test data shape is: { test.shape}&quot;)<br><br>#any missing values in train dataset<br>train.isnull().sum()<br><br>#any missing values in test dataset<br>test.isnull().sum()<br><br>#check if any id&#39;s in train are present in test data<br>train[&#39;id&#39;].isin(test[&#39;id&#39;]).sum()</pre><p><strong>Further EDA:</strong></p><p>For easier further exploration of the two datasets, I decided to join the two sets.</p><pre>#join the two datasets, the train data will appear above the test dataset.<br>full=pd.concat(objs=[train, test], axis=0)<br><br>full.head()<br>full.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*i4owRrGYdnI6pbEOkHOxsg.png" /><figcaption>The merged dataframe.</figcaption></figure><p>Let’s rename the target column to sentiment to make things a lil bit more straightforward on what we’re working on 😄. Also, let’s see how the target label is distributed by creating a visualization. It’s always good to know if your dataset is balanced or imbalanced before starting to work on any classification task.</p><pre>#Rename the `target` column to `sentiment`<br>full=full.rename(columns={&#39;target&#39;:&#39;sentiment&#39;})<br><br>#Also, let&#39;s see the relation between `keyword` and `sentiment`<br>full.groupby(&#39;sentiment&#39;)[&#39;keyword&#39;].count()<br><br>#visualize the distribution in the full dataset:<br>sns.set(style=&quot;whitegrid&quot;, color_codes=True)<br>ax=sns.catplot(&quot;sentiment&quot;, data=full, kind=&quot;count&quot;, height=6)<br>plt.title(&quot;Distribution of Sentiments&quot;, size=15, weight=&quot;bold&quot;)<br>plt.xlabel(&quot;Sentiment&quot;, size=14, weight=&quot;bold&quot;)<br>plt.ylabel(&quot;Counts&quot;, size=14, weight=&quot;bold&quot;)<br>ax.set_xticklabels([&#39;Negative&#39;,&#39;Positive&#39;], rotation=0)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*iGS7c_AewpvwfLvm3tOBGw.png" /></figure><p>From the plot, we can see we have an almost equal distribution of both positive and negative sentiments, but from a technical perspective, this dataset is nowhere near “equal distribution”, therefore it is considered to be imbalanced. This information is important to know before starting to build your model — an imbalanced dataset can have a critical impact on your final model. In our case, the model will likely be inclined towards the predominant class — Negative Class.</p><p>…</p><p>Just for Fun:</p><p>Let’s print some random disaster and non-disaster related tweets.</p><pre>#print random examples of both disaster(positive) and non-disaster(negative) tweets.<br>print(full[full[&#39;sentiment&#39;]==1].iloc[np.random.randint(0,3200), 3])<br><br>#we do the same for the non-disaster<br>print(full[full[&#39;sentiment&#39;]==0].iloc[np.random.randint(0,4300), 3])</pre><p><strong><em>Missing values</em></strong></p><p>In any dataset, it’s hardly impossible to not find any missing values. For that reason, let’s create a pandas dataframe containing the missing values in each column but in percentage.</p><pre>percentage_missing=full.isnull().sum()*100/len(full)<br>missing_df=pd.DataFrame({&quot;columns&quot;:full.columns,<br>                        &quot;% missing&quot;: percentage_missing,<br>                        })<br>missing_df.reset_index(drop=True, inplace=True)<br>missing_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*J93YXp54DMLUkbp8AHpZKg.png" /><figcaption>Missing Values DataFrame.</figcaption></figure><p>From the dataframe, we can clearly see that our dataset is somehow “okay” considering there&#39;s no column with over 50% missing values, this means we can be able to handle these missing values in a more effective manner. However, I won’t cover on handling the missing values because I’m only intending to use the text and sentimentcolumns to create the model.</p><p>Similarly, let’s create another dataframe to see the top locations where the tweets in our dataset were ‘tweeted’ from.</p><pre>location=full[&#39;location&#39;].value_counts().sort_values(ascending=False)<br>location_df=pd.DataFrame(dict(zip(location.index, location.values)), index=[0]).\<br>                                melt(var_name=&quot;location&quot;, value_name=&quot;counts&quot;)<br>location_df.loc[:10]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*8M6kQYH0CN7HWlw8hGxIjQ.png" /><figcaption>Top locations DataFrame.</figcaption></figure><p><strong>WordClouds:</strong></p><p>Visualizing text using traditional graphical plots can be quite hard, instead, we will create some wordclouds to visualize the common keywords associated with disaster tweets…</p><p>let’s create wordclouds for the keywords drawn from the actual tweet text.</p><pre>#Disaster keywords<br>dis_tweets=&quot; &quot;.join([tweet for tweet in full[full[&#39;sentiment&#39;]==1][&#39;text&#39;]])<br><br>wc=WordCloud(max_words=100, width=1600, height=800, max_font_size=100,<br>            random_state=42).generate(dis_tweets)<br><br>#plot<br>plt.figure(figsize=(10,8))<br>plt.title(&quot;Disaster Keywords from tweets&quot;,size=30, weight=&#39;bold&#39;)<br>plt.imshow(wc, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*RDXZd_L0PhpnwZv_Aw6L_g.png" /><figcaption>Disaster-Associated keywords from the tweet text.</figcaption></figure><p>Non-Disaster keywords…</p><pre>#Non-disater keywords<br>non_dis_tweets=&quot; &quot;.join([tweet for tweet in full[full[&#39;sentiment&#39;]==0][&#39;text&#39;]])<br><br>wc=WordCloud( width=1600, height=800, max_font_size=120,<br>            random_state=10).generate(non_dis_tweets)<br><br>#plot<br>plt.figure(figsize=(10,8))<br>plt.title(&quot;Non-Disaster Keywords from tweets&quot;,size=30, weight=&#39;bold&#39;)<br>plt.imshow(wc, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*wifXs-3vUWme1VuZuOxjqQ.png" /><figcaption>Non-Disaster tweet text keywords.</figcaption></figure><h3><strong><em>Data Preprocessing and Transformations.</em></strong></h3><p>This step is very crucial in sentiment analysis, it involves: cleaning, transforming and preparing the data before it&#39;s fed into the model. In sentiment analysis data cleaning is not a walk-in-the-park task as textual data often contains redundant and/or repetitive words. However, several NLP data preprocessing techniques can be employed here, such as:-</p><ul><li>Removing stopwords, emojis, usernames, URLs, numbers, whitespaces, punctation marks, duplicated rows, etc.</li><li>Converting the text document to lowercase for better generalization.</li><li>Stemming- Involves reducing a word to it’s root form by removing the suffixes. eg., “eating” is stemmed to “eat”.</li><li>Lemmatization- Almost similar to stemming, it also involves reducing a word to it’s base form but it takes into consideration the context and part of the sentence where the word was used. eg., “ran” lemmatized to “run”.</li><li>Tokenization- This process involves breaking down a sequence of a text into smaller portions called tokens.</li><li>Vectorization- This involves mapping words to real numbers, or well put; a vector of real numbers.</li></ul><p>Let’s perform some ot these techniques.</p><pre>def clean_text(text):<br>    &#39;&#39;&#39;<br>    Make text lowercase, remove text in square brackets,remove links,remove punctuation, stopwords and remove words containing numbers.<br>    &#39;&#39;&#39;<br>    text = str(text).lower()<br>    text = re.sub(&#39;\[.*?\]&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;https?://\S+|www\.\S+&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;&lt;.*?&gt;+&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;\n&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;\w*\d\w*&#39;, &#39;&#39;, text)<br><br>    stop_words=set(stopwords.words(&quot;english&quot;))<br>    text = &#39; &#39;.join(word for word in text.split(&#39; &#39;) if word not in stop_words)<br>    # only removing the hash # sign from the word<br>    text = re.sub(r&#39;#&#39;, &#39;&#39;, str(text)) <br>    # remove punctuation<br>    punct = set(string.punctuation)<br>    text = &quot;&quot;.join(ch for ch in text if ch not in punct) <br>    &quot; &quot;.join(word for word in text.split() if word not in stop_words)<br>    <br>    return text</pre><p>The function we created, first converts all the text into lowercase, then removes all the links/urls, special characters, symbols and stop words, etc. The function later on returns a new transformed tweet/text…</p><pre>full[&#39;clean_tweet&#39;]=full[&#39;text&#39;].apply(clean_text)<br>full.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*brt-8mlp22J5rt0qiJYDYQ.png" /><figcaption>new colum created by the clean_tweet function.</figcaption></figure><p>Let’s now separate our full dataset to it’s original train and test sets.</p><pre>train=full.iloc[:len(train), :]<br>test=full.iloc[len(test):,:]<br><br>#clean the text in both datasets using the function we&#39;ve created<br>for data in [train, test]:<br>    data[&#39;clean_tweet&#39;]=data[&#39;text&#39;].apply(clean_text)<br><br>test.head()</pre><h4><strong>Building the Models:</strong></h4><p>I built and evaluated four different classification models using the clean_tweetcolumn as the only input and with the help of Kfold stratified cross-validation. The models were:-</p><ul><li>Naive Bayes Classifier.</li><li>Logistic Regression .</li><li>Support Vector Machine.</li><li>XGBoost.</li></ul><blockquote>Remember a machine learning model can only be able to take in interger values as the input, not words.</blockquote><p>Now we need to convert the ‘cleaned text’ into integers, this can be done through vectorization techniques.</p><p>For the next block of code, I used the scikit-learn vectorizer methods; CountVectorizer() and TfidfVectorizer() to convert the text into numerical features that will be used as the input for the classification models.</p><pre>#Count Vectorizer<br>cv=CountVectorizer( binary=True)#idicates if the word is present or not<br>cv.fit(train[&#39;clean_tweet&#39;].values.tolist()+test[&#39;clean_tweet&#39;].values.tolist())<br>train_cv=cv.transform(train[&#39;clean_tweet&#39;])<br><br>#tfidf vectorizer<br>tf=TfidfVectorizer()<br>tf.fit(train[&#39;clean_tweet&#39;].values.tolist()+test[&#39;clean_tweet&#39;].values.tolist())<br>train_tf=tf.transform(train[&#39;clean_tweet&#39;])</pre><p>Let’s now select our target variable...</p><pre>#identify the target variable<br>y=train[&#39;sentiment&#39;]</pre><p><strong><em>classification models:</em></strong></p><pre>from sklearn.model_selection import StratifiedKFold<br><br>fold=StratifiedKFold(n_splits=5, shuffle=True, random_state=42)<br><br>models={<br>    &quot;SVM&quot;:LinearSVC(),<br>    &quot;Logistic_Regression&quot;: LogisticRegression(),<br>    &quot;Naive_Bayes&quot;:BernoulliNB()<br>}<br><br>#vectors<br>vectors={<br>    &quot;CountVectorizer&quot;:train_cv,<br>    &quot;TfidFVectorizer&quot;:train_tf<br>}</pre><p>To simplify the process of building the models, I decided to create a function that would be appropriate in this scenario; the function builds all the models at once instead of creating a single model at a time. The function performs a KFold cross-validation and returns the model name and the results of each fold as the values.</p><pre>def strat_kfold(class_model:str,sample:str,y,kfold):<br>    <br>    results={}<br>    <br>    #store the model names in a dict<br>    results[&#39;model name&#39;]=class_model+ &quot;_&quot; + sample<br>    <br>    #call the model and the training data<br>    model=models[class_model]<br>    X= vectors[sample]<br>    <br>    #perform the cross_validation<br>    for fold, (train_idx, valid_idx) in enumerate(kfold.split(X,y)):<br>        X_train, X_valid=X[train_idx], X[valid_idx]<br>        y_train, y_valid=y[train_idx], y[valid_idx]<br>        <br>        #train and predict<br>        model.fit(X_train, y_train)<br>        y_pred=model.predict(X_valid)<br>        <br>        <br>        results[&quot;Kfold_{}&quot;.format(fold+1)]=f1_score(y_valid, y_pred)<br>    return results</pre><p>Store the models in a list and while at it, let&#39;s create a pandas dataframe containing the name of the model and the results.</p><pre>all_models=[]<br><br>for class_model in models:<br>    for sample in vectors:<br>        all_models.append(strat_kfold(class_model, sample, y, fold))<br>        print(f&quot;Model: {class_model}_{sample}...\n&quot;)<br><br><br>models_df=pd.DataFrame(all_models)<br>models_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*vsj7TUZtcpSsgsCIETPadg.png" /><figcaption>trained models’ results.</figcaption></figure><p><strong>XGBoost Model:</strong></p><p>I also wanted to see how well a gradient boosting model would perform in this scenario, so I decided to build an XGBoost model. Unfortunately the model didn&#39;t perform to my expectations but considering that I didn’t use any hyperparameter tuning, I’d say both the Count Vectorizer and TfidfVectorizer models performed slightly better.</p><p>Here&#39;s the Count Vectorizer model…</p><pre>params={<br>    &quot;objective&quot;:&#39;binary:logistic&#39;,<br>    &quot;tree_method&quot;:&#39;hist&#39;,<br>}<br><br>#Count Vectorizer model<br>xg_dict={}<br>xg_dict[&#39;model name&#39;]=&quot;XGBoost_CV&quot;<br><br><br>for fold, (train_idx, valid_idx) in enumerate(folld.split(train_cv, y)):<br>    print(f&quot;\nCurrently Training: {xg_dict[&#39;model name&#39;]}... Fold: {fold+1}&quot;)<br>    X_train, X_valid= train_tf[train_idx].astype(np.float32), train_tf[valid_idx].astype(np.float32)<br>    y_train, y_valid= y[train_idx].astype(np.float32), y[valid_idx].astype(np.float32)<br><br>    #training<br>    xgb_model=xgb.XGBClassifier(**params)<br>    xgb_model.fit(<br>        X_train,y_train, <br>        eval_set=[(X_valid, y_valid)], <br>        verbose=100,<br>        early_stopping_rounds=50<br>        )<br>    <br>    #predictions<br>    y_preds=xgb_model.predict(X_valid)<br>    xg_dict[&quot;Kfold_{}&quot;.format(fold+1)]=f1_score(y_valid, y_preds)<br><br><br># adding results to models df<br>new_model = pd.DataFrame(xg_dict, columns=models_df.columns, index=[0])<br>models_df = pd.concat([models_df, new_model], ignore_index=True)</pre><p>TfidfVectorizer Model…</p><pre>xgb_dict={}<br>xgb_dict[&#39;model name&#39;]=&quot;XGBoost_tfidf&quot;<br><br>for fold, (train_idx, valid_idx) in enumerate(folld.split(train_tf, y)):<br>    print(f&quot;\nCurrently Training: {xgb_dict[&#39;model name&#39;]}... Fold: {fold+1}&quot;)<br>    X_train, X_valid= train_tf[train_idx].astype(np.float32), train_tf[valid_idx].astype(np.float32)<br>    y_train, y_valid= y[train_idx].astype(np.float32), y[valid_idx].astype(np.float32)<br><br><br>    #training<br>    xgb_model=xgb.XGBClassifier(**params)<br>    xgb_model.fit(<br>        X_train, y_train, <br>        eval_set=[(X_valid, y_valid)],<br>        eval_metric= [&#39;logloss&#39;], <br>        verbose=1000, <br>        early_stopping_rounds=50<br>        )<br><br>    #predictions<br>    y_preds=xgb_model.predict(X_valid)<br>    xgb_dict[&#39;Kfold_{}&#39;.format(fold+1)]=f1_score(y_valid, y_preds)<br><br># adding results to models df<br>new_model = pd.DataFrame(xgb_dict, columns=models_df.columns, index=[0])<br>models_df = pd.concat([models_df, new_model], ignore_index=True)<br></pre><p>After building and adding the models to the models dataframe, all we’ve been left with is to create another column in the models_df that will contain the calculate f1 average score of each model, we need to see which one performed better…</p><pre>models_df[&#39;avg&#39;]=models_df.loc[:,&quot;Kfold_1&quot;:&quot;Kfold_5&quot;].sum(axis=1)*100/5<br>models_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*QkavDR0YImyBDaGgFxygpw.png" /><figcaption>Models Score</figcaption></figure><p>From the average column, our models performed decently considering the fact that we only used one column; clean_tweet , and with no hyperparameter tuning or feature engineering.</p><p>The Logistic_Regression_CountVectorizer model performed better than the rest, the model will be highly recommended for further development using the appropriate hyperparameter tuning, feature engineering and model overfitting and underfitting techniques.</p><p><strong>Evaluation:</strong></p><pre>X_train, X_test, y_train, y_test=train_test_split(train_cv, y, test_size=0.3, shuffle=True, random_state=42 )<br><br>model=LogisticRegression()<br>model.fit(X_train, y_train)<br><br>y_pred=model.predict(X_test)<br>y_train_pred=model.predict(X_train)<br><br>print(f&quot;\n\nTrain F1 Score: {f1_score(y_train,y_train_pred)}\nValidation F1 Score: {f1_score(y_test,y_pred)}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*wFgSdpenx18LegM0CC9akA.png" /></figure><p>The model performed exceptionally good on the train set but on the validation set it seems to have a relatively lower validation score. It’s with no doubt our Logistic Regression model overfitted the training data.Different techniques can be used to overcome this kind of overfitting but we won&#39;t go down that road for now but I will definitely consider writing an article about it.</p><pre>print(classification_report(y_test,y_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*GNKJJ4doXaglBsLjTdFq8Q.png" /></figure><p><strong>Confusion Matrix:</strong></p><pre>labels=[&#39;Negative&#39;, &#39;Positive&#39;]<br>cmatrix=confusion_matrix(y_test,y_pred)<br><br>fig, ax=plt.subplots(figsize=(10,8))<br>sns.heatmap(cmatrix, annot=True, fmt=&#39;g&#39;, ax=ax)<br>plt.xlabel(&quot;Predicted values&quot;)<br>plt.ylabel(&quot;True values&quot;)<br>plt.yticks(ticks=[0.5,1.5], labels=labels)<br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*WRm_QnS3ZqaKUxMO30CDaA.png" /></figure><p>From the confusion matrix, our model is clearly having a hard time making predictions on the positive class. This issue can be traced back to our initial concern about the dataset being imbalanced in the target class.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=881dc648118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Essentials for Data Scientists: Top Must-Know Commands.]]></title>
            <link>https://jamesriri.medium.com/sql-essentials-for-data-scientists-top-must-know-commands-418ac027942a?source=rss-376641da0201------2</link>
            <guid isPermaLink="false">https://medium.com/p/418ac027942a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Riri]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 19:20:33 GMT</pubDate>
            <atom:updated>2023-03-13T20:42:00.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*utSQc7vZmnWYXuYYn37CHw.png" /></figure><p>As a data scientists, having strong SQL skills is very vital for your data science career. In most cases, you are required to gather, retrieve, manipulate or store data which in most cases is contained in relational databases. Most RDBMS use SQL as their standard query language. With that in mind, it is therefore very essential for you as a data scientist to understand and equip yourself with this query language in order to perform your role successfully.</p><p>In this article, we will cover some of the essential SQL commands that every data scientist should know. But if by any chance the concept of SQL is new to you, I would recommend you have a look on my previous <a href="https://medium.com/@jamesriri03/sql-basics-a-brief-introduction-to-sql-529c71b898e1">article</a> where I discussed the basics of SQL.</p><p>With that said, let’s roll…</p><ol><li><strong>SELECT</strong></li></ol><p>The SELECT command is the most commonly used command in SQL. This statement is used to get or retrieve data from a database. Databases normally store data in tables, which consist of columns and rows. To get data from the database, you just need to specify the columns and the table from which you want to get the data using the SELECT statement.</p><p>Here is an example:</p><pre> CREATE TABLE customers(<br>    customer_id int NOT NULL PRIMARY KEY,<br>    name varchar2(30),<br>    gender varchar2(10),<br>    email varchar2(30),<br>    mobile number(12)<br>);<br><br>INSERT INTO customers (customer_id, name, gender, email, mobile) <br>VALUES (101, &#39;Tarrance Chastenet&#39;, &#39;Male&#39;, &#39;tchastenet0@washingtonpost.com&#39;, &#39;486-928-8389&#39;);<br><br>INSERT INTO customers (customer_id, name, gender, email, mobile) <br>VALUES (102, &#39;Norrie Bauser&#39;, &#39;Male&#39;, &#39;nbauser1@patch.com&#39;, &#39;617-319-2153&#39;);<br><br>INSERT INTO customers (customer_id, name, gender, email, mobile) <br>values (103, &#39;Arden Bister&#39;, &#39;Female&#39;, &#39;abister2@dailymotion.com&#39;, &#39;331-972-3630&#39;);<br><br>INSERT INTO customers (customer_id, name, gender, email, mobile) <br>values (104, &#39;Jeannette Brisley&#39;, &#39;Female&#39;, &#39;jbrisley3@sphinn.com&#39;, &#39;336-684-6469&#39;);<br><br>INSERT INTO customers (customer_id, name, gender, email, mobile) <br>VALUES (105, &#39;Lorie Marieton&#39;, &#39;Female&#39;, &#39;lmarieton4@nyu.edu&#39;, &#39;904-565-5910&#39;);<br><br>INSERT INTO customers (customer_id, name, gender, email, mobile) <br>VALUES (106, &#39;Maximilian Hilhouse&#39;, &#39;Male&#39;, &#39;mhilhouse5@blogtalkradio.com&#39;, &#39;213-803-5466&#39;);<br><br>INSERT INTO customers (customer_id, name, gender, email, mobile) <br>VALUES (107, &#39;Antoine Bigglestone&#39;, &#39;Male&#39;, &#39;abigglestone6@cbsnews.com&#39;, &#39;650-609-0093&#39;);<br><br>INSERT INTO customers (customer_id, name, gender, email, mobile) <br>VALUES (108, &#39;Jacenta Mordacai&#39;, &#39;Female&#39;, &#39;jmordacai7@scribd.com&#39;, &#39;942-142-6608&#39;);</pre><p>From the table we’ve created above, we can use the SELECT statement as follows:</p><pre>SELECT customer_id, name<br>FROM customers;</pre><p>The command will retrieve the data contained in the specified columns.</p><p><strong>2. WHERE</strong></p><p>The WHERE clause is used to filter data based on a condition. It is used to extract only those records that fullfill a specified condition. Mostly it’s used together with the SELECT statement but its also used together with UPDATE, DELETE, DROP, etc. statements.</p><p>Example:</p><pre>SELECT * <br>FROM customers<br>WHERE gender=&#39;Male&#39;;<br><br>SELECT name<br>FROM customers<br>WHERE customer_id BETWEEN 3 AND 8;<br><br>SELECT name <br>FROM customers<br>WHERE name LIKE &#39;C%&#39;;</pre><p><strong>3. ORDER BY</strong></p><p>The ORDER BY clause is used to sort data from the retrieved records either by ascending or descending order.</p><p>By default, this clause sorts the data in ascending order.</p><p>To optimize your productivity, you can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.</p><p>Example:</p><pre>SELECT * <br>FROM  customers<br>ORDER BY customer_id ASC;</pre><p><strong>4. GROUP BY</strong></p><p>This statement allows you to group rows of data based on one or more columns, and then perform aggregate functions on each group. The resulting output is a summary of the data for each group, which can be very useful for analyzing data and identifying patterns.</p><p>The aggregate functions include :COUNT(),MAX(),MIN(),SUM(),AVG()</p><p>Example:</p><pre>SELECT COUNT(customer_id), name<br>FROM customers<br>GROUP BY gender<br>ORDER BY COUNT(customer_id) DESC;</pre><p><strong>5. JOIN</strong></p><p>The JOIN clause is used to combine data from two or more tables based on a common column. For example, if you have two tables that contain related data and you want to combine them into a single table, you can use the JOIN statement.</p><p>For the sake of this section, we will create another table named ‘orders’ which we will use to illustrate different kinds of JOIN.</p><pre>CREATE TABLE orders (<br>  order_id INT PRIMARY KEY,<br>  customer_id INT,<br>  order_date DATE,<br>  total_amount DECIMAL(10,2)<br>);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(1, 101, &#39;2022-01-01&#39;, 100.50);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(2, 102, &#39;2022-01-02&#39;, 200.75);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(3, 103, &#39;2022-01-03&#39;, 50.00);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(4, 101, &#39;2022-01-04&#39;, 75.25);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(5, 102, &#39;2022-01-05&#39;, 300.00);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(6, 104, &#39;2022-01-06&#39;, 150.00);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(7, 103, &#39;2022-01-07&#39;, 50.00);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(8, 102, &#39;2022-01-08&#39;, 175.50);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(9, 104, &#39;2022-01-09&#39;, 250.00);<br><br>INSERT INTO orders (order_id, customer_id, order_date, total_amount)<br>VALUES(10, 101, &#39;2022-01-10&#39;, 125.75);</pre><p>There are different types of JOINs: -</p><ul><li><strong><em>INNER JOIN</em></strong></li></ul><p>This type of join returns only the rows where there is a match in both tables.</p><pre>SELECT *<br>FROM orders<br>INNER JOIN customers <br>ON orders.customer_id = customers.customer_id;</pre><p>This statement will return all rows from the orders table and the customers table where the customer_id values match in both tables.</p><blockquote><strong><em>Note</em></strong><em>: You can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.</em></blockquote><ul><li><strong><em>LEFT JOIN</em></strong></li></ul><p>This type of join returns all rows from the left table (orders) and the matching rows from the right table (customers). If there is no match in the right table, NULL values will be returned for the columns of that table.</p><p>Example:</p><pre>SELECT *<br>FROM orders<br>LEFT JOIN customers <br>ON orders.customer_id = customers.customer_id;</pre><blockquote>Note: LEFT JOIN is also known as LEFT OUTER JOIN</blockquote><ul><li><strong><em>RIGHT JOIN</em></strong></li></ul><p>This type of join returns all rows from the right table (customers) and the matching rows from the left table (orders). If there is no match in the left table, NULL values will be returned for the columns of that table.</p><p>Example:</p><pre>SELECT *<br>FROM orders<br>RIGHT JOIN customers <br>ON orders.customer_id = customers.customer_id;</pre><p>This above query will return all rows from the customers table and the matching rows from the orders table, and also return NULL values for the columns of the orders table where there is no match in the customers table.</p><blockquote>Note: RIGHT JOIN is also known as RIGHT OUTER JOIN.</blockquote><ul><li><strong><em>FULL JOIN</em></strong></li></ul><p>This type of join returns all rows from both tables, and NULL values are returned for the columns where there is no match in the other table.</p><p>Example:</p><pre>SELECT *<br>FROM orders<br>FULL OUTER JOIN customers <br>ON orders.customer_id = customers.customer_id;</pre><p>This query will return all rows from both the orders table and the customers table, and also return NULL values for the columns of each table where there is no match in the other table.</p><p>In summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*MCSTN1jGPc6uOgUv.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=418ac027942a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL BASICS: A BRIEF INTRODUCTION TO SQL.]]></title>
            <link>https://jamesriri.medium.com/sql-basics-a-brief-introduction-to-sql-529c71b898e1?source=rss-376641da0201------2</link>
            <guid isPermaLink="false">https://medium.com/p/529c71b898e1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Riri]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 10:27:28 GMT</pubDate>
            <atom:updated>2023-03-06T10:56:28.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*UFrgf64h-XnR1Rkl.png" /></figure><p>Many are the times you’ve heard the acronym SQL maybe from your friends, colleagues or from your lecturers, but what really is SQL? SQL stands for “Structured Query Language” and it’s the lingua franca that is used to manage, create, manipulate, and retrieve information/data from databases. It was developed in the 1970s by the IBM computer scientists.</p><p>Now that you know what is SQL, what does it really do? SQL performs various tasks in a database, some of these tasks include: -</p><ul><li>execute queries against databases.</li><li>create new tables in databases.</li><li>insert records in databases.</li><li>update records in a database.</li><li>Create and maintain database users.</li><li>delete records.</li><li>retrieve data from databases e.t.c.</li></ul><p>SQL is a very effective, easy to learn and use language. It is also considered to be functionaly complete due to it’s ability to let users define, retrieve and manipulate data in tables.</p><p>In this article, we will walk through the basics of SQL. Let’s roll…</p><p><strong>SQL Statements</strong></p><p>Statements in SQL are a set of instructions that consists of identifiers, parameters, variables, data types and SQL reserved key words. An SQL statement must compile successfully. e.g DELETE TABLE Users.</p><p>There are different types of SQL Statements, let’s discuss them below.</p><ol><li><strong><em>Data Manipulation Language(DML)</em></strong></li></ol><p>DML statements access and manipulate data in existing schema objects. These statements do not implicitly commit the current transaction. The data manipulation language statements are:</p><p>SELECT- Retrieves certain records from one or more tables.</p><p>INSERT- Creates a new record.</p><p>UPDATE- Modifies an existing record.</p><p>DELETE- Deletes particular record(s).</p><p>MERGE - combines the separate INSERT, UPDATE, and DELETE statements into a single SQL query.</p><p><strong><em>2. Data Definition Language(DDL)</em></strong></p><p>Data definition language statements let’s you perform tasks like:</p><ul><li>create, alter, and drop schema objects.</li><li>Analyze information on a table, index, or cluster.</li><li>Add comments to the data dictionary.</li></ul><p>DDL statements Includes:-</p><p>CREATE- Creates a new table, a view of a table, or other object in the database.</p><p>ALTER - Modifies an existing database object.</p><p>DROP - Deletes an entire table, a view of a table or other objects in the database.</p><p>RENAME- Used together with ALTER to modify objects in a database.</p><p>TRUNCATE- Deletes all data from the table.</p><p>COMMENT - Starts with /* and ends with */, this part of the code is not executed.</p><p><strong><em>3.Data Control Language(DCL)</em></strong></p><p>DCL statements let’s you grant and revoke privileges and roles, they are:</p><p>GRANT - Gives a privilege to user(s).</p><p>REVOKE- Takes backs privileges that were previously granted to the user.</p><p><strong><em>4.Transaction Control Language(TCL)</em></strong></p><p>Transaction control statements manage changes made by DML statements. The transaction control statements are:</p><p>COMMIT - Stores changes invoked by a transaction to the database.</p><p>ROLLBACK- Reverts all the changes that were made since the last COMMIT.</p><p>SAVEPOINT- Used together with Rollback to get a certain transaction at a particular point.</p><h4>Writing SQL statements.</h4><p>While writing SQL Statements it’s good to keep in mind that: -</p><p>i. SQL statements are not case sensitive.</p><p>ii. SQL can be entered on many lines.</p><p>iii. Keywords cannot be split across lines.</p><p>iv. Clauses are usually placed on separate lines for readability and ease of editing.</p><p>v. Indents make it more readable.</p><p>vi. Keywords may be entered in caps and all others in lowercase.</p><h4><strong>Why Learn SQL?</strong></h4><p>If you’re a professional in the software development domain, or a student who wants to become a Software Engineer, SQL is a very essential query language that you should equip yourself with. In most application softwares, developers tend to use SQL to store and manipulate data. Also, most Relational Database Management Systems(RDBMS) like MYSQL,Oracle, Postgres, Sybase, MS Access use SQL as their standard database language.</p><h4><strong>How does SQL Work?</strong></h4><p>Let’s say you’re executing SQL commands for any given SQL task, the system on which you’re running the code determines which is the best way to carry out your request while the SQL engine interprets the code. Sounds like a complicated process but it’s not.</p><p>Now let’s see the steps that are involved in Query Processing(this process involves translating the High Level SQL Queries into low level expressions that are used in the physical level of the file system, as well as in the query optimization and of course in the actual execution of the query).</p><h4>Step-1:Parser</h4><p>During this stage, the database performs the following checks- Syntax check, and Semantic check, this is after converting the query into relational algebra.</p><p><em>Syntax Check:</em></p><p>Involves checking whether the rules of writing an SQL command have been satisfied/followed ( This rules are what we call Syntax).</p><p>e.g SELECT * FORM students</p><p>The above command can&#39;t be executed and thus will result into an error, this is due to the mispelling of the keyword FROM.</p><p><em>Semantic Check:</em></p><p>During this check, the parser determines whether a statement is meaningful or not.</p><p>Example: Let’s say you requested for a table named Students from the database but you haven&#39;t created it yet which technically means it doesn&#39;t exist, the error you’ll get will be due to the <em>Semantic Check.</em></p><h4>Step-2: Optimizer</h4><p>During the optimization stage, database must perform a hard parse(this is when the SQL commands are re-loaded into the shared pool)for atleast one unique Data Manipulation Language statement. Eventually, the parse performs optimization on the commands.</p><h4>Step-3:Execution Engine:</h4><p>The query is finally executed and the output is displayed.</p><h4>Hands-on SQL.</h4><p>Now let’s get down to the practical part of SQL.</p><h4><strong><em>Creating Tables</em></strong></h4><p>In SQL you create tables using the CREATE TABLE statement. When creating tables, you must provide three basic essentials:</p><ul><li>Table name.</li><li>Column names.</li><li>Data types for each column.</li></ul><p><strong>Guidelines for creating tables.</strong></p><p><strong><em>Table and column naming rules:</em></strong></p><ul><li>Must start with a letter, which is followed by a sequence of letters, numbers,_,#,0r $.</li><li>Must be 1 to 30 characters long.</li><li>Must not be an SQL reserved word.</li></ul><p><strong><em>data types:</em></strong></p><p>SQL supports different datatypes, they include:</p><ul><li><em>VARCHAR2(n):</em> Variable length charater string up to n characters.</li><li><em>CHAR(n):</em> Fixed length charater string of n characters.</li><li><em>NUMBER(n):</em> Integer number of up to n digits.</li><li><em>NUMBER(precision, scale):</em> Fixed-point decimal number. “precision” is the total number of digits; “scale” is the number of digits to the right of the decimal point. The decimal point is not counted.</li><li><em>NUMBER:</em> Floating-point decimal number.</li><li><em>DATE:</em> DD-MON-YY (or YYYY) HH:MM:SS A.M. (or P.M.) form date-time.</li><li><em>LONG:</em> Variable-length character string up to 2 GB.</li><li><em>NCHAR:</em> LONG for international character sets (2-byte per character).</li><li><em>CLOB:</em> Single-byte ASCII character data up to 4 GB.</li><li><em>BLOB:</em> Binary data (e.g., program, image, or sound) of up to 4 GB.</li><li><em>BFILE:</em> Reference to a binary file that is external to the database (OS file).</li><li><em>RAW(size) or LONG_RAW:</em> raw binary data.</li><li><em>ROWID:</em> Unique row address in hexadecimal format.</li></ul><p>Example:</p><pre>CREATE TABLE employees(<br>employee_id number(7) not null,<br>first_name varchar2(20),<br>last_name varchar2(20),<br>cellphone varchar2(12),<br>email varchar2(20),<br>hire_date date,<br>job_id varchar2(5),<br>salary number(12,2),<br>manager_id number(6),<br>department_id number(4)<br>);</pre><h4>Adding data into tables.</h4><p>You use the key word INSERT to add data into any table in SQL.</p><p>Example:</p><pre>INSERT INTO employees <br>VALUES(1000,&#39;Simon&#39;,&#39;Otieno&#39;,&#39;0722456789&#39;,&#39;otieno@yahoo.com&#39;,&#39;01-jan-90&#39;,&#39;5500&#39;,32000,5000,10);<br><br>INSERT INTO employees <br>VALUES(1001,&#39;Alice&#39;,&#39;Mwangi&#39;,&#39;0720766659&#39;,&#39;alice@yahoo.com&#39;,&#39;02-feb-80,&#39;5600&#39;,42000, 5000,10);</pre><h4>Retrieving data from database objects using SELECT Statement</h4><p>As mentioned earlier, SELECT is used to retrieve data from the database. With the SELECT statement you can have the following capabilities.</p><ul><li>Projection- choose columns/fields from a table through a query.</li><li>Selection- choose rows in a table.</li><li>Joining - bring together data that is stored in different tables by specifying the link between them.</li></ul><p>Examples:</p><pre>SELECT * FROM employees; /*selects everything*/<br><br>SELECT employee_id,first_name,last_name, email , job_id, salary <br>FROM employees; /*selects only the specified columns*/</pre><h4>Arithmetic Expressions in SQL</h4><p>Arithmetic expressions in SQL perfom arithmetic operations on the numeric operads/values stored in the database tables. Expressions used include:-</p><p>+ - for Addition.</p><p>- - for Subtraction operations.</p><p>* - for multiplication.</p><p>/ - for division.</p><p>% - for modulus.</p><p>Example:</p><pre>SELECT employee_id, first_name,last_name, salary, salary + 3000 <br>FROM employees;<br><br>SELECT employee_id, first_name,last_name, salary, 12* salary + 700<br>FROM employees;<br><br>SELECT employee_id, first_name,last_name, salary, 12* (salary + 700) <br>FROM employees;<br><br>SELECT employee_id, first_name,last_name, salary, 12* (salary - 2000) <br>FROM employees;</pre><h4><strong>Restricting and sorting data using the </strong><strong>SELECT statement.</strong></h4><p><strong>use of the </strong><strong>WHERE clause.</strong></p><p>The WHERE clause is used to filter records. It only extracts those records that fulfill a specified condition.</p><p><em>Comparison conditions</em></p><p>= -Equal to.</p><p>&gt; -Greater than.</p><p>&gt;=-Greater than or equal to.</p><p>&lt; -Less than.</p><p>&lt;=-Less than or equal to.</p><p>&lt;&gt;-Not equal to.</p><p>IS Null -is a null value.</p><p>IN (set) -Match any of the list.</p><p>examples:</p><pre>SELECT employee_id &quot;Employee ID&quot;,first_name &quot;First Name&quot;,last_name &quot;Last Name&quot;, email &quot;Email&quot; , job_id &quot;Job ID&quot;,salary &quot; Monthly Pay &quot; <br>FROM employees <br>WHERE employee_id=1000;<br><br>SELECT employee_id &quot;Employee ID&quot;,first_name &quot;First Name&quot; ,last_name &quot;Last Name&quot;, email &quot;Email&quot; , job_id &quot;Job ID&quot;,salary &quot; Monthly Pay &quot; <br>FROM employees <br>WHERE salary &gt; 10000;<br><br>SELECT employee_id &quot;Employee ID&quot;,first_name &quot;First Name&quot; ,last_name &quot;Last Name&quot;, email &quot;Email&quot; , job_id &quot;Job ID&quot;,salary &quot; Monthly Pay &quot; <br>FROM employees <br>WHERE salary IN(10000,20000,30000);</pre><p><em>Logical Conditions</em></p><p>AND- Returns true if both are true</p><p>OR- Returns true if one is true</p><p>NOT- Return true if condition is false</p><p>Examples:</p><pre>SELECT employee_id,last_name <br>FROM employees <br>WHERE salary &gt;=10000 AND manager_id=5000;<br><br>SELECT employee_id,last_name <br>FROM employees <br>WHERE department_id NOT IN(90,60,30);</pre><p><strong>Using the </strong><strong>ORDER BY Clause.</strong></p><p>This keyword, sorts out the records in a particular order. By default, it sorts records in ascending order.</p><p>Example:</p><pre>SELECT last_name,job_id, department_id <br>FROM employees <br>ORDER BY hire_date DESC;<br><br>SELECT last_name,job_id, department_id <br>FROM employees <br>ORDER BY hire_date ASC;</pre><p>ps: asc=ascending, desc=descending.</p><p><strong>UPDATE Command</strong></p><p>As mentioned earlier in the article, this command is used to update data in given tables.</p><p>Example:</p><pre>UPDATE employees <br>SET salary= 50000 <br>WHERE employee_id=1001;<br><br>UPDATE employees <br>SET last_name=&#39;Opiyo&#39; <br>WHERE employee_id=1000;</pre><p><strong>DELETE Command.</strong></p><p>It is Used to delete or remove records from tables in a database.</p><p>example:</p><pre>DELETE FROM employees <br>WHERE employee_id=1000;</pre><p><strong>ROLLBACK Command.</strong></p><p>This command is used to undo any changes made since the last commit statement in a SQL transaction. When a rollback command is executed, all changes made to the database since the last commit are undone, and the database is reverted to its previous state.</p><p>example:</p><pre>ROLLBACK;</pre><p><strong>COMMIT Command.</strong></p><p>Ensures that records are permanently saved. This command can be used within a transaction to commit the changes made by the transaction. Once the commit command is executed, the changes are saved permanently and cannot be rolled back.</p><p>example:</p><pre>COMMIT;</pre><h4>SQL Constraints</h4><p>Constraints are rules that define the allowable values and relationships for data in a database table. Constraints can help ensure data integrity, prevent invalid or inconsistent data from being inserted or updated, and provide a way to enforce business rules or policies. They include:-</p><ul><li><strong><em>NOT NULL Constraint</em></strong></li></ul><p>This constraint is used to specify that a column in a table must contain a value and cannot be left empty or null.</p><p>Example:</p><pre>CREATE TABLE Sales ( <br>Sale_Id int NOT NULL, <br>Sale_Amount int NOT NULL, <br>Vendor_Name varchar(255) NOT NULL, <br>Sale_Date date, <br>Profit int<br>);</pre><ul><li><strong><em>UNIQUE Constraint</em></strong></li></ul><p>The “UNIQUE” constraint is used to ensure that the values in a column or a group of columns are unique and cannot be repeated in the same table.</p><p>Example:</p><pre>CREATE TABLE employees2( <br>employee_id number(6), <br>last_name varchar2(20) NOT NULL, <br>email varchar2(20), <br>salary number(10,2), <br>hire_date date NOT NULL, <br>CONSTRAINT emp_email_uk UNIQUE(email)<br>);</pre><ul><li><strong><em>PRIMARY KEY Constraint.</em></strong></li></ul><p>This constraint is used to specify a column or a group of columns that uniquely identifies each row in a table. The primary key constraint ensures that the values in the specified column or columns are unique and cannot be repeated in the same table.</p><p>Example:</p><pre>CREATE TABLE Sales (<br>Sale_Id int NOT NULL,<br>Sale_Amount int NOT NULL,<br>Vendor_Name varchar(255),<br>Sale_Date date,<br>Profit int,<br>PRIMARY KEY (Sale_Id)<br>);</pre><ul><li><strong><em>FOREIGN KEY Constraint.</em></strong></li></ul><p>The “FOREIGN KEY” constraint is used to create a relationship between two tables based on the values in a column or a group of columns. The foreign key constraint ensures that the values in the specified column or columns in one table correspond to the values in a primary key column or columns in another table.</p><p>Example:</p><pre>CREATE TABLE employees3 (<br>employee_id number(6) PRIMARY KEY,<br>last_name varchar2(20) NOT NULL,<br>first_name varchar2(20),<br>salary number(10,2),<br>hire_date date NOT NULL,<br>department_id number(4) CONSTRAINT emp_dept_fk <br>FOREIGN KEY(department_id) REFERENCES department (department_id)<br>);<br><br>CREATE TABLE department(<br>  department_id int PRIMARY KEY,<br>  last_name varchar2(20) NOT NULL,<br>  first_name varchar2(20)<br>);</pre><ul><li><strong><em>CHECK Constraint.</em></strong></li></ul><p>This constraint is used to specify a condition that must be satisfied for each row in a table. The check constraint ensures that the values in a column or a group of columns meet a specific condition or set of conditions.</p><p>Example:</p><pre>CREATE TABLE Sales( <br>Sale_Id int NOT NULL UNIQUE, <br>Sale_Amount int NOT NULL, <br>Vendor_Name varchar(255) <br>CHECK (Sale_Amount &gt;= 100 AND Vendor_Name&lt;&gt; &#39;John&#39;), <br>Sale_Date date, <br>Profit int<br>);</pre><ul><li>When you have constrains in place, an error is returned if you try to violate the constraint rule.</li></ul><h4>ALTER TABLE Statement.</h4><p>This statement is used to:-</p><p>i. Add a new column to a table.</p><p>ii. Modify an existing column.</p><p>iii. Define default value for a new column.</p><p>iv. Drop a column from a table.</p><p>Example:</p><pre>ALTER TABLE employees <br>ADD CONSTRAINT emp_id_pk PRIMARY KEY;<br><br>ALTER TABLE employees2 <br>DROP CONSTRAINT emp_dept_fk;</pre><p>Notice the ADD and DROP constraint commands, the former is used to create a UNIQUE, PRIMARY KEY, FOREIGN KEY, or CHECK constraint while the latter is used to delete the same. This is can only be done if the table already exists.</p><h4>DATA OBJECTS</h4><p>In SQL, Objects are used in databases to store or reference data. An object can only be accessed by using its identifier. There are various data objects in SQL, they include:-</p><ul><li>Table- Basic unit of storage.</li><li>View- Logically represents subsets of data from one or more tables.</li><li>Sequence- Generates numeric values.</li><li>Index- Improves the performance of some queries.</li><li>Synonyms- Gives alternative names to objects.</li></ul><p>Let’s look at VIEW.</p><p><strong><em>VIEW</em></strong></p><p>A view is a virtual table that does not actually store data, but instead provides a way to access and manipulate data from one or more tables. A view can be thought of as a stored SELECT statement that defines a set of columns and rows based on a query.</p><p>Why use a VIEW?</p><ol><li>To restrict data access.</li><li>To make complex queries easy.</li><li>To provide data independence.</li><li>To present different views of the same data.</li></ol><p>creating a view:</p><pre>CREATE VIEW emp1 AS <br>SELECT * <br>FROM employees;</pre><p>To remove a view use the DROP VIEW statement.</p><p>e.g</p><pre>DROP VIEW emp1</pre><p><em>Originally published at </em><a href="https://gist.github.com/Njaramba-Riri/bd9a8c8216ff7b6b77f310458487ec80"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=529c71b898e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Data Analysis: The Ultimate Guide]]></title>
            <link>https://jamesriri.medium.com/exploratory-data-analysis-the-ultimate-guide-c7e99ffd49ce?source=rss-376641da0201------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7e99ffd49ce</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Riri]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 06:35:25 GMT</pubDate>
            <atom:updated>2023-02-28T07:25:40.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/291/0*mL6TdvWKtbvKDRxQ.png" /></figure><h3>Exploratory Data Analysis (EDA): The Ultimate Guide</h3><p>Exploratory Data Analysis(EDA), also referred to as Data Exploration, is the process of analyzing,investigating and summarizing datasets to gain insights into the underlying patterns and relationships within the dataset, this is done by employing data visualization techniques and graphical statistical methods like histograms,heatmaps, violin plots, joint plots etc. Technically, Eda is all about ‘understanding the dataset’.</p><p>‘Understanding’ in this context might refer to quite a number of things: -</p><ul><li>Extracting important variables which is normally referred to as Feature engineering.</li><li>Identifying and dealing with outliers and missing values.</li><li>Understanding the relationships between variables; linear or non-linear variables.</li></ul><p>By employing EDA techniques, you can change a very grumpy dataset into a very clean dataset. Overall, EDA is a very crucial and critical part of any data analysis project, it is often used to guide the data analyst while doing further analysis and data modelling.</p><p>In this article we will dive deeper into EDA, we will discuss several topics: -</p><ol><li>Data cleaning and preparation</li><li>Univariate Analysis</li><li>Bivariate Analysis</li><li>Multivariate Analysis</li><li>Visualization Techniques</li><li>Descriptive Statistics.</li></ol><p>The first step in data analysis is to clean and prepare the data. This might involve employing techniques such as identifying and correcting missing values, removing outliers, and transforming variables as necessary. This step ensures that data is cleaned and prepared for the other processes ahead. For a successful data analysis process, data is required to be as accurate and reliable as possible.</p><p>Let’s have a look on how you can do this:</p><pre>#Import the necessary libraries<br><br>import pandas as pd<br># Read in data <br>df = pd.read_csv(&#39;data.csv&#39;) <br><br># Check for missing values <br>print(df.isnull().sum()) <br><br><br># Remove outliers <br><br>df = df[df[&#39;column_name&#39;] &lt; 100] <br><br># Transform variables <br>pdf[&#39;new_column&#39;] = df[&#39;column_name&#39;] * 2</pre><p>Univariate analysis involves analyzing each variable in the dataset individually. Let’s say you have variable named age, by using univariate analysis, you can calculate the summary statistics of this variable eg., mean, median,mode, standard deviation, and variance. This step also involves visualizing the distribution of each variable using histograms, box plots, density plots etc.</p><p>We can use the Seaborn library to perform a univariate analysis on some set of data: -</p><pre>import seaborn as sns <br><br># Load data <br>tips = sns.load_dataset(&#39;tips&#39;) <br><br># Calculate summary statistics <br>print(tips.describe()) <br><br># Visualize distribution with histogram <br>sns.histplot(tips[&#39;total_bill&#39;], kde=False)</pre><p>On the other hand of Univariate Analysis we have Bivariate Analysis, your guess is good as mine, Bivariate Analysis involves analyzing the relationships between two variables in a dataset.Again, let’s look this from a practical point of view, you have two variables height and weight and you need to understand the relationship between the two, Bivariate analysis let&#39;s you use graphical methods such as scatter plots, bar charts, line plots etc. to visualize this relationships.It also includes calculation of correlation coefficients, cross-tabulations and contigency tables.</p><p>Let’s use the matplotlib library to illustrate bivariate analysis: -</p><pre>#Import the necessary libraries <br>import matplotlib.pyplot as plt <br>import seaborn as sns <br><br># Load data <br>iris = sns.load_dataset(&#39;iris&#39;) <br><br># Calculate correlation coefficients <br>print(iris.corr()) <br><br># Visualize relationship with scatter plot <br>plt.scatter(iris[&#39;sepal_length&#39;], iris[&#39;sepal_width&#39;]) plt.xlabel(&#39;Sepal Length&#39;) plt.ylabel(&#39;Sepal Width&#39;) plt.show()p</pre><p>This is the statistical procedure that involves analyzing the relationships between more than two variables. Alternatively, multivariate analysis can be used in analyzing the relationship between dependent and independent variables. It’s major applications is relevant in:- clustering, feature selection, dimensionality reduction, hypothesis testing etc.</p><p>Another very important component of EDA is data visualization, it gives the data analyst a chance to explore and understand the data visually. This step is very crucial for any organization as it is easily understandable by the non-technical people in the organization. Non-technical people sometimes have hard time trying to understand the ‘under-the-hood’ variable relationships but with data visualization, they can easily understand the relationshhips between different variables in the dataset.There are several techniques and tools used in this process. Some tools that are normally used by data analysts to visualize data include: -</p><ul><li>MS Power Bi</li><li>MS Excel</li><li>Tableu</li><li>Google Data Studio</li></ul><p>For the techniques, there are numerous techniques that can be employed to visualize your data. We will discuss some of these techniques using the pandas library: -</p><p><em>Histograms</em></p><p>Histograms are used to visualize the distribution of a continuous variable like height. The hist() method is used to generate a histogram.</p><pre># Generate a histogram <br>df[&#39;column_name&#39;].hist()</pre><p><em>Boxplots</em></p><p>Boxplots are used to visualize the distribution of continuous variables and to detect outliers. The boxplot() method is used.</p><pre># Generate a boxplot <br>df[&#39;column_name&#39;].boxplot()</pre><p><em>ScatterPlots</em></p><p>This technique is used to visualize the relationship between two continuous variables, e.g, height and weight. The plot.scatter() method is used to generate a scatterplot.</p><pre># Generate a scatterplot <br>df.plot.scatter(x=&#39;column1&#39;, y=&#39;column2&#39;)</pre><p><em>Barcharts</em></p><p>Bar charts are used in visualizing the distribution of categorical variables in a dataset. An example of a categorical variable is gender, race, type of job etc. The plot.bar() method is used to generate a bar chart.</p><pre># Generate a bar chart <br>df[&#39;column_name&#39;].value_counts().plot.bar()</pre><p>We’ve talked a lot about the theoretical side of EDA, but now let’s get to the fun part where we will be applying these techniques on a real-world dataset. Working with real-world data can at times be quite hard and frustrating, as it involves paying careful attention to data cleaning, exploration, handling outliers, dealing with missing data, and finally understanding the data. Also, it’s good to keep in mind that- the ultimate goal for any data scientist is to achieve an accurate, meaningful, and relevant analysis to the problem at hand. To get your hands on a real-word data, there are various open source and free data websites that provides a wide pool of datasets, they iclude: Data.gov, Kaggle, World Bank Open Data, Open ML, Datahub, etc.</p><p>Enough have been said, let’s now dive right into the nitty-gritty part. For this particular article, i’ll be uswhichfghing an East African dataset that can be found on: https://www.kaggle.com/datasets/enockmokua/financial-dataset</p><p><em>Importing Libraries</em></p><pre>#Import the necessary libraries <br>%matplotlib inline  #for displaying plots directly below the code cell <br>import matplotlib.pyplot as plt  #for creating plots <br>import pandas as pd  #for data manipulation and analysis <br>import numpy as np  #for working with arrays and matrices <br>import seaborn as sns  #for complex visualizations that can&#39;t be achieved by plt <br>sns.set();  #sets the default parameters for seaborn</pre><p><em>Loading and Exploring the Data</em></p><pre>#load the data <br>df=pd.read_csv(&quot;Datasets/finance.csv&quot;)</pre><pre>#check the dataset size and shape <br>df.shape, df.size</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*7LM_p9wsysBORJjA" /></figure><pre>#Display the first 5 rows <br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/0*fOqySgW73TxSZweR" /></figure><pre>#Display the last 5 rows <br>df.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/0*qaNhth48LwTpuab1" /></figure><pre>#View the column names <br>df.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/0*O665UeA6N-Ojesn0" /></figure><pre>#view the column data types <br>df.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/0*7UhYv_zIR-GPKmTq" /></figure><pre>#view the summary statistics of the numerical columns <br>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*47Tgf7q4sWP6sF2-" /></figure><pre>#Display the summary of the DataFrame <br>df.info</pre><pre>#Display the total number of missing values in each column <br>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*oemfwMYTnq7RVVls" /></figure><pre>#Create a mini dataframe to see the % of the missing values <br>missing=(df.isnull().sum()*100/len(df)) <br>missing_df=pd.DataFrame({&#39;Percentage missing&#39;: missing}) <br>missing_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*-snridu3hs0k0eV8" /></figure><p><em>Data Cleaning</em></p><pre>#Drop irrelevant columns, or columns with too many missing values <br>df.drop([&#39;Unnamed: 0&#39;,&#39;year&#39;], axis=1, inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*rHak_Jymtz_i5nLr" /></figure><pre>#Fill the missing values with the mean or median <br>df[&#39;Respondent Age&#39;].fillna(df[&#39;Respondent Age&#39;].mean(), inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*W2aY8SF0vsXy-Lon" /></figure><pre>#Check for any duplicates and drop them if exists <br>df.drop_duplicates(inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/0*qM2VNc4OhyfyePkE" /></figure><p><em>Creating visualizations</em></p><p>We will create histogram visualizations using the Matplotlib library and seaborn libraries.</p><pre>#Using matplotlib <br>x=(df[&quot;Respondent Age&quot;]) <br>plt.hist(x,100,density=True, facecolor=&quot;green&quot;) plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*e65Ygd_wzJkLiKWP" /></figure><pre>#Using Seaborn ]<br>sns.histplot(df[&#39;Respondent Age&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*o6uadF-HjxRoKbJ8" /></figure><pre>#Scatter plots for two numerical columns <br>sns.scatterplot(data=df, x=&#39;Respondent Age&#39;,y=&#39;household_size&#39;,hue=&#39;Has a Bank account&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*XfTp2H5-sJ3UkdGD" /></figure><pre>#Boxplot of a numerical column by a categorical column <br>sns.boxplot(x=&#39;Respondent Age&#39;,y=&#39;country&#39;, data=df);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*e3zQPWxqD7pWFl9a" /></figure><pre>#A heatmap of the correlation between columns <br>sns.heatmap(df.corr());</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*0gt2ldAxKzPgV8V5" /></figure><pre>#A bar chart of the headcount per country <br>df.country.value_counts().plot(kind=&#39;bar&#39;) plt.xlabel(&quot;Country&quot;) plt.ylabel(&quot;Count&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*HwgXeaZZZvwAJMv2" /></figure><pre>#A pie chart for the number of respondents per country <br>counts=df.country.value_counts() plt.pie(counts, labels=counts.index, autopct=&#39;%1.1f%%&#39;) plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*8d4Y_sh2lEMLtldz" /></figure><h4><strong>Chi-Squared Test</strong></h4><p>So far we’ve only talked and visualized mostly numerical variables, and you might be wondering, “What about the Categorical variables?”. That’s where Chi-Squared test comes in, the chi-squared test is basically a statistical test used to determine if there is any significant association/relationship between two categorical variables. It is used to compare observed data with expected data, and to determine if the differences between them are significant enough to reject the null hypothesis that there is no association between the variables.</p><p>In Python, you can use the scipy.stats module, which provides a function called chi2_contingency() that calculates the chi-squared statistic, degrees of freedom, p-value, and expected frequencies for a contingency table. Let&#39;s try it out.</p><pre>import numpy as np <br>from scipy.stats import chi2_contingency <br><br># create a contingency table <br>table = np.array([[10, 20, 30], [15, 25, 35]]) <br><br># perform the chi-squared test <br>chi2, p, dof, expected = chi2_contingency(table) <br><br># print the results <br>print(&#39;Chi-squared statistic:&#39;, chi2) <br>print(&#39;Degrees of freedom:&#39;, dof) <br>print(&#39;P-value:&#39;, p) <br>print(&#39;Expected frequencies:\n&#39;, expected)</pre><ul><li>The contingency table we created with two rows and three columns, represents the frequency of two categorical variables.</li></ul><p>The expected output will be:</p><pre>Chi-squared statistic: 0.27692307692307694 <br>Degrees of freedom: 2 <br>P-value: 0.870696738961232 <br>Expected frequencies: [[11.11111111 20. 28.88888889] <br>                       [13.88888889 25. 36.11111111]]</pre><p>-The p-value is greater than the significance level of 0.05, which means we fail to reject the null hypothesis that there is no association between the variables. Therefore, we conclude that there is no significant association between the variables.</p><p>-Check out this <a href="https://towardsdatascience.com/chi-square-test-for-feature-selection-in-machine-learning-206b1f0b8223">article</a> for further understanding of Chi-Square Test.</p><p><em>Originally published at </em><a href="https://gist.github.com/Njaramba-Riri/6555c707a2f13eda228fc62748545493"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7e99ffd49ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>