<?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 Nafiu on Medium]]></title>
        <description><![CDATA[Stories by Nafiu on Medium]]></description>
        <link>https://medium.com/@nafiu.dev?source=rss-8ec1182d9733------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aQMaWfgz1mV0CY4F8Igl7w.png</url>
            <title>Stories by Nafiu on Medium</title>
            <link>https://medium.com/@nafiu.dev?source=rss-8ec1182d9733------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:33:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nafiu.dev/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[Advanced exploratory analysis and machine learning, to predict your personality type]]></title>
            <link>https://medium.com/@nafiu.dev/advanced-exploratory-analysis-and-machine-learning-to-predict-your-personality-type-f90a323caacb?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/f90a323caacb</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 15:06:51 GMT</pubDate>
            <atom:updated>2024-02-19T15:06:51.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dDpjBn969s-XdxDK" /><figcaption>Photo by <a href="https://unsplash.com/@nonsapvisuals?utm_source=medium&amp;utm_medium=referral">Nonsap Visuals</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Hi everyone</strong>, this is a practical guide to a fascinating topic; today, we will do some advanced data analysis to understand how personality types work, and we will also learn how to process data and create a machine learning model that will help to predict your personality type.<br>In simple terms, <strong>The goal</strong> of this project is to practice data analysis to answer all the questions that a person or a business might need when it comes to personality types. Secondly in this post, you will learn how to process and train a machine-learning model and make real-time predictions to predict a targeted person&#39;s personality type.</p><p>For this tutorial, we will be using the <strong>(MBTI) Myers-Briggs Personality Type Dataset </strong>from Kaggle. which you can find here: <a href="https://www.kaggle.com/datasets/datasnaek/mbti-type/data">https://www.kaggle.com/datasets/datasnaek/mbti-type/data</a></p><p><strong>Table of contents</strong></p><ol><li><a href="#035b">overview</a></li><li><a href="#2038">loading data</a></li><li><a href="#fee0">Cleaning data</a></li><li><a href="#7204">Exploratory data analysis</a></li><li><a href="#326e">Data Pre-processing</a></li><li><a href="#5ddc">Modeling and Training</a></li><li><a href="#5f34">Real-time predictions</a></li><li><a href="#85b8">Conclusion</a></li></ol><p><strong>First</strong>, let me give you a simple basic summary of the dataset that we are gonna use.</p><p>The Myers-Briggs Type Indicator (MBTI) dataset is based on the theories of Carl Gustav Jung, a Swiss psychiatrist. It’s a widely used psychological dataset designed to categorize individuals into 16 distinct personality types across 4 axes.<br>which are:</p><p><em>1. Extraversion (E) vs. Introversion (I):<br>— Extraversion: Outgoing, sociable, and energetic.<br> — Introversion: Reserved, quiet, and reflective.</em></p><p><em>2. Sensing (S) vs. Intuition (N):<br> — Sensing: Practical, concrete, and focused on details.<br> — Intuition: Imaginative, creative, and focused on possibilities.</em></p><p><em>3. Thinking (T) vs. Feeling (F):<br> — Thinking: Logical, analytical, and objective.<br> — Feeling: Empathetic, compassionate, and focused on relationships.</em></p><p><em>4. Judging (J) vs. Perceiving (P):<br> — Judging: Organized, planned, and decisive.<br> — Perceiving: Flexible, spontaneous, and adaptable.</em></p><p>So for example. an individual who prefers introversion, intuition, thinking, and perceiving would be labeled an INTP in the MBTI system.</p><p><strong>The dataset.<br></strong>This dataset contains over 8600 rows of data, on each row is a person’s.<br>The dataset has 2 two feature types and posts. <br>Type (This person’s 4-letter MBTI code/type)<br>A section of each of the last 50 tweets they have posted (Each entry separated by “|||” (3 pipe characters))</p><p>Now that we have an overview of the dataset that we gonna use and what we gonna do in this tutorial, let&#39;s get started with the coding. also, I hope that you have already downloaded the dataset and have it in your working directory.</p><p><strong>Let’s get started…:)</strong></p><h4>Loading the dataset</h4><p>let’s Import the required libraries</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import re<br>import nltk<br>from nltk.corpus import stopwords<br>import string<br>from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer<br>from sklearn.model_selection import train_test_split<br>from sklearn.svm import LinearSVC<br>from sklearn.metrics import accuracy_score<br><br>nltk.download(&#39;stopwords&#39;)</pre><p>loading the dataset using pandas.</p><pre>df = pd.read_csv(&#39;mbti_1.csv&#39;)<br>df.head()</pre><p>let’s check more details of the dataset such as the data types of the features and also check if there are any null values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*85ecOWv9c0xv6S08aPdNhg.png" /><figcaption>image by the author</figcaption></figure><p>we can see that the dataset contains 8675 rows, two features(type and posts), and has no null values.</p><h4>Cleaning Data</h4><p>well, since the dataset has no null values. there is not much of a cleaning in general to do. but we do have to clean the posts feature since it&#39;s text and it has, special characters, stopwords, links, and some other things that we don&#39;t need. So, in this post, we gonna process that text clean it, and create another feature named “clean_posts”.</p><p>let&#39;s code the cleaning function and clean it</p><pre>stop = nltk.corpus.stopwords.words(&#39;english&#39;)<br>def clean_text(text):<br>    text = text.replace(&#39;|||&#39;,&#39; &#39;)<br>    text = re.sub(&#39;https?://\S+|www\.youtube\S+&#39;, &#39;youtube&#39;, text)<br>    text = re.sub(&#39;https?://\S+|www\.facebook\S+&#39;, &#39;facebook&#39;, text)<br>    text = re.sub(&#39;https?://\S+|www\.instagram\S+&#39;, &#39;instagram&#39;, text)<br>    text = re.sub(&#39;https?://\S+|www\.twitter\S+&#39;, &#39;twitter&#39;, text)<br>    text = re.sub(&#39;https?://\S+|www\.\S+&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;\[.*?\]&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;&lt;.*?&gt;+&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;[%s]&#39; % re.escape(string.punctuation), &#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>    text = [word for word in text.split( ) if word not in stop]<br>    text = &quot; &quot;.join(text)<br>    text = text.lower()<br>    return text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*kVMoLHKSBIALvxqE3_6q-Q.png" /><figcaption>image by the author</figcaption></figure><h4>Exploratory data analysis</h4><p>That is all for data cleaning. so now let’s get started with analysis.</p><p>before we dive into exploratory analysis I want to give you an idea of how we are gonna proceed with this part of this tutorial. to keep you in focus.<br>A question will be asked and we will be using data analysis and data visualization methods to answer that question and so on.</p><p><strong>Number of tweets in each row? (separated by “|||”)</strong></p><pre>df[&#39;num_tweets&#39;] = df[&#39;posts&#39;].str.count(&#39;\|\|\|&#39;) + 1<br>df[&#39;num_tweets&#39;].unique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*UeNgLb0u5iCKE6OheWg5jA.png" /><figcaption>image by the author</figcaption></figure><p>well, we can see that every post doesn&#39;t have 50 tweets. some rows have as less as 2. which is pretty low., :(</p><p>So now let&#39;s check if the wether 16 types have an equal number of posts. (all combined)</p><h4>Number of tweets in each type?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*tRX_kdXc9sSwbGIGH3IKCg.png" /><figcaption>image by the author</figcaption></figure><p>well, we can see that it’s not equal.</p><p>but think about this. even at this point, we can say that the personality types ESFJ, ESFP, ESTJ, and ESTP don’t like Twitter. since they have fewer posts on Twitter.</p><p><strong>Average total word count? in each post</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*3z4OWnau6NS8u7WIht2HgQ.png" /><figcaption>image by the author,</figcaption></figure><p>we can conclude that the average number of word counts is 726 words per post.</p><p><strong>Average word count in each type?</strong></p><pre>avg_word_count_by_type = df.groupby(&#39;type&#39;)[&#39;word_count&#39;].mean()<br>avg_word_count_by_type.plot(kind=&#39;bar&#39;, figsize=(8, 4), color=&#39;skyblue&#39;)<br>plt.title(&#39;Average Word Count for Each Personality Type&#39;)<br>plt.xlabel(&#39;Personality Type&#39;)<br>plt.ylabel(&#39;Average Word Count&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*YA8Z1L1U2ZN-98UJa9xE6w.png" /><figcaption>image by author</figcaption></figure><p><strong>will the word count affect results (accuracy)?</strong></p><p><strong>NO</strong>, the Average Length of posts in each category is almost the same, so we can say it will not affect the results.</p><p><strong>Most used words on all the posts?</strong></p><pre>vectorizer = CountVectorizer()<br>word_counts = vectorizer.fit_transform(df[&#39;clean_posts&#39;])<br>feature_names = vectorizer.get_feature_names_out()<br>total_word_counts = word_counts.sum(axis=0)<br><br># Create a DataFrame to display the most used 10 words<br>top_words_df = pd.DataFrame({<br>    &#39;Word&#39;: feature_names,<br>    &#39;Count&#39;: total_word_counts.A1  # Convert to a 1D array<br>})<br><br>top_10_words = top_words_df.sort_values(by=&#39;Count&#39;, ascending=False).head(10)<br>top_10_words</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*DHMBz5MXEA4qABuLcPAfmQ.png" /><figcaption>image by author</figcaption></figure><p><strong>Which type is most obsessed with talking about others?</strong></p><pre># Define a list of words related to talking about others<br>words_related_to_others = [&#39;he&#39;, &#39;she&#39;, &#39;they&#39;, &#39;his&#39;, &#39;her&#39;, &#39;their&#39;, &#39;him&#39;, &#39;his&#39;, &#39;hers&#39;, &#39;theirs&#39;]<br><br>df[&#39;mentions_others&#39;] = df[&#39;clean_posts&#39;].apply(lambda x: any(word in x for word in words_related_to_others))<br>mentions_others_by_type = df.groupby(&#39;type&#39;)[&#39;mentions_others&#39;].sum()<br>most_obsessed_type = mentions_others_by_type.idxmax()<br>mentions_others_by_type = df.groupby(&#39;type&#39;)[&#39;mentions_others&#39;].sum()<br><br>mentions_others_by_type.plot(kind=&#39;bar&#39;, figsize=(12, 6), color=&#39;lightcoral&#39;)<br>plt.title(&#39;Counts of Posts Mentioning Others by Personality Type&#39;)<br>plt.xlabel(&#39;Personality Type&#39;)<br>plt.ylabel(&#39;Number of Posts Mentioning Others&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kP3VfcH6cB-FqQ8901UiEg.png" /><figcaption>image by author</figcaption></figure><p><strong>Which type is most obsessed about themselves?</strong></p><pre># Define a list of words related to talking about oneself<br>words_related_to_self = [&#39;i&#39;, &#39;me&#39;, &#39;my&#39;, &#39;mine&#39;]<br><br>df[&#39;mentions_self&#39;] = df[&#39;clean_posts&#39;].apply(lambda x: any(word in x for word in words_related_to_self))<br>mentions_self_by_type = df.groupby(&#39;type&#39;)[&#39;mentions_self&#39;].sum()<br><br>mentions_self_by_type.plot(kind=&#39;bar&#39;, figsize=(12, 6), color=&#39;lightgreen&#39;)<br>plt.title(&#39;Counts of Posts Mentioning Oneself by Personality Type&#39;)<br>plt.xlabel(&#39;Personality Type&#39;)<br>plt.ylabel(&#39;Number of Posts Mentioning Oneself&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9yJ51nJRlgS4PXfA9y1tQ.png" /><figcaption>image by author</figcaption></figure><p><strong>Which type is more romantic?</strong></p><pre># Define a list of words related to romance<br>words_related_to_romance = [&#39;love&#39;, &#39;romance&#39;, &#39;date&#39;, &#39;heart&#39;, &#39;sweet&#39;, &#39;kiss&#39;, &#39;cuddle&#39;]<br><br>df[&#39;mentions_romance&#39;] = df[&#39;clean_posts&#39;].apply(lambda x: any(word in x for word in words_related_to_romance))<br>mentions_romance_by_type = df.groupby(&#39;type&#39;)[&#39;mentions_romance&#39;].sum()<br><br>mentions_romance_by_type.plot(kind=&#39;bar&#39;, figsize=(12, 6), color=&#39;pink&#39;)<br>plt.title(&#39;Counts of Romantic Posts by Personality Type&#39;)<br>plt.xlabel(&#39;Personality Type&#39;)<br>plt.ylabel(&#39;Number of Romantic Posts&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMSSAaE-S6zCQH7bCdhcOg.png" /><figcaption>image by the author</figcaption></figure><p><strong>which type is most active on social media?</strong></p><pre># Define a list of social media platform names<br>platforms = [&#39;facebook&#39;, &#39;instagram&#39;, &#39;youtube&#39;]<br><br># Create columns indicating the presence of platform names in posts<br>for platform in platforms:<br>    df[f&#39;mentions_{platform}&#39;] = df[&#39;clean_posts&#39;].apply(lambda x: platform in x.lower())<br>mentions_by_type = df.groupby(&#39;type&#39;)[[f&#39;mentions_{platform}&#39; for platform in platforms]].sum()<br><br>mentions_by_type.plot(kind=&#39;bar&#39;, figsize=(12, 6), colormap=&#39;viridis&#39;)<br>plt.title(&#39;Counts of Mentions for Each Social Media Platform by Personality Type&#39;)<br>plt.xlabel(&#39;Personality Type&#39;)<br>plt.ylabel(&#39;Number of Mentions&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYS5ckmEBkjHXmZKQrhFvA.png" /><figcaption>image by author</figcaption></figure><p>For sure we can conclude that YouTube is the most common social media platform among these people.</p><h4>Data Pre-processing</h4><p>preparing data to create the machine learning model.</p><p>let&#39;s get started by splitting the data</p><pre>train_df, test_df = train_test_split(df, test_size=0.2, random_state=42)</pre><p>Next, Vectorizing the clean posts using TfidfVectorizer</p><p><strong><em>TfidfVectorizer explained <br></em></strong><em>Term frequency Inverse document frequency known as TFIDF is a statistical formula to convert text documents into vectors based on the relevancy of the word. The method creates a matrix with data on the most and least important terms in the document using the bag of words model.</em></p><pre>vectorizer = TfidfVectorizer()<br>X_train = vectorizer.fit_transform(train_df[&#39;clean_posts&#39;])<br>X_test = vectorizer.transform(test_df[&#39;clean_posts&#39;])</pre><p>Creating targeted variables, our targeted variables are going to be the type feature.</p><pre>y_train = train_df[&#39;type&#39;]<br>y_test = test_df[&#39;type&#39;]</pre><h4>Modeling and Training</h4><p>let’s load the model. we will be using LinearSVC model from sklearn which is used for multiclass classification tasks.</p><pre>Model = LinearSVC()</pre><p>Training the model with the processed data</p><pre>Model.fit(X_train, y_train)</pre><p>Making predictions and Evaluating the model</p><pre>y_pred = Model.predict(X_test)<br>accuracy = accuracy_score(y_test, y_pred)<br>print(f&quot;Accuracy: {accuracy *100:.2f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*qUvpD0_fk92sQPsLlGhCqw.png" /><figcaption>image by author</figcaption></figure><p>we can see that our model got an accuracy of 66%. which is not bad. <br>so next let&#39;s get straight into making real-time predictions.</p><h4>Real-time predictions</h4><p>let&#39;s create a function that processes the given data (text) calls the model and returns the predicted type.</p><pre>def predict_realtime(comment):<br>  comment_processed = vectorizer.transform([comment])<br>  comment_pred = Model.predict(comment_processed)<br>  return comment_pred[0]</pre><p>Just for this test case I&#39;m gonna pick a text from the dataset and check if it predicts it correctly. you can use any text you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*OglVHP1LRyMvBE4aLW9OnA.png" /><figcaption>image by author</figcaption></figure><p>Here we can see that it predicts that the given data belongs to the “INFJ” type. which is correct. (look at the dataset :).</p><h4>Conclusion</h4><p><strong>Yay…</strong> you completed it. you did it 😂 🎉.<br>This is the end of this tutorial. I believe this is a good project that wants to improve data science skills. well, there are lots of improvements which you can still make, I think it’s best if you try to improve and learn.</p><p>Anyways it was fun so hope you enjoyed it. 🙂</p><p><strong>link to GitHub repo: </strong><a href="https://github.com/nafiu-dev/data_analysis_projects">https://github.com/nafiu-dev/data_analysis_projects</a></p><p><strong>you can connect with me here:</strong></p><p><strong>Instagram</strong>: 👉 <a href="https://www.instagram.com/nafiu.dev">https://www.instagram.com/nafiu.dev</a></p><p><strong>Linkedin</strong>: 👉<a href="https://www.linkedin.com/in/nafiu-nizar-93a16720b"> https://www.linkedin.com/in/nafiu-nizar-93a16720b</a></p><p><strong>My other posts:</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/telecom-customer-churn-dataset-exploratory-data-analysis-and-building-machine-learning-models-97ca2b899b6a">Telecom customer churn dataset; Exploratory data analysis and building machine learning models</a></li><li><a href="https://medium.com/@nafiu.dev/stock-market-prediction-using-lstm-will-the-price-go-up-tomorrow-practical-guide-d1df2d54a517">Stock market prediction using LSTM; will the price go up tomorrow. Practical guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f90a323caacb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telecom customer churn dataset; Exploratory data analysis and building machine learning models]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@nafiu.dev/telecom-customer-churn-dataset-exploratory-data-analysis-and-building-machine-learning-models-97ca2b899b6a?source=rss-8ec1182d9733------2"><img src="https://cdn-images-1.medium.com/max/2600/0*iajvtuz9YdOmEKDN" width="4000"></a></p><p class="medium-feed-snippet">Hi everyone, this is a practical guide to advanced exploratory data analysis and machine learning. We will discuss how to explore the&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@nafiu.dev/telecom-customer-churn-dataset-exploratory-data-analysis-and-building-machine-learning-models-97ca2b899b6a?source=rss-8ec1182d9733------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@nafiu.dev/telecom-customer-churn-dataset-exploratory-data-analysis-and-building-machine-learning-models-97ca2b899b6a?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ca2b899b6a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Sat, 28 Oct 2023 16:57:35 GMT</pubDate>
            <atom:updated>2023-10-28T16:57:35.387Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Create a Text Paraphrasing SaaS Tool Using React]]></title>
            <link>https://javascript.plainenglish.io/create-a-text-paraphrasing-saas-tool-using-react-e23659f37c2e?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23659f37c2e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[ideas]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 15:17:12 GMT</pubDate>
            <atom:updated>2023-06-02T15:17:12.220Z</atom:updated>
            <content:encoded><![CDATA[<h4>Weekly SaaS, Idea 1: Let’s learn to build your dream SaaS software.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D4t7L5POUf5DoPw7" /><figcaption>Photo by <a href="https://unsplash.com/fr/@siora18?utm_source=medium&amp;utm_medium=referral">Siora Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Hi everyone</strong>, Today we will be creating a paraphrasing tool using react js which enables you to easily rewrite, rephrase, change, and transform the syntax, and structure of the input text. This Tool supports more than 50 languages including English, French, German, Spanish, Italian, Arabic, and Chinese with automatic language detection.</p><p>This means if you want to paraphrase a Chinese sentence you will only have to copy and paste it into the paraphraser and this tool will do the job for you.</p><blockquote><strong>Note:</strong> I will be writing tutorials on creating different types of applications, machine learning, and more. And if you want your idea to be one, Share your idea with me <a href="https://www.instagram.com/nafiu.dev/">here</a>, <a href="https://www.instagram.com/nafiu.dev">Instagram@nafiu.dev</a></blockquote><p><strong>Here is a preview of the working app</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*q1fvexxHTcQNLjTQNTkHsQ.png" /><figcaption>image by author</figcaption></figure><p><strong>What you will learn</strong></p><ul><li>Create a react project</li><li>Handle an API</li><li>React Hooks</li></ul><p><strong>Table of contents</strong></p><ul><li><a href="#6013">Creating and installing required packages</a></li><li><a href="#9e0b">Cleaning the app</a></li><li><a href="#b393">Creating the components and designing the App</a></li><li><a href="#4564">Creating and Connecting with the API</a></li><li><a href="#839f">Conclusion</a></li></ul><p><strong>Let’s get started… :)</strong></p><h4><strong>Creating and installing required packages</strong></h4><p>Open the terminal on your desktop or where ever location where you want to create this app. And create a new folder in the directory named <strong>paraphrasing_tool</strong> and change the directory to the folder.</p><pre>mkdir paraphrasing_tool <br>cd paraphrasing_tool </pre><p>Now create a new react app using create new react app command</p><pre>npx create-react-app .</pre><p>Once the app is successfully created now install the Axios packages using the npm command. Axios is useful for us to connect with the API.</p><pre>npm i axios</pre><h4><strong>Cleaning the app</strong></h4><p>Open the folder in vscode.</p><pre>code .</pre><p>Now it’s time to clean the app here we will delete the unnecessary files and clean the App.js.<br>Delete the following files App.css, App.test.js, and logo.svg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*gK3ud13g_L6qv4lKmanoJA.png" /><figcaption>image by author</figcaption></figure><p>Now open the App.js file and remove everything in the file and using the vscode shortcut <strong>rafce </strong>create a new clean function in the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*nOFYzBas4EH0H4nIK05_EA.png" /><figcaption>image by author</figcaption></figure><p>Next, start the app using the command npm start, the app must start without any errors.</p><h4><strong>Creating the components and designing the App</strong></h4><p>Well, sure in a simple blog we can’t spend hours of time writing CSS, therefor I will just let ask you to copy and paste the following CSS code into the index.css file.</p><p>Open the index.css file in the vscode and copy and paste this CSS code</p><pre>* {<br>  padding: 0;<br>  margin: 0;<br>  box-sizing: border-box;<br>}<br><br>.container {<br>  width: 100%;<br>  height: 100vh;<br>  display: flex;<br>  flex-direction: column;<br>  align-items: center;<br>  justify-content: center;<br>}<br>.text_box {<br>  width: 80%;<br>  display: flex;<br>}<br>.text_box textarea {<br>  width: 50%;<br>  height: 300px;<br>  margin: 10px;<br>  padding: 5px;<br>  font-size: 17px;<br>  outline: none !important;<br>  border: 2px solid #e0e0e0 ;<br>  border-radius: 3px;<br>  box-shadow: 0 0 5px #719ECE;<br>  -webkit-border-radius: 3px;<br>  -moz-border-radius: 3px;<br>  -ms-border-radius: 3px;<br>  -o-border-radius: 3px;<br>}<br><br>.text_box textarea:focus {<br>  outline: none !important;<br>  border: 3px solid #00b0ff  ;<br>  box-shadow: 0 0 5px #719ECE;<br><br>}<br>.button_box {<br>  width: 80%;<br>  display: flex;<br>  justify-content: space-between;<br>}<br>.button_box button, .button_box p {<br>  margin: 10px;<br>}<br>.button_box button {<br>  border: 2px solid #00b0ff;<br>  background-color: #00b0ff;<br>  color: #eee;<br>  font-size: 17px;<br>  padding: 5px 10px;<br>  border-radius: 3px;<br>  cursor: pointer;<br>  font-weight: bold;<br>  -webkit-border-radius: 3px;<br>  -moz-border-radius: 3px;<br>  -ms-border-radius: 3px;<br>  -o-border-radius: 3px;<br>}<br>.button_box button:hover {<br>  background-color: #fff;<br>  color: #00b0ff;<br>}<br>.button_box p {<br>  font-size: 18px;<br>  font-weight: bold;<br>  color: #333;<br>}<br>.button_box p span {<br>  color: #00b0ff;<br>}</pre><p>Now open the App.js file, here we will create the structure of the app. We will be creating a wrapped container and two rows of div in the container as the following.</p><p>Here is the pure HTML code required to run the app.</p><pre>        &lt;div className=&#39;container&#39;&gt;<br>            &lt;div className=&quot;text_box&quot;&gt;<br>                &lt;textarea &gt;&lt;/textarea&gt;<br>                &lt;textarea class=&quot;loading&quot; disabled &gt;&lt;/textarea&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;button_box&quot;&gt;<br>                &lt;button&gt;Paraphrase&lt;/button&gt;<br>                &lt;p&gt;similarity: &lt;span&gt;0.22&lt;/span&gt;&lt;/p&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;</pre><p>At this moment if you visit the app in the browser you will see the app as we wanted.</p><p>Next, you have to import useState from react js. And create 4 different states that are required for this app.</p><ol><li>Loading: for loading, show the loading screen until we get the returned data</li><li>input: here we will store user input text</li><li>Similarity: This is a similarity of the text, input, and output. We get this from the API as well</li><li>Result: this is the output paraphrased data returned from the API</li></ol><p>Use the following set of codes to set this up.</p><pre>    const [loadin, setLoading] = useState(true)<br>    const [input, setinput] = useState(&quot;&quot;)<br>    const [similarity, Setsimilarity] = useState(0)<br>    const [result, SetResult] = useState(&quot;&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*8jajurRXZr_xTTVjsey_NA.png" /><figcaption>image by author</figcaption></figure><p>That is all we need to store data for this application. Next, we will create a function to handle the click.</p><p>Basically, what to happen after you click the Paraphrase button</p><p>Create a function name <strong>handleClick </strong>which will take the user input as a perimeter and this function will set the loading, and outputs</p><pre>    const handleClick = async input =&gt; {<br>        setLoading(true)<br>        // CALL API HERE<br><br>        setLoading(false)<br>        SetResult(&quot;balh balh&quot;) <br>        Setsimilarity(&quot;blah balh&quot;) <br> <br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*MOAdqde4FFVHB28hkVpKCg.png" /><figcaption>image by the author</figcaption></figure><p>Now we have to show the data to our user, meaning we have to add these variables to the returned html doc. As the following.</p><pre>return (<br>    &lt;div className=&#39;container&#39;&gt;<br>        &lt;div className=&quot;text_box&quot;&gt;<br>            &lt;textarea onChange={e =&gt; setinput(e.target.value)} &gt;{input}&lt;/textarea&gt;<br>            { <br>                loadin ? <br>                ( &lt;textarea class=&quot;loading&quot; disabled &gt;&lt;/textarea&gt;) <br>                :<br>                (<br>                    &lt;textarea value={result}&gt;{result}&lt;/textarea&gt;<br>                )<br>            }<br>        &lt;/div&gt;<br>        &lt;div className=&quot;button_box&quot;&gt;<br>            &lt;button onClick={() =&gt; {handleClick(input)}}&gt;Paraphrase&lt;/button&gt;<br>            {similarity &gt; 0 ? (&lt;p&gt;similarity: &lt;span&gt;{similarity}&lt;/span&gt;&lt;/p&gt;): null}<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*SL0fsYEgMGB97tCd5qOcZw.png" /><figcaption>image by author</figcaption></figure><h4><strong>Creating and Connecting with the API</strong></h4><p>Today we will be using rapidapi as an API service provider therefore you will need to visit <a href="https://rapidapi.com/">https://rapidapi.com/</a> and create an account.</p><p>After successfully creating an account you will have to subscribe to the API paraphraser1 for free by visiting <a href="https://rapidapi.com/vidanov-PTkl1skiJB3/api/paraphraser1">https://rapidapi.com/vidanov-PTkl1skiJB3/api/paraphraser1</a></p><p>After that process, come back to the vscode and create a folder name apis inside the src folder, then now create a file name Api.js and open the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*PWXkkYsE0EYT18lcF_uAJg.png" /><figcaption>image by author</figcaption></figure><p>In this file, we will make a connection with our API, using the following code.</p><pre>import axios from &#39;axios&#39;<br><br>const Api = async text =&gt; {<br>    const options = {<br>        method: &#39;POST&#39;,<br>        url: &#39;https://paraphraser1.p.rapidapi.com/&#39;,<br>        headers: {<br>          &#39;content-type&#39;: &#39;application/json&#39;,<br>          &#39;X-RapidAPI-Key&#39;: &#39;YOUR_API_KEY_HERE&#39;,<br>          &#39;X-RapidAPI-Host&#39;: &#39;paraphraser1.p.rapidapi.com&#39;<br>        },<br>        data: {<br>          input: text<br>        }<br>    }<br>    try {<br>        const response = await axios.request(options)<br>        console.log(response.data)<br>        return response.data<br>    } catch (err) {<br>        console.log(err)<br>    }<br>}<br><br>export default Api</pre><p>Next import this file inside the app.js file, and let&#39;s start calling the API and collecting data from it.</p><p>Importing the API</p><pre>import Api from &#39;./Apis/Api</pre><p>We will call the API inside the handleclick function and also we will update the data at the same time. So let’s update that function as the following.</p><pre>    const handleClick = async input =&gt; {<br>        setLoading(true)<br>        const res = await Api(input)<br>        <br>        setLoading(false)<br>        SetResult(res.output) <br>        Setsimilarity(res.similarity) <br> <br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*iHRZsehLJ-k5tDeXVs6sUQ.png" /><figcaption>image by author</figcaption></figure><p>Now the application must work as we expected. Without any errors and must Paraphrase the text.</p><p><strong>Hoooorayyyy</strong>. We have completed our first idea...</p><h4><strong>Conclusion</strong></h4><p>I hope you have earned great knowledge from this post, this is a very simple app in general in the future we will be building more advanced apps as I get more ideas from the readers.</p><p><strong>You can share your ideas with me here at:</strong> <a href="https://www.instagram.com/nafiu.dev"><strong>https://www.instagram.com/nafiu.dev</strong></a></p><p><strong>link to the GitHub repo</strong>: <a href="https://github.com/nafiu-dev/react_parapharaser_saas">https://github.com/nafiu-dev/react_parapharaser_saas</a></p><p>Thank you for reading.</p><p><strong>you can connect with me here:</strong></p><p><a href="https://www.instagram.com/nafiu.dev">https://www.instagram.com/nafiu.dev</a></p><p>Linkedin:<a href="https://www.linkedin.com/in/nafiu-nizar-93a16720b"> https://www.linkedin.com/in/nafiu-nizar-93a16720b</a></p><p><strong>My other posts:</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/awesome-web-development-projects-that-i-have-created-which-you-can-also-try-443ab0b1229c">Awesome web development projects that I have created, which you can also try</a></li><li><a href="https://medium.com/@nafiu.dev/building-an-advanced-backend-api-from-scratch-using-node-js-f26ed5c7092c">Building an advanced backend API from scratch using Node.js;</a></li></ul><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><em>.</em></p><p><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a>, <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a><em>, </em><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a><em>, and </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23659f37c2e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/create-a-text-paraphrasing-saas-tool-using-react-e23659f37c2e">Create a Text Paraphrasing SaaS Tool Using React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Awesome web development projects that I have created, which you can also try]]></title>
            <link>https://medium.com/@nafiu.dev/awesome-web-development-projects-that-i-have-created-which-you-can-also-try-443ab0b1229c?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/443ab0b1229c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 10:17:29 GMT</pubDate>
            <atom:updated>2023-04-07T10:17:29.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X1cqIb93Te64j8zL" /><figcaption>Photo by <a href="https://unsplash.com/@f12r?utm_source=medium&amp;utm_medium=referral">Fahim Muntashir</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Hi everyone</strong>, this post is going to be a little different, in this post I will go through some of the amazing web development projects that I have built throughout the past couple of years and explain those projects so that you can build your own amazing projects like such.</p><p><strong>Table of contacts</strong></p><p><a href="#25d0"><strong>App 1 — Painting web app</strong></a><strong><br></strong><a href="#3dde"><strong>App 2 — Job listing platform</strong></a><strong><br></strong><a href="#6ee8"><strong>App 3 — Information gathering tool</strong></a><strong><br></strong><a href="#e52d"><strong>App 4 — Banking platform</strong></a><strong><br></strong><a href="#20d6"><strong>App 5 — Keyword searching tool</strong></a><strong><br></strong><a href="#85d9"><strong>App 6 — sticker generating tool</strong></a><strong><br></strong><a href="#f00e"><strong>App 7 — B2C E-commerce platform</strong></a><strong><br></strong><a href="#2602"><strong>Conclusion</strong></a><strong><br></strong><a href="#1c75"><strong>Host your web app for free</strong></a><strong><br></strong><a href="#3198"><strong>Connect with me</strong></a></p><p>Before we go through the projects let me mention that I will give a good description of how each of these projects works and what stack has been used to create these projects. I will also provide a demo working video of the projects with the source code of it.</p><p><strong>Let’s get started…:)</strong></p><h4><strong>Pintor.app — App 1</strong></h4><p>Pintor is a web-based simple painting app created for simple drawings and planning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9Sv5R-YWUp8ZebLTxbLog.png" /><figcaption>Image by author</figcaption></figure><p>The project is built using react.js and fabrics, as a programming language I only used javascript throughout the whole project additionally HTML and CSS were also used to structure and design the application.</p><p>The application has great amount features, where users will be able to add shapes, text, and images to the canvas. Also, the app has a free drawing feature and also allows user to create their own shapes like photoshop which is really cool.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7ewCU1hfrGc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7ewCU1hfrGc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7ewCU1hfrGc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d99a034bb23b07e87ceb905971b95ef/href">https://medium.com/media/7d99a034bb23b07e87ceb905971b95ef/href</a></iframe><p>App: <a href="https://pintor.app/">https://pintor.app</a></p><p>Can’t provide code for this application since it’s in production.</p><h4><strong>Hire — App 2</strong></h4><p>Hire is a web-based job listing platform where users can search for a favorite job and apply for it, and companies can sign up for the platform and post their job vacancies on the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ZGx7NLmd46TXEGYaPqyHw.png" /><figcaption>Image by author</figcaption></figure><p>This platform is built using the MERN stack. This application has amazing features such as a search function, authentication function, and CRUD functions.</p><p>Users can search for jobs without signing up. But the user must sign up to see job details in order to apply. Also, companies must sign up to post their available jobs on the platform.</p><p><strong>Tech</strong>: Javascript,MongoDB, Nodejs, reactjs, JWT, bootstrap</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjrW0CyayrTk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjrW0CyayrTk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjrW0CyayrTk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e88a5387f1603dd4bf9b2f6bce9542ce/href">https://medium.com/media/e88a5387f1603dd4bf9b2f6bce9542ce/href</a></iframe><p><strong>Source code:</strong> <a href="https://github.com/nafiu-dev/hire">https://github.com/nafiu-dev/hire</a></p><h4><strong>Sheld — App 3</strong></h4><p>Sheld is a web-based network scanning tool that allows users to scan targeted IP addresses or domains to gather information about the targeted IP address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2uENDrvKdDRHlooBfRppQ.png" /><figcaption>Image by author</figcaption></figure><p>The platform is created using the Django web framework and with the help of some Linux tools. This application has functionalities such as scanning for opened port numbers, tracking network routes, nslookup, checking for domain information, and more.</p><p>After the user visits the platform user is allowed to log in to try the tools online. After logging in user will be able to perform information-gathering tasks online on this platform.</p><p><strong>Tech</strong>: python, javascript, Django, Linux, Bootstrap, Nmap</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5wZX-ebueFY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5wZX-ebueFY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5wZX-ebueFY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6821bfec5120cb078e786643cc38d7c7/href">https://medium.com/media/6821bfec5120cb078e786643cc38d7c7/href</a></iframe><p><strong>Source code:</strong> <a href="https://github.com/nafiu-dev/sheld-security">https://github.com/nafiu-dev/sheld-security</a></p><h4><strong>Laari — App 4</strong></h4><p>Web-based banking platform where users can create accounts per request and users will be able to login to those accounts and transfer money between accounts using their account number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hS_5DOE7LXiYj9gVNAcL3A.png" /><figcaption>Image by author</figcaption></figure><p>The platform is created using Django, Django-rest-framework, and reactjs. Users will be able to log in to their account and check their money balance and transfer history also user will be able to view the price of the currencies and send a messaging to the bank (platform admin) for any problems if needed.</p><p><strong>Tech:</strong> python, javascript, Django, Django-rest-framework, reactjs, CSS</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FH9SXMiA9i58%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DH9SXMiA9i58&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FH9SXMiA9i58%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/52fb2eae13434abb2885bb2387ac636e/href">https://medium.com/media/52fb2eae13434abb2885bb2387ac636e/href</a></iframe><p><strong>Source code:</strong> <a href="https://github.com/nafiu-dev/bankapp-laari">https://github.com/nafiu-dev/bankapp-laari</a></p><h4><strong>Scan — App 5</strong></h4><p>web-based web scraping tool that looks for the best keywords and also checks the site&#39;s performance, accessibility, SEO, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4f8U2Hk9Fxt32sIz1Vuffg.png" /><figcaption>Image by author</figcaption></figure><p>The platform is created using Nodejs and reactjs with advanced web scrapping skills and tools.</p><p>In this platform users can extract keywords from a targeted domain or also scan for keywords by giving a reference keyword, also if the user provides a domain name then the platform will check for the targeted site&#39;s performance, accessibility, and SEO and will provide information about it accordingly. And will also extract subdomains from the targeted site.</p><p><strong>Tech</strong>: Nodejs,MongoDB, Expressjs Reactjs, CSS</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWUiIpAsBbv4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWUiIpAsBbv4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWUiIpAsBbv4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f5aafb5686fb93828285bd6b1399aaf/href">https://medium.com/media/6f5aafb5686fb93828285bd6b1399aaf/href</a></iframe><p><strong>Source code:</strong> <a href="https://github.com/nafiu-dev/scan-seo">https://github.com/nafiu-dev/scan-seo</a></p><h4><strong>Sticker — App 6</strong></h4><p>Web-based stacker generating tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1A7v0DhospCxjl9f-OwRFQ.png" /><figcaption>Image by author</figcaption></figure><p>The app has fixed designed shapes of the stickers that users can select and upload an image to it and generate a sticker as a selected shape.</p><p><strong>Tech</strong>: Reactjs, fabricjs, CSS</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfscRfD8K7gs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfscRfD8K7gs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfscRfD8K7gs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3357e96764c2db489ec3d8a8fe614136/href">https://medium.com/media/3357e96764c2db489ec3d8a8fe614136/href</a></iframe><p><strong>Source code:</strong> <a href="https://github.com/nafiu-dev/sticker">https://github.com/nafiu-dev/sticker</a></p><h4><strong>Catch — App 7</strong></h4><p>Catch is a secure and fully functional e-commerce website where users can log in as a seller or as a customer and buy or sell products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhKoS6yuNna5f8q0JQDjNw.png" /><figcaption>Image by author</figcaption></figure><p>This platform is created in Nodejs. The platform has great functionalities such as authentication, image upload, cart function, pagination, and more.</p><p>Users can view products, and add products to their cart or their list of favorites. Users must log in to check out from the cart. Sellers must log in to the platform before posting any products on the platform.</p><p><strong>Tech</strong>: Nodejs, ExpressJS, Ejs, passports</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FX-rQrxTLf3Q&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DX-rQrxTLf3Q&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FX-rQrxTLf3Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/39c5bcd8ad98293a1792279e51fe3cb4/href">https://medium.com/media/39c5bcd8ad98293a1792279e51fe3cb4/href</a></iframe><p><strong>Source code:</strong> <a href="https://github.com/nafiu-dev/catch">https://github.com/nafiu-dev/catch</a></p><h4><strong>Overall</strong></h4><p>Above listed are some of the web applications that I have created in the past couple of years. You can explore more on my GitHub page.</p><h4><strong>Host your website</strong></h4><p>Get your website up and running easily using Bluehost for free. weather if it’s a SAAS app or even if it&#39;s a blog or any other kind of information-sharing website, you can deploy it easily using Bluehost.</p><blockquote>For me, the best part of Bluehost is its great performance, unbeatable support, user-friendly interface, and popularity which made it very easy to find the kind of solution I want the way I wanted it.</blockquote><p><strong>Use the following link to start for FREE:</strong> <a href="https://bluehost.sjv.io/nf-5gbEon">https://bluehost.sjv.io/nf-5gbEon</a></p><p><strong>you can connect with me here:</strong></p><p><strong>Instagram</strong>: <a href="https://www.instagram.com/nafiu.dev">https://www.instagram.com/nafiu.dev</a></p><p><strong>Linkedin</strong>:<a href="https://www.linkedin.com/in/nafiu-nizar-93a16720b"> https://www.linkedin.com/in/nafiu-nizar-93a16720b</a></p><p><strong>My other posts:</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/end-to-end-full-stack-project-from-backend-frontend-and-machine-learning-to-ethical-hacking-series-3e53779e5aff">End to End full stack project from backend, frontend and machine learning to ethical hacking series.</a></li><li><a href="https://pub.towardsai.net/youtube-dislikes-prediction-in-real-time-working-with-a-combination-of-data-a-practical-guide-fb7e88b0b445">Youtube dislikes prediction in real-time — working with a combination of data; a practical guide</a></li><li><a href="https://medium.com/@nafiu.dev/highlighting-the-most-popular-machine-learning-algorithms-implementing-it-4bf18b645163">Highlighting the most popular machine learning algorithms; Implementing it</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=443ab0b1229c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Youtube dislikes prediction in real-time — working with a combination of data; a practical guide]]></title>
            <link>https://pub.towardsai.net/youtube-dislikes-prediction-in-real-time-working-with-a-combination-of-data-a-practical-guide-fb7e88b0b445?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb7e88b0b445</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[youtube]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[lstm]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Fri, 23 Dec 2022 20:01:28 GMT</pubDate>
            <atom:updated>2022-12-23T20:01:28.732Z</atom:updated>
            <content:encoded><![CDATA[<h3>YouTube Dislikes Prediction in Real-time — Working With a Combination of Data; A Practical Guide</h3><p><strong>Hi everyone</strong>, this is a practical guide to a fascinating topic; today, we will discuss how you can work with a combination of mixed data. Well, we have all gone through it when we go through a dataset, and there are features with different data types and wonder how we can combine both types and use them for training a single machine learning model. Well, today, you have the simple guided answer for that. Also, to make things interesting, we will train a machine-learning model that predicts youtube dislikes in real-time. It&#39;s no surprise anymore that youtube removed its dislike count feature a year ago, maybe I’m even a little late to solve this problem, but the dataset we are using today is for sure gonna fulfill our needs of learning for today. Remember that since youtube dislike is a number, we are solving a <strong>regression problem</strong>. 🙂</p><p><strong>Table of contents</strong></p><ol><li><a href="#cf4c">Loading data</a></li><li><a href="#ecae">Data pre-processing</a></li><li><a href="#66e8">Modeling and training</a></li><li><a href="#7647">Evaluation</a></li><li><a href="#e52c">Real-time prediction</a></li></ol><p><strong>What you will learn</strong></p><ul><li>Work with mixed data</li><li>Clean text data</li><li>Process both text and numeric data</li><li>Keras TensorFlow functional API</li><li>LSTM (RNN)</li><li>To create a model that processes different types of data at once</li><li>how to check the accuracy of a regression model</li><li>Youtube API</li></ul><p><strong><em>Reality</em></strong><em>: in youtube, the amount of views, likes, and dislikes that a video can get depends on a lot of things, such as the popularity of the creator, the quality of the video, SEO, user shares, and a lot of other thighs which goes beyond the dataset available for us. Anyways let’s try to get the best out of what we have 😁</em></p><p><strong><em>Note:</em></strong><em> throughout this tutorial, I will be mentioning what and how you can do to improve this model and the things I have missed while creating this if I missed anything. And when it comes to adding libraries, we will be adding as we need instead of importing all of them once</em></p><p><strong>Let’s get started…</strong></p><p>You can get the dataset at <a href="https://www.kaggle.com/datasets/dmitrynikolaev/youtube-dislikes-dataset">https://www.kaggle.com/datasets/dmitrynikolaev/youtube-dislikes-dataset</a></p><p>Please download the dataset and extract it in your working directory. This dataset is a mixed language dataset of 37422 unique raws we are gonna shorten it down to only English language by using the video ids provided with the dataset, which makes our dataset 15835 unique raws in total before processing. This is actually a very short amount of data to solve a problem like this, try to increase the amount of data by processing other languages, too which will surely help to increase model accuracy.</p><p><strong><em>Note:</em></strong><em> This dataset was last updated on 13/12/2021 so we will assume that is the date that this data was extracted since we will use this data to deal with the time period</em></p><h4><strong>Load the dataset and collect the features we need</strong></h4><p>Hope you have the .csv file in your working directory, well let’s load it using pandas and shorten it down to only English and get more details of the available features from the dataset.</p><p>Import some libraries to get started</p><pre>import numpy as np<br>import pandas as pd<br>import tensorflow as tf</pre><p>Loading the dataset</p><pre>dataset = pd.read_csv(&#39;youtube_dislike_dataset.csv&#39;)<br>dataset.head()</pre><p>Collecting only English data</p><pre>file_US_ids = open(&quot;video_IDs/unique_ids_US.txt&quot;, &quot;r&quot;)<br>US_ids = file_US_ids.read().splitlines()<br>dataset = dataset[dataset[&#39;video_id&#39;].isin(US_ids)]<br>dataset.shape </pre><p>Checking more details of the dataset, such as the data types of the features</p><pre>dataset.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*PrAfLbrGE9pULzZirmn4YA.png" /><figcaption>image by author</figcaption></figure><p>The dataset contains 12 features. We only will use 7 features from these. These features are described below:</p><p><strong>Video_id:</strong> unique video id<br><strong>Title:</strong> title of the youtube video<br><strong>Channel_id: </strong>channel id of the publisher<br><strong>Channel_title:</strong> name of the channel<br><strong>Published_at:</strong> the date that the video was published<br><strong>View_count:</strong> Number of views that video got in a period of time<br><strong>Likes:</strong> Number of likes that video has<br><strong>Dislikes:</strong> Number of dislikes that video got in a period of time<br><strong>Comment_count:</strong> Number of comments that the video has<br><strong>Tags</strong>: video tags as strings<br><strong>Description:</strong> Video description<br><strong>Comments:</strong> list of video comments as a string</p><p>Well, there you have all the features available, now let’s select some of them which we will use in this practical guide.</p><p>We will be using the following 7 features:<br><em>view_count, published_at, likes, comment_count, tags, description, dislikes</em></p><pre>dataset = dataset[[&#39;view_count&#39;, &#39;published_at&#39;,&#39;likes&#39;, &#39;comment_count&#39;,&#39;tags&#39;,&#39;description&#39;,&#39;dislikes&#39;]]</pre><p>We will create one more feature and also will get rid of one feature from here in the pre-processing stage. Honestly, using the title and channel name would be a great improvement for the model, you can try it. 🙂</p><h4>Data pre-processing</h4><p>Let’s get started with processing data, in this stage, we do a lot of important things to our datasets such as dealing with missing values, creating related time fields, and cleaning and tokenizing text data. Let me explain more while doing it.</p><p><strong>Dealing with missing values</strong></p><p>The dataset is quite tricky if you just look for missing values (<strong>nan</strong>) you will not find anything this is because in a way the dataset doesn’t have any missing values since all the fields are filled with an empty string, so handle this case we will check for empty strings fields that don’t have a word in it and convert it into a <strong>nan</strong> value and check again, I’m sure we will get a good amount of null values now. And guess what? We will drop them all, this will make our dataset shot to 13536 raws in total, which is pretty small 😂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*BZ4OV_GVK1Dr2cElB1e_7Q.png" /><figcaption>image by author</figcaption></figure><p><strong>Creating a new feature — dealing with time</strong></p><p>Above, I mention that we are going to assume that the data was extracted on 13/12/2021, well, this is the time that date comes into play.</p><p>We are gonna create a new feature named <strong>timesec</strong> by calculating the amount of time between the date that the video was published and the time it was extracted in minutes.</p><p>So basically: <em>timesec = extracted date - published_at date</em></p><p>First, we will write a function to calculate the time between two points in minutes and use the pandas apply method to create the new feature.</p><p>Function to calculate the time between:</p><pre>from datetime import datetime<br>def calTime(time):<br>  start = datetime.strptime(time, &#39;%Y-%m-%d %H:%M:%S&#39;)<br>  end =   datetime.strptime(&#39;13/12/2021 00:00:00&#39;, &#39;%d/%m/%Y %H:%M:%S&#39;) # assuming this is the date that this dataset was extracted<br>  return np.round((end - start).total_seconds() / 60, 2)</pre><p>Using pandas apply method to run the function and create the new feature</p><pre>dataset[&#39;timesec&#39;] = dataset[&#39;published_at&#39;].apply(calTime)</pre><p><strong>Cleaning the text features</strong></p><p>We will create a function to clean our text data followed by a set of steps that will get the right and important meaning out of it.</p><p>Basically, the function will remove any unnecessary URLs, punctuation marks, numbers, stopwords, and random words that are not in the dictionary will be removed. It will also deal with contractions words and will lemmatize words and at last, will convert all to lowercase and return the processed string. We will do this with help of a bunch of libraries so let’s get started by importing those.</p><p>Importing the required libraries for this</p><pre>import re<br>from string import punctuation <br>from bs4 import BeautifulSoup<br>import nltk<br>nltk.download(&#39;stopwords&#39;)<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;omw-1.4&#39;)<br>nltk.download(&#39;words&#39;)<br><br>from nltk.corpus import stopwords<br>from nltk.stem import WordNetLemmatizer</pre><p>The contraction word dictionary will help to convert a combination of two words to their separate root word. (this is not all, there are more)</p><pre>contraction_map={<br>    &quot;ain&#39;t&quot;: &quot;is not&quot;,<br>    &quot;aren&#39;t&quot;: &quot;are not&quot;,<br>    &quot;can&#39;t&quot;: &quot;cannot&quot;,<br>...<br>}</pre><p>The function we created to clean text</p><pre><br>lemmatizer = WordNetLemmatizer()<br>in_words = set(nltk.corpus.words.words())<br>def clean_text(text):<br>    text = str(text)<br>    text = BeautifulSoup(text, &quot;lxml&quot;).text<br>    text = re.sub(r&#39;\([^)]*\)&#39;, &#39;&#39;, text)<br>    text = re.sub(&#39;&quot;&#39;,&#39;&#39;, text)<br>    text = &#39; &#39;.join([contraction_map[t] if t in contraction_map else t for t in text.split(&quot; &quot;)])<br>    text = re.sub(r&quot;&#39;s\b&quot;,&quot;&quot;,text)<br>    text = re.sub(&quot;[^a-zA-Z]&quot;, &quot; &quot;, text)<br>    text = &quot; &quot;.join(w for w in nltk.wordpunct_tokenize(text) if w.lower() in in_words or not w.isalpha())<br><br>    text = [word for word in text.split( ) if word not in stopwords.words(&#39;english&#39;)]<br>    text = [lemmatizer.lemmatize(word) for word in text]<br>    text = &quot; &quot;.join(text)<br>    text = text.lower()<br>    return text</pre><p>At last creating two new columns with cleaned text after running the function</p><pre>%time dataset[&#39;clean_description&#39;] = dataset[&#39;description&#39;].apply(clean_text)<br>%time dataset[&#39;clean_tags&#39;] = dataset[&#39;tags&#39;].apply(clean_text)</pre><p><strong>Splitting data</strong></p><p>Since we are using different datatypes it&#39;s not ideal to use the usual train_test_split function so we will start by splitting data by train and test with the help of slicing after that we will separate X and Y from both train and test data, then will separate the text and numerical features, we will keep both tags and description separate but will keep all the numeric features as one. This might be confusing anyway let’s see the code, which will make things clear.</p><p><strong><em>Note:</em></strong><em> Y is the dislike feature and our target variable. And X would be the view_count, likes, comment_count, timesec, clean_tags, clean_description. We don’t need the published_at feature.</em></p><p>Slicing to train and test</p><pre># Slicing to train and test<br>dataset_train = dataset.iloc[:12500,:]<br>dataset_test = dataset.iloc[12501:,:]<br><br># Creating X and Y variables of train dataset<br>X_train = dataset_train.loc[:, dataset.columns != &#39;dislikes&#39;]<br>Y_train = dataset_train[&#39;dislikes&#39;].values<br><br>#Creating X and Y variables of the test dataset<br>X_test = dataset_test.loc[:, dataset.columns != &#39;dislikes&#39;]<br>Y_test = dataset_test[&#39;dislikes&#39;].values<br><br># Splitting and organizing the features of train data<br>X_train_numaric = X_train[[&#39;view_count&#39;, &#39;likes&#39;, &#39;comment_count&#39;, &#39;timesec&#39;]].values<br>X_train_tags = X_train[&#39;clean_tags&#39;].values<br>X_train_desc = X_train[&#39;clean_description&#39;].values<br><br># Splitting and organizing the features of the test data<br>X_test_numaric = X_test[[&#39;view_count&#39;, &#39;likes&#39;, &#39;comment_count&#39;, &#39;timesec&#39;]].values<br>X_test_tags = X_test[&#39;clean_tags&#39;].values<br>X_test_desc = X_test[&#39;clean_description&#39;].values<br></pre><p><strong>Text tokenization — processing text</strong></p><p>Here we are gonna create a function to tokenization function to process our text features. The function will create a tokenizer and tokenize words and will add padding of 100 to it and will return a set of useful information such as processed test and train data, the number of max words, the vocabulary and the size of it, and the tokenizer itself that we will use later to make real-time predictions.<br>We will have to use this on both tags and description features as well.</p><p>Let’s get to the code. 🙂</p><p>Importing required libraries for this</p><pre>from tensorflow.keras.preprocessing.text import Tokenizer <br>from tensorflow.keras.preprocessing.sequence import pad_sequences</pre><p>The function to do the processing</p><pre>def Tokenizer_func(train,test, max_words_length=0, max_seq_len=100):<br>    tokenizer = Tokenizer()<br>    tokenizer.fit_on_texts(train)<br>    <br>    max_words = 0<br>    if max_words_length &gt; 0:<br>        max_words = max_words_length<br>    else:<br>        max_words = len(tokenizer.word_counts.items())<br><br>    tokenizer = Tokenizer(num_words=max_words)<br>    tokenizer.fit_on_texts(train)<br><br>    train_sequences = tokenizer.texts_to_sequences(train)<br>    test_sequences = tokenizer.texts_to_sequences(test)<br>    <br>    train = pad_sequences(train_sequences,maxlen=max_seq_len, padding=&#39;post&#39;)<br>    test = pad_sequences(test_sequences,maxlen=max_seq_len, padding=&#39;post&#39;)<br>    <br>    voc = tokenizer.num_words +1<br>    return {&#39;train&#39;: train, &#39;test&#39;: test, &#39;voc&#39;: voc, &#39;max_words&#39;:max_words, &#39;tokenizer&#39;: tokenizer}</pre><p>Calling the function for tags</p><pre>X_tags_processed = Tokenizer_func(X_train_tags,X_test_tags)<br># Extracting data from it…<br>X_train_tags,X_test_tags,x_tags_voc,x_tags_max_words,x_tag_tok = X_tags_processed[&#39;train&#39;], X_tags_processed[&#39;test&#39;],X_tags_processed[&#39;voc&#39;],X_tags_processed[&#39;max_words&#39;],X_tags_processed[&#39;tokenizer&#39;]</pre><p>Calling the function for description</p><pre>X_desc_processed = Tokenizer_func(X_train_desc,X_test_desc)<br># Extracting data from it…<br>X_train_desc, X_test_desc,x_desc_voc,x_desc_max_words,x_desc_tok = X_desc_processed[&#39;train&#39;], X_desc_processed[&#39;test&#39;],X_desc_processed[&#39;voc&#39;],X_desc_processed[&#39;max_words&#39;],X_desc_processed[&#39;tokenizer&#39;]</pre><p>Well, we have one more thing to do before ending the processing step of this tutorial.</p><p><strong>Numeric data normalization</strong></p><p>For this, we will use the StandardScaler to normalize both train and test data. Well, let’s see the code.<br>Importing the libraries, Creating the Scaler, and processing numeric data using it</p><pre>from sklearn.preprocessing import StandardScaler<br>Sc = StandardScaler()<br>X_train_numaric = Sc.fit_transform(X_train_numaric)<br>X_test_numaric = Sc.transform(X_test_numaric)</pre><p><strong>Yay..</strong> we are halfway done… this is the end of data preprocessing. 🎉🎉🎉</p><h4>Creating the Model and Training</h4><p>Here we will be using Keras functional API to create a machine-learning model we will be building a type of an RNN known as LSTM to process text data and later connected it to an MLP with the numeric data. I’m not gonna explain LSTM here since I have already gone through it in a previous post which is linked here…</p><p><a href="https://medium.com/@nafiu.dev/stock-market-prediction-using-lstm-will-the-price-go-up-tomorrow-practical-guide-d1df2d54a517">Stock market prediction using LSTM; will the price go up tomorrow. Practical guide</a></p><p><strong>Allow me to explain our model here:</strong></p><p>We have 3 inputs in the model: tags input, description input which has an input shape of none, and numeric which has an input size of 4 since we have 4 numeric features. Both tags and description starts with an embedding layer and then with two LSTM layer with units of 100 (remeber we added 100 as padding) followed by a normalization layer after each LSTM later. For both features, the first LSTM layer will have a dropout of 0.2 and return sequence set to true, and the second layer comes with a dropout of 0.4 and return sequence set to false. After passing through those layers both tags and description are combined with numeric data input and then passed through 4 dense layers with the units of 256,128,32, and 1, the first 3 layers with <strong>relu</strong> activation function and the last layer with a linear activation function (coz the problem is regression). Next, the whole model is compiled using <strong>model.compile() </strong>method, set as mean_squared_error as a loss function and mean_absolute_error as a matric and adam as an optimizer, as adam functions learning rate decreased to 0.001. Then finally we can view the summary of the model by using <strong>model.summary() </strong>method.</p><p>Let&#39;s view the code…</p><p>Import required libraries for this.</p><pre>from keras.models import Model<br>from tensorflow.keras.layers import Input, LSTM, Embedding, Dense, concatenate,LayerNormalization<br>from keras.optimizers import Adam<br>from keras.callbacks import EarlyStopping</pre><p>Creating the model</p><pre>tagsInput = Input(shape=(None,), name=&#39;tags&#39;)<br>descInput = Input(shape=(None,), name=&#39;desc&#39;)<br>numaricInput = Input(shape=(4,), name=&#39;numaric&#39;)<br><br>tags = Embedding(input_dim=x_tags_voc,output_dim=8,input_length=x_tags_max_words)(tagsInput)<br>tags = LSTM(100,dropout=0.2, return_sequences=True)(tags)<br>tags = LayerNormalization()(tags)<br>tags = LSTM(100,dropout=0.4, return_sequences=False)(tags)<br>tags = LayerNormalization()(tags)<br><br>desc = Embedding(input_dim=x_desc_voc,output_dim=8,input_length=x_desc_max_words)(descInput)<br>desc = LSTM(100,dropout=0.2, return_sequences=True)(desc)<br>desc = LayerNormalization()(desc)<br>desc = LSTM(100,dropout=0.4, return_sequences=False)(desc)<br>desc = LayerNormalization()(desc)<br><br>combined = concatenate([tags, desc,numaricInput])<br>x = Dense(256,activation=&#39;relu&#39;)(combined)<br>x = Dense(128,activation=&#39;relu&#39;)(x)<br>x = Dense(32,activation=&#39;relu&#39;)(x)<br>x = Dense(1,use_bias=True,activation=&#39;linear&#39;)(x)<br>model = Model([tagsInput, descInput,numaricInput], x)</pre><p>Compiling the model</p><pre>model.compile(loss=&#39;mean_squared_error&#39;, optimizer=Adam(learning_rate=0.001, decay=0.001 / 20), metrics=[&#39;mae&#39;])</pre><p>Now let&#39;s see the summary of the model using model.sumary() method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*pkTp7ifq4eWyz1-b9Gzumw.png" /><figcaption>image by author</figcaption></figure><p>Now it&#39;s time to train our model. We will train our model under 500 epochs with a batch size of 25 and with a validation split of 2 percent, since we have the early stopping on it will probably be done training the model before it even comes close to 500 epochs.</p><p>Well, there is one more thing that we must do before starting to train our model. LSTM supports 3-dimensional data but our data is 2 dimensional so we must convert it into 3-dimensional data before we start training</p><p>Initializing EarlyStopping to avoid overfitting while training the model</p><pre>es = EarlyStopping(monitor=&#39;val_loss&#39;, mode=&#39;min&#39;, verbose=1, patience=20)</pre><p>Reshaping the data to 3-dimensional data</p><pre>X_train_tags = np.reshape(X_train_tags,(X_train_tags.shape[0],X_train_tags.shape[1],1))<br>X_train_desc = np.reshape(X_train_desc,(X_train_desc.shape[0],X_train_desc.shape[1],1))<br>X_train_tags.shape, X_train_desc.shape, X_train_numaric.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*jnNwGXZQvfDjcbhBNVj5Ng.png" /><figcaption>image by author</figcaption></figure><p>Training the model</p><pre>history = model.fit(<br>                    x=[X_train_tags, X_train_desc,X_train_numaric],<br>                    y=Y_train,<br>                    epochs=500, <br>                    batch_size=25,<br>                    validation_split=0.2,<br>                    verbose=1,<br>                    callbacks=[es]<br>                  )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*xKG_S1TsZpgkRGyoMEu2rQ.png" /><figcaption>image by author</figcaption></figure><p>Here we can see our model has stopped training once it reaches 26 epochs.</p><h4>Evaluating our model</h4><p>Now that our model has done training, it’s time to check the results but before that, let’s answer a simple question and understand a couple of important things.<br><strong>How to check the accuracy of a regression model?</strong></p><p><strong>Residuals</strong> — The difference between the predicted value and the actual value.</p><p><strong>Mean Absolute Error</strong> — the mean value of the residuals between predicted values and actual values.</p><ul><li>The lower the <strong>MAE </strong>the better the model is.</li><li><strong>MAE </strong>is calculated by adding residuals and dividing by the length of the dataset (test data)</li><li>Describes how close the predictions are to the actual values on average.</li></ul><p><strong>Mean Squared Error</strong> — shows how close a regression line is to a set of data points</p><p><strong>Root Mean Squared Error</strong> — is the square root of the mean of all the squared values of errors</p><ul><li>indicates the absolute fit of the model relative to the given data</li><li><strong>RMSE </strong>has a relationship with <strong>MAE</strong></li><li>If <strong>RMSE </strong>value is much higher than <strong>MAE</strong>, it means the results of some large errors in the dataset.</li></ul><p><strong>R-squared</strong> — shows how well the data fits into the model</p><ul><li>Outputs a value on a scale of 0 to 1</li><li>The higher the <strong>R2 </strong>the better the model is</li><li><strong>R2 </strong>score value can be used to get the accuracy of the model same as a classification model by multiplying the value * 100</li></ul><p><strong>Key points:</strong></p><ul><li><strong>R2 </strong>must be high</li><li>The lower <strong>MSE </strong>the better the model is</li><li>The lower <strong>MAE </strong>the better the model is</li><li>The lower <strong>RMSE </strong>the better the model is</li><li><strong>MAE </strong>should be lower then <strong>RMSE</strong></li></ul><p>Now let’s implement these in our project and see the model results. We can do this by using the following code</p><pre>pprydd = model.predict([X_test_tags, X_test_desc, X_test_numaric])<br>from sklearn import metrics<br>print(&quot;Mean Absolute Error (MAE) - Test data : &quot;, metrics.mean_absolute_error(Y_test, pprydd))<br>print(&quot;Mean Squared Error (MSE) - Test data : &quot;, metrics.mean_squared_error(Y_test, pprydd))<br>print(&quot;Root Mean Squared Error (RMSE) - Test data : &quot;, np.sqrt(metrics.mean_squared_error(Y_test, pprydd)))<br>print(&quot;Co-efficient of determination (R2 Score): &quot;, metrics.r2_score(Y_test, pprydd))</pre><p>We can see that our model has an<strong> R2</strong> score of 0.82 (82%) but also, we can see we have a very high <strong>MSE</strong> which is not a good sign 😥. And we can see both <strong>MAE </strong>and <strong>RMSE </strong>are pretty low compared to <strong>MSE, </strong>which is fine but the <strong>RMSE </strong>is higher than the <strong>MAE, </strong>which actually indicates the result of some errors in our dataset 🤕… not the best model in the world but in my opinion, this is not bad compare to the usable data we had.</p><p>Note: you can try improving the model by doing more research about this field, like what are the things that depend on while getting more dislike on videos and focus on that. Also, try using the features that we didn’t use in this tutorial… anyways, leys continue.</p><h4>Real-time prediction</h4><p>Now, the part we all have been waiting for to predict youtube dislike in real-time. For this, we will be using youtube API to get targeted video data by id and collect the required data from it and process it and run it through the model. To make things easy, we will write a function to make this all happen at once.<br>Let’s see the code. :)</p><p>Import the required library</p><pre>import googleapiclient.discovery</pre><p>Create youtube client</p><pre>DEVELOPER_KEY = &#39;YOUR_API_KEY&#39; <br>youtube_client = googleapiclient.discovery.build(&#39;youtube&#39;, &#39;v3&#39;, developerKey=DEVELOPER_KEY)</pre><p>Time to write the function. Let me explain how this works.<br>Once the data is received, we will extract the required fields from it</p><p>For both text fields, the text will be cleaned using the previously created cleaning function and then will be processed through the tokenizer we created earlier, and at last, the padding will be added to the text.</p><p>The timesec field will be calculated using the next function. Inside this function, it will get the time period between the date that the targeted video was published and today in minutes.</p><p>Next, all the numeric features will be passed through the Scaler for normalization. Once the processing is done, then we will predict the dislike of the video by passing through the model, and the function will return the predicted dislike number among some other useful information.</p><pre>def realtime(youtube,video_id):<br>  def calTimesss(time):<br>    start = datetime.strptime(time, &#39;%Y-%m-%dT%H:%M:%S%z&#39;)<br>    end =   datetime.now()<br>    return np.round((end - start.replace(tzinfo=end.tzinfo)).total_seconds() / 60, 2)<br>  request = youtube.videos().list(part=&quot;snippet, statistics&quot;,id=video_id)<br>  response = request.execute()<br><br>  desc = response[&#39;items&#39;][0][&#39;snippet&#39;][&#39;description&#39;]<br>  desc  =[clean_text(desc)]<br>  desc = x_desc_tok.texts_to_sequences(desc)<br>  desc = pad_sequences(desc,maxlen=100, padding=&#39;post&#39;)<br>  <br>  tags = response[&#39;items&#39;][0][&#39;snippet&#39;][&#39;tags&#39;]<br>  tags=(&quot; &quot;.join(tags))<br>  tags  =[clean_text(tags)]<br>  tags = x_tag_tok.texts_to_sequences(tags)<br>  tags = pad_sequences(tags,maxlen=100, padding=&#39;post&#39;)<br><br>  publishedAt = response[&#39;items&#39;][0][&#39;snippet&#39;][&#39;publishedAt&#39;]<br>  timesec = calTimesss(publishedAt)<br>  viewcount = response[&#39;items&#39;][0][&#39;statistics&#39;][&#39;viewCount&#39;]<br>  likeCount = response[&#39;items&#39;][0][&#39;statistics&#39;][&#39;likeCount&#39;]<br>  commentCount = response[&#39;items&#39;][0][&#39;statistics&#39;][&#39;commentCount&#39;]<br>  numaricdata = [[viewcount, likeCount,commentCount,timesec]]<br>  numaricdata = Sc.transform(numaricdata)<br><br>  pryd = model.predict([tags, desc, numaricdata])<br><br>  return {&quot;predicted&quot;: int(pryd[0][0]), &quot;info&quot;: {<br>      &quot;video_id&quot;: video_id,<br>      &quot;likes&quot;: likeCount,<br>      &quot;commentCount&quot;: commentCount,<br>      &quot;viewCount&quot;: viewcount,<br>      &quot;publishedAt&quot;: publishedAt,<br>      &quot;dislike&quot;: int(pryd[0][0]),<br>  }}</pre><p>Now let&#39;s run it, and let’s see the results…</p><pre>video_id = &quot;videoid&quot;<br>realtime(youtube_client, video_id)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*MWMPV3B89rpnB0v6UwQiog.png" /><figcaption>image by author</figcaption></figure><p><strong>Haha</strong>, it worked 😂 🎉. According to the model, this video has <em>1231</em> diskiles. <strong>Ouch</strong>, a lot of haters 😟</p><p>Well, this is the end of this tutorial about working with combination data, it was fun so hope you enjoyed it. Also hope you will try to improve this model… Keep learning 🙂</p><p><strong>link to GitHub repo</strong>:<a href="https://github.com/nafiu-dev/boolean_image_classifier_FAST-"> </a><a href="https://github.com/nafiu-dev/youtube_dislike_prediction_practice">https://github.com/nafiu-dev/youtube_dislike_prediction_practice</a></p><p><strong>you can connect with me here:</strong></p><p><a href="https://www.instagram.com/nafiu.dev">https://www.instagram.com/nafiu.dev</a></p><p><strong>Linkedin</strong>:<a href="https://www.linkedin.com/in/nafiu-nizar-93a16720b"> https://www.linkedin.com/in/nafiu-nizar-93a16720b</a></p><p><strong>My other posts:</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/end-to-end-full-stack-project-from-backend-frontend-and-machine-learning-to-ethical-hacking-series-3e53779e5aff">End to End full stack project from backend, frontend and machine learning to ethical hacking series.</a></li><li><a href="https://pub.towardsai.net/create-a-boolean-image-classifier-fast-with-any-data-set-with-a-brief-explanation-of-the-4b1265b5b33f">Create a Boolean Image Classifier Fast With Any Data Set, With a Brief Explanation of the…</a></li><li><a href="https://medium.com/@nafiu.dev/highlighting-the-most-popular-machine-learning-algorithms-implementing-it-4bf18b645163">Highlighting the most popular machine learning algorithms; Implementing it</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb7e88b0b445" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/youtube-dislikes-prediction-in-real-time-working-with-a-combination-of-data-a-practical-guide-fb7e88b0b445">Youtube dislikes prediction in real-time — working with a combination of data; a practical guide</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Boolean Image Classifier Fast With Any Data Set, With a Brief Explanation of the…]]></title>
            <link>https://pub.towardsai.net/create-a-boolean-image-classifier-fast-with-any-data-set-with-a-brief-explanation-of-the-4b1265b5b33f?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b1265b5b33f</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Mon, 28 Nov 2022 20:01:57 GMT</pubDate>
            <atom:updated>2022-11-28T20:01:57.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create a Boolean Image Classifier Fast With Any Data Set, With a Brief Explanation of the Convolutional Neural Network (CNN) With Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0szq0HU1Iem9ptvs" /><figcaption>Photo by <a href="https://unsplash.com/@ray30?utm_source=medium&amp;utm_medium=referral">ray rui</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Hi everyone</strong>, in this post, we are going to look at a type of neural network called the Convolutional Neural Network. Here we will learn how it works in detail and what you should consider when building it. And to make things interesting, we will train a machine-learning model and make predictions in real-time.</p><p><strong>Table of contents</strong></p><ul><li><a href="#0ea3">CNN overview</a></li><li><a href="#6c68">Prerequisites</a></li><li><a href="#7613">CNN architecture</a></li><li><a href="#f64e">Implementation</a></li></ul><p><strong>What you will learn</strong></p><ul><li>How CNN works</li><li>How to prepare images for training</li><li>How to implement a CNN</li></ul><h4><strong>CNN </strong>overview</h4><p>A Convolutional Neural Network, also known as a <strong>ConvNet</strong>, is a type of deep neural network designed for finding patterns in images, image recognition, and computer vision tasks. Although CNN&#39;s are specifically designed for processing images, they can also be used for classifying non-image data, such as audio data. However, in this post, we will focus on processing images with a CNN</p><h4><strong>Things you should be familiar with before diving deep into CNN</strong></h4><p><strong>1. Batch size<br></strong>Batch_size is the number of samples that will be spread through the network.<br>Eg: Imagine you have 160 training samples, and your batch size is 32. In this case, the network takes the first 32 samples from the training dataset (1st to 31st) and will train the network. Next, it will take the next set of samples (33rd to 65th) from the training dataset and will train the network. This process continues until all batches are processed and trained</p><p><strong>2. Input_shape<br></strong>The input shape contains 4 parameters; those are batch size, height, width and channels. The batch size, height, and width are selected in the image processing phase, where we resize the images and make some other necessary requirements for our dataset. The fourth parameter, “channels,” depends on the type of image we use. If we use grayscale images, the channel is 1, for RGB images it is 3, since an RGB image is represented as a 3D tensor.<br><strong>Imagine </strong>you are using RGB images and the size of the preprocessed image is 256, then the input_shape would look like this input_shape=(256,256,3), as you can see we have not specified a batch_size so we can use any batch_size when training the model. We will discuss this later when we build our model and go through the summary of the model.</p><p><strong>3. Filter<br></strong>The so-called feature detector is a grid matrix that moves over the image pixels and extracts features from the input image to create an output feature map. This feature map is the input for the next pooling layer. (We will get into more details about the pooling layer when we talk about the architecture.) There can be multiple filters in one convolutional layer, the size of the filters is specified in each layer, and the movement of the filters is described by <strong>Stride</strong>.</p><p><strong>4. Stride</strong><br>Is the number of steps that the filter will take across the input image in order to extract the feature<br><strong>Example:<br></strong>Imagine we have an input image of 6x6, and we selected the filter size to be 3x3 and the stride as 1. This means the 3x3 filter will move across the 6x6 image one pixel by pixel to form the output feature map. Let&#39;s visualize that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*zrBQc3N8EsTcSFyhYcBBFA.png" /><figcaption>image by author</figcaption></figure><p>This example is based on grayscale images. If the image is an RGB image, the filters should have 3 channels since RGB images are 3 channels deep and each filter will go through its corresponding channel and will create the output feature map by adding all of it to one.</p><p><strong>5. Padding<br></strong>Adds an additional outer layer of pixels of zeros to each side of the output feature map in order to maintain the feature map as same as the input image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*hle6OsE2fKCt6waqymJNJg.png" /><figcaption>image by author</figcaption></figure><p><em>We </em><strong><em>won’t</em></strong><em> be using padding when we implement our model, but let’s see how we can add padding to a convolution layer. The easiest way to add padding is by using “valid” and “same”, </em><strong><em>valid </em></strong><em>means no padding, and </em><strong><em>same </em></strong><em>means add padding.</em></p><p><strong>6. Sigmoid Activation function</strong><br>The sigmoid Activation function is used to add non-linearity to an ML model, in simple terms, it takes the real output number and transforms it into a range between 0 and 1.</p><p><strong>7. Relu Activation function</strong></p><p>The rectified linear unit known as <strong>Relu</strong>, the most popular nonlinear activation function used in deep-learning neural networks. This works by converting all the negative output values to the default value of 0 and retaining all the positive values to overcome the vanishing gradient problem, which also allows the models to learn faster.</p><h4><strong>CNN architecture</strong></h4><p>Let’s start with the types of layers that are involved while creating a CNN; normally a simple CNN would have 3 Layers which are: a convolution Layer, a pooling layer, and a fully connected layer, followed by a Flatten layer before the Dense layer and also an activation layer added to each convolution and Dense Layer. Let’s see what each of these layers does…</p><p><strong>Convolution Layer</strong></p><p>This is the main building block of CNN. There can be multiple convolution layers in a CNN. The first layer of the CNN must be a convolution layer. This layer will take images as input to begin the process. The main key point that we should consider while implementing this layer: is the input image shape, filter, and stride. We have already discussed this in the prerequisites part of this post but anyways, let’s brush it up.</p><ol><li><strong>Input image shape:<br></strong>Here you should consider the batch_size, width, height, and depth of the image since the depth of the image changes according to the type of image we use therefore, this parameter depends on the type of image we use.. <a href="#8db1"><strong>scroll up for more</strong></a></li><li><strong>filter<br></strong>There can be multiple filters/kernels in a single convolution layer therefore, you should describe the number of filters, the size of each filter, and the <strong>stride </strong>for each filter. Filters are used to scan through the image and extract important features. <a href="#6f94"><strong>scroll up for more</strong></a></li></ol><p>In simple terms, the purpose of this convolution layer is to extract the important features from images and creates the output feature map that needs to be fed into the pooling layer</p><h4><strong>Pooling layer</strong></h4><p>The second most important layer used in a CNN, the pooling layer, takes the <strong>feature map</strong> and passes it through another <strong>filter </strong>to reduce the dimensions of the feature map and generates a <strong>pooled feature map</strong> after extracting the most important features from the input feature map.</p><p><strong>Two types of pooling layers:</strong></p><p><strong>Max pooling:</strong><br>In max pooling, the filter will get the maximum element from the input feature map covered by a filter</p><p><strong>Average pooling:</strong><br>In Average pooling, the filter will calculate the average of the input feature map covered by a filter</p><p><strong>Example:</strong> imagine the input feature map is 4x4 and the size of the pooling filter is 2x2 (default) with default stride the output will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*yNsuRYrLOnjJuJNLfmBKCA.png" /><figcaption>image by author</figcaption></figure><h4><strong>Flatten layer</strong></h4><p>This layer converts the final pooled feature map into one dimension. In order to prepare the input for the next dense layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*y29n0OV5xPiWAhjxZnoAuA.png" /><figcaption>image by author</figcaption></figure><h4><strong>Dense Layer</strong></h4><p>There can be Dense multiple layers in a CNN. This layer uses the flattened feature map to extract detected features from it. The <strong>Relu </strong>activation function will be used in every dense layer except for the last one since it’s the layer that makes the final classification.</p><h4><strong>Connecting the dots</strong></h4><p>The CNN starts with a convolution layer. In fact, a CNN can have multiple convolution Layers each of these layers will be followed by a pooling layer. The first convolution layer will take the image as an input, and when the process begins, the job of the convolution and pooling layer is to extract important features from the image. Next comes the flattened layer, this is where the fully connected layer begins. The output from the last pooling layer will be fed into this layer to convert the last pooled feature map into one dimension of data which will then be passed through the Dense layer in order to classify images. There can be Dense multiple layers in a CNN also Relu activation is used in each convolution and Dense layer except for the final dense layer, where the softmax (or other) activation function will be used according to our needs.</p><h4><strong>Implementation</strong></h4><p>For demonstration, we are going to use the gender classification dataset from Kaggle, you can get it from here: <a href="https://www.kaggle.com/datasets/cashutosh/gender-classification-dataset">https://www.kaggle.com/datasets/cashutosh/gender-classification-dataset</a></p><p>Download and unzip the archive.zip file in the working directory. This dataset has two folders, Training and Validation; inside each of these folders, there are two more folders named male and female, which have many images according to the correct gender.</p><p>Here we will use the power of python programming to get those images, process them and create and train our model.</p><p><strong>Let’s get started.</strong></p><p><strong>Importing required libraries</strong></p><pre>import tensorflow as tf<br>import numpy as np<br>from tensorflow.keras.preprocessing.image import ImageDataGenerator<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout</pre><p><strong>Loading data and processing images</strong></p><p>To make things fast and easy, we will use the ImageDataGenerator API from TensorFlow to load and set up our dataset for training.</p><p>Set the batch size as 32 — <strong>explained here</strong></p><pre>BATCH_SIZE = 32</pre><p>initialize the ImageDataGenerator API. in the train dataset generator, we will set the validation split as 2%, which we will use later as a test dataset.</p><pre>TrainTest_Datagen = ImageDataGenerator(<br>      rescale=1./255,<br>      validation_split=0.2 # we will use this as test data<br>)<br>Validation_datagen = ImageDataGenerator(<br>    rescale=1./255,<br>) </pre><p>Call the API with the required information, such as the data directory, image size, batch_size, and class mode.<br>Set the image size as 256x256 and the class_mode as binary. Let’s see the code.</p><pre>train_data = TrainTest_Datagen.flow_from_directory(<br>    &#39;./Training&#39;,<br>    target_size=(256,256),<br>    batch_size=BATCH_SIZE,<br>    class_mode=&#39;binary&#39;,<br>    subset=&#39;training&#39;<br>)<br>Test_data = TrainTest_Datagen.flow_from_directory(<br>    &#39;./Training&#39;, <br>    target_size=(256,256),<br>    batch_size=BATCH_SIZE,<br>    class_mode=&#39;binary&#39;,<br>    subset=&#39;validation&#39;# set as test data<br>) <br>Val_data = Validation_datagen.flow_from_directory(<br>    &#39;./Validation&#39;,<br>    target_size=(256,256),<br>    batch_size=BATCH_SIZE,<br>    class_mode=&#39;binary&#39;,<br>)</pre><p>Check the target variables generated from the image generator</p><pre>train_data.class_indices</pre><p><strong>Modeling and Training</strong></p><p>We will use TensorFlow sequential API to create our model, well before we build it, lets discuss its architecture.</p><ul><li>Three convolution layers, with the number of filters increasing from 16, 32 to 64, and each layer with Relu activation function applied to it followed with Max pooling layer after each convolution layer. So Three Three convolution layers and Three pooling layers.</li><li>Next, flatten layer.</li><li>Two dense layers. First, one with 256 neurons with Relu activation function applied to it, and second has 1 neuron with sigmoid activation function applied to it</li></ul><p>Let’s see the code.</p><pre>model = Sequential([<br>    Conv2D(16, (3,3), 1, activation=&#39;relu&#39;, input_shape = (256,256,3)),<br>    MaxPooling2D(),<br><br>    Conv2D(32, (3,3), 1,  activation=&#39;relu&#39;),<br>    MaxPooling2D(),<br><br>    Conv2D(64, (3,3), 1,activation=&#39;relu&#39;),<br>    MaxPooling2D(),<br><br>    Flatten(),<br>    Dense(256, activation=&#39;relu&#39;),<br>    Dense(1, activation=&#39;sigmoid&#39;)<br>])</pre><p>Compile the model and view the summary.</p><pre>model.compile(optimizer=&quot;adam&quot;,loss=&#39;binary_crossentropy&#39;,metrics = [&#39;accuracy&#39;])<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*vGhERiKsa7l5qny8IsogSQ.png" /><figcaption>image by author</figcaption></figure><p>Train the model we will train our model under 20 epochs and 1175 steps per epoch for training datasets and 364 steps per epoch for validation datasets also we will use EarlyStopping to avoid overfitting while training the model.</p><pre>es = tf.keras.callbacks.EarlyStopping(monitor=&#39;val_loss&#39;, patience=5, verbose=1)<br>history = model.fit(<br>      train_data,<br>      steps_per_epoch=1175,<br>      epochs=20,<br>      validation_data = Val_data,<br>      validation_steps=364,<br>      callbacks=[es]<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*jgTMcmlHWmvSBU2nIdKNrg.png" /><figcaption>image by author</figcaption></figure><p>Here we can see our model has stopped training once it reaches the 8th epoch.</p><p><strong>Evaluating our model</strong></p><p>Here we will use our test dataset to evaluate our model and check its accuracy. The next piece of code does just that</p><pre>test_loss, test_acc = model.evaluate(Test_data, verbose=0)<br>print(&#39;\nTest accuracy:&#39;, np.round(test_acc * 100,3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*eemgaHjq_xf84B2dzvfL7g.png" /><figcaption>image by author</figcaption></figure><p>Well, we got 94.7% in accuracy, which is awesome.<br>But wait, how can we use this model in real-time?</p><p><strong>Real-time prediction</strong></p><p>First, let’s write a function to process our images and call the model and print out the results for us.</p><pre>def RealPredict(img_path):<br>  img_test = tf.io.read_file(img_path)<br>  img_test = tf.io.decode_jpeg(img_test , channels = 3)<br>  img_test = tf.image.resize(img_test , [256 , 256] , method=&quot;nearest&quot;)<br>  yhat = model.predict(np.expand_dims(img_test, 0))<br>  if yhat &lt; 0.5: <br>    print(f&#39;Predicted the person a female&#39;)<br>  else:<br>      print(f&#39;Predicted the person a male&#39;)</pre><p>Let’s run the function and see if we get the correct results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*Sgcm1TLr09k3kZHQDqWcnw.png" /><figcaption>Image by author</figcaption></figure><p><strong><em>Yay, Hooray</em></strong>,<em> our model works perfectly.. Well done</em></p><p>Well, this is the end of this tutorial about CNN and image classification, I hope you enjoyed it. Don’t forget to follow me since I will be posting great guided tutorials about machine learning and full-stack development.</p><p><strong>link to Github repo</strong>: <a href="https://github.com/nafiu-dev/boolean_image_classifier_FAST-">https://github.com/nafiu-dev/boolean_image_classifier_FAST-</a></p><p><strong>you can connect with me here:</strong></p><p><a href="https://www.instagram.com/nafiu.dev">https://www.instagram.com/nafiu.dev</a></p><p><strong>Linkedin</strong>: <a href="https://www.linkedin.com/in/nafiu-nizar-93a16720b">https://www.linkedin.com/in/nafiu-nizar-93a16720b</a></p><p><strong>My other posts:</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/end-to-end-full-stack-project-from-backend-frontend-and-machine-learning-to-ethical-hacking-series-3e53779e5aff">End to End full stack project from backend, frontend and machine learning to ethical hacking series.</a></li><li><a href="https://medium.com/@nafiu.dev/stock-market-prediction-using-lstm-will-the-price-go-up-tomorrow-practical-guide-d1df2d54a517">Stock market prediction using LSTM; will the price go up tomorrow. Practical guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b1265b5b33f" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/create-a-boolean-image-classifier-fast-with-any-data-set-with-a-brief-explanation-of-the-4b1265b5b33f">Create a Boolean Image Classifier Fast With Any Data Set, With a Brief Explanation of the…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an advanced backend API from scratch using Node.js;]]></title>
            <link>https://medium.com/@nafiu.dev/building-an-advanced-backend-api-from-scratch-using-node-js-5eccb35adbe6?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eccb35adbe6</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 16:19:59 GMT</pubDate>
            <atom:updated>2022-11-06T09:25:09.640Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building an advanced backend API from scratch using Node.js; CRUD, authentication — part 2 — Adding extra </strong>features</h3><h4>Hi all, welcome to the end to end full stack (backend, frontend) project with artificial intelligence and machine learning and ethical hacking series. In this post we are going to add additional features to our previously build backed API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*abBZXJw9ocX8n7XO" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the previous post we set up and built an advanced RESTFUL API using Node.js and at the end of the post I mention that we gonna add two more features to our API which is to allow users to add comment to a post and allowing them to upload images from local machine but instead of adding those two features, in this post we will be adding comment feather only, is to allow users to add comment to a targeted post. Same as before to make things easier let’s break down the process into parts and write it down in point form.</p><p><strong>Part one of backend development:</strong></p><p><a href="https://medium.com/@nafiu.dev/building-an-advanced-backend-api-from-scratch-using-node-js-f26ed5c7092c">Building an advanced backend API from scratch using Node.js;</a></p><p><strong>Link to series:</strong></p><p><a href="https://medium.com/@nafiu.dev/end-to-end-full-stack-project-from-backend-frontend-and-machine-learning-to-ethical-hacking-series-3e53779e5aff">End to End full stack project from backend, frontend and machine learning to ethical hacking series.</a></p><p><strong>What will you learn?</strong></p><ul><li>Create database schemas</li><li>Create different types of routes</li><li>Populate database Schemas using mongoose virtuals</li><li>Mongoose deep populate</li><li>Test an API</li></ul><p><strong>Features</strong> <strong>we going to implement:</strong></p><ul><li>Allow users to add a comment to a targeted post</li><li>Get comments with post (populate)</li><li>Get both posts, comments while requesting for a user</li></ul><p><strong>Steps you should follow:</strong></p><ul><li><a href="#88b3">Create comments data Schema</a></li><li><a href="#ecc9">Create route to add comment</a></li><li><a href="#1948">Update Post Schema with virtuals in order to populate comments</a></li><li><a href="#7fc2">Populate the required routes with comments (routes that get /posts)</a></li><li><a href="#44a2">Test the API</a></li><li><a href="#5108">Conclusion</a></li></ul><blockquote><strong>Note:</strong> Again I hope you have completed the previous post (part 1) since this is a follow up to it, you must have the API completed to that point. Saying that, let’s get started with this tutorial.</blockquote><h4><strong>Create comments data Schema</strong></h4><p>Create a file named <strong>Comment.js</strong> in the models folder. We are going to create a data schema inside this file. We going to have 3 data input fields which are:<br><strong>Postid</strong>: id of the post that you want to add the comment<br><strong>Userid</strong>: id of the user that posted the comment<br><strong>Comment</strong>: the comment (string)</p><p><strong>/models/Comment.js</strong></p><pre>const mongoose = require(&#39;mongoose&#39;);<br>let CommentSchema = new mongoose.Schema({<br>    PostId: {<br>        type: mongoose.Schema.Types.ObjectId,<br>        ref: &#39;post&#39;,<br>        required: true<br>    },<br>    UserId: {<br>        type: mongoose.Schema.Types.ObjectId,<br>        ref: &#39;user&#39;,<br>        required: true<br>    },<br>    comment: {<br>        type: String,<br>        required: true<br>    }<br>})<br>module.exports = mongoose.model(&#39;comment&#39;, CommentSchema)</pre><h4><strong>Create route to add comment</strong></h4><p>Open the features.js file inside routes folder here we will create a route to add a comment at the end of the file before exporting the router and also make sure you import the Comment Model to the top of features file. (same way as you imported other models)</p><p><strong>/post/comment/:id</strong>: POST request that will take a comment as a string and add to the database with the id of the targeted post and the id of the logged in user. Id of the post is the ‘:id’ in the URL.</p><p><strong>/routes/features.js</strong></p><pre>// GET | /api/v1/post/comment/:id| Private | add a comment to a post<br>router.post(&#39;/post/comment/:id&#39;, verifyAuth,async (req, res) =&gt; {<br>    try {<br>        const comment = await Comment.create({<br>            PostId: req.params.id,<br>            comment: req.body.comment,<br>            UserId: req.user.id,<br>        })<br>        if (!comment) {<br>            return res.status(400).json({<br>                success: false<br>            })<br>        }</pre><pre>        res.status(200).json({<br>            data: comment,<br>            success: true<br>        })<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})<br>module.exports = router</pre><h4><strong>Update Post Schema</strong></h4><p>Now we have to add virtuals to the post data schema in order to get the comments associated with a post while getting the post. To do that open the Post.js file in the models folder and add the following function to create virtuvals.</p><p><strong>/models/Post.js</strong></p><pre>PostSchema.virtual(&#39;comments&#39;, {<br>    ref: &#39;comment&#39;,<br>    localField: &#39;_id&#39;,<br>    foreignField: &#39;PostId&#39;,<br>    justOne: false<br>})</pre><pre>module.exports = mongoose.model(&#39;post&#39;, PostSchema)</pre><h4><strong>Populate the required routes</strong></h4><p>Now we have to populate some routes with comments so that we can get the comments with requests.</p><p><strong>Routes that we gonna update</strong></p><p><strong>/user</strong>: so that we can get the posts and the comments with the posts of the logged in user. (deep populate)<br><strong>/profile/:id</strong>: get the posts and comments of the posts of a targeted user (deep populate)<br><strong>/posts</strong>: get all the posts and comments of the the posts<br><strong>/followers-posts</strong>: get all the posts from followings and comments of the the posts<br><strong>/post/:id:</strong> get a single post and the comments of the targeted post</p><p>Lets see the code changes</p><p><strong>/user — auth.js</strong></p><pre>router.get(&#39;/user&#39;, verifyAuth,  async (req, res) =&gt; {<br>    try {<br>        const user = await User.findById(req.user.id).populate({<br>            // deep populate<br>            path: &#39;posts&#39;,<br>            populate : {<br>                path : &#39;comments&#39;<br>            }<br>        })<br>        res.status(200).json({<br>            user,<br>            success: true<br>        })<br>    } catch (err) {<br>        console.error(err.message)<br>        res.status(500).json({ msg:&#39;SERVER ERROR&#39;})<br>    }<br>})</pre><p><strong>/profile/:id — features.js</strong></p><pre>router.get(&#39;/profile/:id&#39;, async (req, res) =&gt; {<br>    try {<br>        const user = await User.findById(req.params.id).populate({<br>            // deep populate<br>            path: &#39;posts&#39;,<br>            populate : {<br>                path : &#39;comments&#39;<br>            }<br>        })<br>        if(!user){<br>            return res.status(401).json({success: false})<br>        }<br>        res.status(200).json({<br>            data: user,<br>            success: true<br>        })<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><p><strong>/posts — posts.js</strong></p><pre>router.get(&#39;/posts&#39;, async (req, res) =&gt; {<br>    try {<br>        // populate<br>        const posts = await     Post.find().populate(&#39;comments&#39;).populate(&#39;posted_by&#39;)<br> <br>        return res.status(200).json({<br>            data: posts,<br>            success: true<br>        })<br>    } catch (error) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><p><strong>/followers-posts — posts.js</strong></p><pre>router.get(&#39;/followers-posts&#39;, verifyAuth, async (req, res) =&gt; {<br> <br>    try {<br>        const get_user = await User.findById(req.user.id)<br> <br>        // populate<br>        const posts  = await Post.find({UserId: get_user.following}).populate(&#39;comments&#39;).populate(&#39;posted_by&#39;)<br> <br>        res.status(200).json({<br>            data: posts,<br>            success: true<br>        })<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><p><strong>/post/:id — posts.js</strong></p><pre>router.get(&#39;/post/:id&#39;, async (req, res) =&gt; {<br>    try {<br>        // populate<br>        const post  = await Post.findById(req.params.id).populate(&#39;comments&#39;)<br> <br> <br> <br>        if(!post){<br>            res.status(400).json({success: false})<br>        }<br>       <br>        res.status(200).json({<br>            data: post,<br>            success: true<br>        })<br> <br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><h4><strong>Test the API</strong></h4><p>Now that we have successfully added the comments feather to the API lets test the API using postman.</p><p><strong>/login<br></strong>Login as joey, remember we created this user in previous post</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2Lv73cl1huP9nr8GI5HFw.png" /><figcaption>screenshot</figcaption></figure><p><strong>/post/comment/:id<br></strong>Use the token you got from joey login and configure headers of the add comment URL and create JSON data in the body and make a <strong>POST </strong>request. :id must be the id of the targeted post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjpufZP9dEYqiMEv8OqJXw.png" /><figcaption>screenshot</figcaption></figure><p>We can see we have successfully added a comment to a targeted post.</p><p><strong>/user<br></strong>Get the joey user to check is the populate work. If it works we must be able to see the posts posted by the user and the added comments on each post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1LCUkh-PpAm_cj78B6aJg.png" /><figcaption>screenshot</figcaption></figure><p>Here we can see both post array with post and comments array on posts as well.</p><h4><strong>Conclusion</strong></h4><p><strong>Hooray</strong>.. <em>We have successfully added and tested a new feather to the API</em></p><p>Great, this is the end of this version of the backend API. Hope you enjoyed it. We might again update the backend once we start adding machine learning models so hopefully next we will be building the front end for the API. And again if you guys (readers) want me to make any changes please let me know I will try my best to implement it.</p><p><strong>link to the github repo: </strong><a href="https://github.com/nafiu-dev/full_stack_app_with_AI-ML_models/tree/backend_v2">https://github.com/nafiu-dev/full_stack_app_with_AI-ML_models/tree/backend_v2</a></p><p><strong>You can connect with me here:</strong></p><p><a href="https://www.instagram.com/nafiu.dev">https://www.instagram.com/nafiu.dev</a></p><p><strong>Linkedin</strong>: <a href="https://www.linkedin.com/in/nafiu-nizar-93a16720b">https://www.linkedin.com/in/nafiu-nizar-93a16720b</a></p><p><strong>My other posts</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/stock-market-prediction-using-lstm-will-the-price-go-up-tomorrow-practical-guide-d1df2d54a517">Stock market prediction using LSTM; will the price go up tomorrow. Practical guide</a></li><li><a href="https://medium.com/@nafiu.dev/highlighting-the-most-popular-machine-learning-algorithms-implementing-it-4bf18b645163">Highlighting the most popular machine learning algorithms; Implementing it</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eccb35adbe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an advanced backend API from scratch using Node.js;]]></title>
            <link>https://medium.com/@nafiu.dev/building-an-advanced-backend-api-from-scratch-using-node-js-f26ed5c7092c?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26ed5c7092c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Sun, 30 Oct 2022 08:27:08 GMT</pubDate>
            <atom:updated>2022-11-06T09:27:44.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an advanced backend API from scratch using Node.js; CRUD, authentication and implementing awesome features— part 1</h3><h4>Hi all, welcome to the end to end full stack (backend, frontend) project with artificial intelligence and machine learning and ethical hacking series. In this post we are going to build the backend of the project.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qRYrb64G-lXIE_U7" /><figcaption>Photo by <a href="https://unsplash.com/@firosnv?utm_source=medium&amp;utm_medium=referral">Firos nv</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To build the backend API I will be using Express.js which is a Node.js framework specified for building RESTFUL APIs. To make this easier let’s break down the project into parts and write down the steps in point form.</p><p>I have already explained the project in the main series post. Check it out.</p><p><a href="https://medium.com/@nafiu.dev/end-to-end-full-stack-project-from-backend-frontend-and-machine-learning-to-ethical-hacking-series-3e53779e5aff">End to End full stack project from backend, frontend and machine learning to ethical hacking series.</a></p><h4><strong>About the project — (backend)</strong></h4><p>Our goal is to create a RESTFUL API which has an awesome amount of features that a modern application would have. This API is based on blogging. Where users will be able to register and login to their account and create a post, edit a post if they want to improve their post and also delete it if they don’t like it. Also will be able to view and read posts from other users and like the post if you like it and also follow the user if you want to keep it up to date.</p><p><strong>What will you learn?</strong></p><ul><li>Structure files and folder</li><li>Configure environment variables</li><li>Connect and create database schemas</li><li>Populate database Schemas using mongoose virtuals</li><li>Create express server</li><li>Create different types of routes</li><li>Handle authentication</li><li>Logic and to implement awesome features</li><li>Test an API</li></ul><p><strong>Features</strong> <strong>we going to implement:</strong></p><ul><li>authentication — user can login and register<br>- User will be able to register and then login<br>- View any user profile — No authentication required<br>- Verify users login — authentication required</li><li>CRUD — users will able to Create, Read, Update and Delete posts<br>- Users can view all the posts — No authentication required<br>- Users can filter posts by followers — authentication required<br>- User can create a new post — authentication required<br>- User can edit own post — authentication required<br>- User can delete own post — authentication required</li><li>Follow and unfollow targeted user — authentication required</li><li>Link and unlike a post — authentication required</li></ul><blockquote><strong>Note:</strong> I will improve this API as we go along, More features will be added and we will make the whole API more secure by adding more security perimeters and fixing existing bugs once we rich the hacking part of the series. For now the basic goal is to create version 1 of the backend API</blockquote><p><strong>Steps we gonna follow:</strong></p><ul><li><a href="#ee27">Install Prerequisites and setup the environment</a></li><li><a href="#3fb0">Create project and Install required packages</a></li><li><a href="#c7e3">Create and Structure folder and files</a></li><li><a href="#95e1">Create and run the server and connect to the database</a></li><li><a href="#75be">Authentication</a></li><li><a href="#5572">Posts — CRUD</a></li><li><a href="#83c9">Add features</a></li><li><a href="#faa0">Test the API</a></li><li><a href="#d1ea">conclusion </a>— next</li></ul><h4><strong>Install Prerequisites and setup the environment</strong></h4><p>Before we start we must install the required programs and set up the environment. In this step we need to make sure of 3 things which are: if our runtime environment is installed, an available database and a way to test the API.</p><p>As a runtime environment we are going to use Node.js so make sure its installed, you can get it here: <a href="https://nodejs.org/">https://nodejs.org</a>.</p><p>To test the API we will use postmen which you can get from here: <a href="https://www.postman.com/">https://www.postman.com</a>. also you must have a code editor I&#39;m using vscode which I prefer to use, you can get it from here: <a href="https://code.visualstudio.com/">https://code.visualstudio.com</a></p><p>And as a database we will use MongoDB atlas so we don’t have to install anything but you need to create an account and get the connection URI</p><p><strong>Steps to setup the database:</strong></p><ol><li>Visit ‘<a href="https://www.mongodb.com/cloud/atlas/register">https://www.mongodb.com/cloud/atlas/register</a>’ and create a free account. And complete the registration process by selecting the free shared subscription model.</li><li>Step 1 will direct you to <strong>Create a Shared Cluster </strong>page, here select the<strong> AWS</strong> &gt; select any <strong>region </strong>&gt; leave both <strong>Cluster Tire</strong> and <strong>Addition Settings</strong> and move to <strong>Cluster name</strong> which in default is <strong>‘Cluster0’ </strong>and I am gonna leave it as it is and create cluster.</li><li>Step 2 will take you to the Quickstart page. Here you must give a username and a password and click create user.</li><li>Next is to set up an <strong>IP Access List</strong>. here you must leave the ip address of your current device or the IP address of the server that you gonna deploy this api. But for the development purposes I’m gonna keep it all open for me by adding <strong>0.0.0.0</strong> as an Ip address and <strong>‘for all’</strong> as a description, and click finish and close. You must change it when you deploy the API else others will have access to your database</li><li>Step 4 will take you to <strong>Database Deployments</strong> page, here you can see Cluster0 click <strong>connect </strong>&gt; <strong>connect new application, </strong>This will show you an URI which we will use to connect the database with the API. now replace the password and username with the password and username you created in step 3. <strong>Example of URI:</strong> <br><em>mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster0.h8milvy.mongodb.net/?retryWrites=true&amp;w=majority</em></li></ol><p>Well, for now let’s keep it somewhere safe, we will get back to it when we start building the API</p><h4><strong>Create a node project and Install required packages</strong></h4><p>Let’s open our terminal and create a folder named ‘backend’ and create a new node project inside that folder which will initialize the package.json file.</p><pre>mkdir backend<br>cd backend<br>npm init -y</pre><p>Before we explore and add additional scripts in the package.json file lets install all the required packages and understand which role it plays in our API</p><pre>npm i express mongoose dotenv cors bcryptjs morgan jsonwebtoken</pre><p><strong>express </strong>— To manage the server and routes.<br><strong>mongoose </strong>— To connect with MongoDB<br><strong>dotenv </strong>— To load environment variables from the .env file<br><strong>cors </strong>— To allow api access from different domains<br><strong>bcryptjs </strong>— To hash passwords<br><strong>morgan </strong>— To log HTTP requests and errors<br><strong>jsonwebtoken </strong>— for authentication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*0CGFehHDkq6grmnJHvFJvg.png" /><figcaption>screenshot — package.json</figcaption></figure><p>Here we can see all the packages we installed under dependencies and also you can see I have added two scripts and one of them is using nodemon but here you can’t see nodemon installed this is because I have installed it globally so you either install it globally or as a dev-dependency.</p><pre>npm i nodemon -D<br>//Or<br>npm install -g nodemon</pre><p><strong>Nodemon </strong>— by using nodemon we don’t have to restart our server every time it fails it will run automatically.</p><h4><strong>Create and Structure folder and files</strong></h4><p>Well explaining each file at this point is going to be useless so at this point let me just show you the folder and file structure and please create the files as it is and I’m sure at this point you already have package.json, package-lock.json and the folder node_modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*Yaw58p_nu9Arh1o3qAAUyw.png" /><figcaption>screenshot — files structure</figcaption></figure><p>Create all the folders and files accordingly.<br>Well, till now we have installed all the required packages and created the files we need to <strong>get started</strong>.</p><h4><strong>Let’s create and run the server and connect to the database</strong></h4><p>Hope you have already created the <strong>index.js</strong> file in the root directory if not<br>please create it now. Inside this file we will import express, dotenv, cors and morgan and set up the middlewares, routes and also will make the connection with the database. To make things easy to understand we will make the database connection in another file (Db.js) and will import the file to the server. This file is located in the config folder. Also before we proceed we must set up the <strong>environment variables</strong> which are also located in the config folder.</p><p><strong>config/config.env</strong></p><pre>MONGO_URI=mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster0.h8milvy.mongodb.net/?retryWrites=true&amp;w=majority</pre><pre>JWT_SECTET=sdfsnisdnjsnfjsdnfjsdnfjk<br>PORT=5000</pre><p>Make sure you use your database connection URI as the MONG_URI</p><p><strong>config/Db.js</strong></p><pre>const mongoose = require(&#39;mongoose&#39;)<br>mongoose.connect(process.env.MONGO_URI)<br> .then(() =&gt; console.log(&#39;DATABASE CONNECTED&#39;))<br> .catch(err =&gt; {<br>  console.log(&#39;DATABASE CONNECTION ERROR&#39;, err)<br>  process.exit(1)<br>})</pre><p>Will use this file to connect the database.</p><p><strong>Open index.js file</strong></p><p>This is how your index.js file will look like, imported packages and created the express server as an app<strong>, </strong>configured all the middleware&#39;s and connected to the database.</p><blockquote><strong>Note:</strong> remember this is the completed version (v1) of index.js file therefore if you try to run the server as this is you will get an error. Because of the routes, remember we haven’t created any routes yet. So if you want to run the server now, you can comment the 3 routes lines and you can run the server and keep uncommenting the appropriate route as we go along</blockquote><p><strong>index.js</strong></p><pre>const express = require(&#39;express&#39;)<br>const app = express()<br>const dotenv = require(&#39;dotenv&#39;)<br>const cors = require(&#39;cors&#39;)<br>const morgan = require(&#39;morgan&#39;)</pre><pre>// MIDDLEWEARES<br>dotenv.config({ path: &#39;./config/config.env&#39; })<br>require(&#39;./config/Db&#39;)<br>app.use(cors())<br>app.use(express.json())<br>app.use(morgan(&#39;dev&#39;)) // for logging</pre><pre>// ROUTES<br>app.use(&#39;/api/v1&#39;, require(&#39;./routes/posts&#39;))<br>app.use(&#39;/api/v1&#39;, require(&#39;./routes/auth&#39;))<br>app.use(&#39;/api/v1&#39;, require(&#39;./routes/features&#39;))<br></pre><pre>PORT  = process.env.PORT || 5000<br>app.listen(PORT, console.log(`SERVER RUNNING ON PORT: ${PORT}`))</pre><p>Use the scripts to run the server.</p><pre>npm run dev</pre><p>The server will run on port 5000, make sure you don’t have anything running on port 5000.</p><blockquote><strong>Note:</strong> In the routes you can see /api/v1 which means that is the first two directories before whatever route directory we give in the routes in the routes folder. Example: the login route will be: <a href="http://127.0.0.1:5000/api/v1/login"><strong>http://127.0.0.1:5000/api/v1/login</strong></a><strong> </strong>since we are using port number 5000.</blockquote><h4><strong>Authentication</strong></h4><p>Open the User.js file in the models folder. Here we are going to create a mongoose Schema for our User models and also we will define some other function to format the current date as we want and also to populate posts which will allow us to get all posts posted by the user while we get the user profile which will make things easy in the long run.</p><p><strong>models/User.js</strong></p><pre>const mongoose = require(&#39;mongoose&#39;)</pre><pre>let UserSchema = new mongoose.Schema({<br> name:{<br>  type: String,<br>  required: true,<br>  index:true<br> },<br> email: {<br>  type: String,<br>  required: true,<br>  unique: true,<br>  match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/]<br> },<br> password:{<br>  type: String,<br>  required: true,<br>  select: false<br> },<br> following: {<br>  type: Array<br> },<br> followers: {<br>  type: Array<br> },<br> created_at:{<br>  type: String,<br> }<br>}, {<br> toJSON: { virtuals: true },<br> toObject: { virtuals: true }<br>})<br>UserSchema.pre(&#39;save&#39;, async function (next) {<br> let date_info = new Date<br> let date_into = date_info.getDate() + &#39;/&#39; + (date_info.getMonth()+1) + &#39;/&#39; +  date_info.getFullYear()<br> this.created_at = await date_into<br>})</pre><pre>UserSchema.virtual(&#39;posts&#39;, {<br> ref: &#39;post&#39;,<br> localField: &#39;_id&#39;,<br> foreignField: &#39;UserId&#39;,<br> justOne: false<br>})<br>module.exports = mongoose.model(&#39;user&#39;, UserSchema)</pre><p>Now open the <strong>auth.js</strong> file if you don’t have it create the auth.js file in the routes folder. Here we are going to create three routes. Register, Login and user routes. We all know what both register and login routes does, so let me tell you about the user route. User route is used to verify the logged in user.</p><p>Also we need to protect some routes to make sure only logged in users can use the route, to make this happen we will create a middleware to check the request headers for the access token. Now create<strong> verifyAuth.js</strong> in the <strong>middleware </strong>folder, we will get back to this after creating the register and login route.</p><blockquote><strong>Note:</strong> remember to uncomment the auth route from index.js file if you had it commented</blockquote><p><strong>Let’s get to code</strong>, first import the required libraries such as jsonwebtoken, bcryptjs, express and configure the router using express and export it. Here you will see I have imported the User model as <strong>User</strong> and also the <strong>verifyAuth.js </strong>file as <strong>verifyAuth.</strong> If you run the server now you will get an error that is because right now there is nothing in the <strong>verifyAuth.js</strong> file so to avoid the error lets code that file and get back to <strong>Auth.js</strong></p><p><strong>middleware/verifyAuth.js<br></strong>Here we are looking for the value ‘x-token’ in the header. Which will hold the access token generated by JWT and verify the token using <strong>jwt.verify().</strong></p><pre>const jwt = require(&#39;jsonwebtoken&#39;)</pre><pre>module.exports = (req, res,next) =&gt; {<br> const token = req.header(&#39;x-token&#39;)<br> if(!token){<br>  return res.status(401).json({<br>   msg: &#39;no Token, access denied&#39;,<br>   success: false<br>  })<br> }<br>try {<br>  const decoded  = jwt.verify(token, process.env.JWT_SECTET)<br>  req.user = decoded<br>  next()<br> } catch (err) {<br>  res.status(400).json({<br>   msg: &#39;no Token, access denied&#39;,<br>   success: false<br>  })<br> }<br>}</pre><p><strong>routes/auth.js</strong></p><p>Here we have to create 3 routes. Let me explain what each route does<br><strong>/register</strong>: This a POST request which will have 3 input fields: name, email, password and these 3 fields are required. Then we will check if the user already exists or not by using the input email. How? if the email already exists in the database then the user already exists and if not then we will consider as a new user and create the new user and before saving the user in the user in the database we will encrypt the password using bcrypt and then we will save the user and return the jWT token which is required for authentication.<br><strong>/login</strong>: is also a POST request which will expect 2 input fields: email and password. Next will check if the user exists or not and if not we will return a message saying invalid credentials and if does we will compare the password using bcrypt and if successful it will return the jWT token which is required for authentication.<br><strong>/user</strong>: this is a GET request which is protected by using the middleware we created earlier. This request will find the current logged in user by using the access token and return the user’s information/profile.</p><pre>const router = require(&#39;express&#39;).Router()<br>const bcrypt = require(&#39;bcryptjs&#39;)<br>const jwt = require(&#39;jsonwebtoken&#39;)</pre><pre>const User = require(&#39;../models/User&#39;)<br>const verifyAuth = require(&#39;../middleware/verifyAuth&#39;)</pre><pre>// POST | /api/v1/register | public | register user<br>router.post(&#39;/register&#39;, async (req, res) =&gt; {<br>    try {<br>        const {name, email, password} = req.body<br>        <br>        <br>        if(!name || !email || !password) {<br>            res.status(400).json({<br>                msg: &#39;please fill the required fields&#39;,<br>                success: false<br>            })<br>        }<br>        <br>        let user = await User.findOne({email})<br>        if(user){<br>            return res.status(400).json({ <br>                msg: &#39;user already exists&#39;,<br>                success: false<br>            })<br>        }<br>        <br>        <br>        user = new User({<br>            name,<br>            email,<br>            password<br>        })<br>        <br>        const slat = await bcrypt.genSalt(10)<br>        user.password = await bcrypt.hash(password, slat)<br>        await user.save()<br>        <br>        <br>        // paylaod || {id: user._id}<br>        jwt.sign({id: user._id}, process.env.JWT_SECTET, {<br>            expiresIn: 36000 <br>        }, (err, token) =&gt; {<br>            if(err) throw err<br>            res.status(200).json({<br>                token<br>            })<br>        })</pre><pre>} catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>// POST api/v1/login | public | login exixting user<br>router.post(&#39;/login&#39;, async (req, res) =&gt; {<br>    try {<br>        const {email, password} = req.body<br>        if( !email || !password){<br>            return res.status(400).json({ <br>                msg: &#39;invalid credentials&#39;,<br>                success: false <br>            })<br>        }</pre><pre>let user = await User.findOne({email}).select(&#39;+password&#39;)<br>        if(!user ) return res.status(400).json({<br>            msg: &#39;invalid credentials&#39;,<br>            success: false <br>        })</pre><pre>const isMatch = await bcrypt.compare(password, user.password)<br>        if(!isMatch ) return res.status(400).json({ <br>            msg: &#39;invalid credentials&#39;,<br>            success: false <br>        })</pre><pre>jwt.sign({id: user._id}, process.env.JWT_SECTET, {<br>            expiresIn: 36000 <br>        }, (err, token) =&gt; {<br>            if(err) throw err<br>            res.status(200).json({<br>                token<br>            })<br>        })</pre><pre>} catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>// GET api/v1/user | private | get logged in user for the process of auth<br>router.get(&#39;/user&#39;, verifyAuth,  async (req, res) =&gt; {<br>    try {<br>        const user = await User.findById(req.user.id).populate(&#39;posts&#39;)<br>        res.status(200).json({<br>            user,<br>            success: true<br>        }) <br>    } catch (err) {<br>        console.error(err.message)<br>        res.status(500).json({ msg:&#39;SERVER ERROR&#39;})<br>    }<br>})</pre><pre>module.exports = router</pre><p>Now that we have successfully created the authentication. It’s time to create posts.</p><h4><strong>Posts</strong></h4><p>We will start by creating the data Schema for posts. Open the Post.js in the models folder and code the schema here also we will create function to format date and to populate the user that created the post</p><p><strong>models/Post.js</strong></p><pre>const mongoose = require(&#39;mongoose&#39;)</pre><pre>let PostSchema = new mongoose.Schema({<br>    UserId: {<br>        type: mongoose.Schema.Types.ObjectId,<br>        ref: &#39;user&#39;,<br>        required: true<br>    },<br>    post_image: {<br>        type: String,<br>    },<br>    description: {<br>        type: String,<br>    },<br>    title: {<br>        type: String,<br>    },<br>    likes: {<br>        type: Array<br>    },<br>    post_emotion: {<br>        // this will be filled by AI/ML later<br>        type: String,<br>        default: null<br>    },<br>    created_at:{<br>        type: String,<br>    }<br>}, {<br>    toJSON: { virtuals: true },<br>    toObject: { virtuals: true }<br>})</pre><pre>PostSchema.pre(&#39;save&#39;, async function (next) {<br>    let date_info = new Date<br>    let date_into = date_info.getDate() + &#39;/&#39; + (date_info.getMonth()+1) + &#39;/&#39; +  date_info.getFullYear()<br>    this.created_at = await date_into<br>})</pre><pre>PostSchema.virtual(&#39;posted_by&#39;, {<br>    ref: &#39;user&#39;,<br>    localField: &#39;UserId&#39;,<br>    foreignField: &#39;_id&#39;,<br>    justOne: true<br>})</pre><pre>module.exports = mongoose.model(&#39;post&#39;, PostSchema)</pre><p>Now open the <strong>posts.js</strong> file if you don’t have it, create the posts.js file in the routes folder. Here we are going to create six routes. Before I start listing and explaining the routes, let’s import the required libraries and files, import express and create the router and export it. We also have to import two models <strong>Post </strong>and <strong>User</strong>. The <strong>User </strong>model will be used to filter posts by the following users and let’s not forget the <strong>verifyAuth </strong>since we need to protect some routes here.</p><blockquote><strong>Note:</strong> uncomment the post route from index.js if you have it commented</blockquote><p><strong>/posts</strong>: this is a GET request in order to get all the posts from the database<br><strong>/followers-posts</strong>: GET request to get posts from the only the users that you follow you must be logged in to make the request<br><strong>/post/:id</strong>: GET request will get a single post by id<br><strong>/add-new</strong>: POST request which will allow the logged in user to create a new post. Input fields are the title of the post the post (description) and an image url to show the image (image_url) in the database the image will be saved as post_image<strong><br>/edit-post/:id</strong>: PUT request will allow logged in user to edit users own posted post. Function will ensure that users can only edit their own posts and the input fields are the same as creating a new post<br><strong>/delete-post/:id</strong>: DELETE request which will allow logged in users to delete their own post by id. The function will ensure the post owner by checking if the post belongs to the logged in user or not.</p><p><strong>routes/posts.js</strong></p><pre>const router = require(&#39;express&#39;).Router()</pre><pre>// Models<br>const Post = require(&#39;../models/Post&#39;)<br>const User = require(&#39;../models/User&#39;)</pre><pre>// MIDDLEWARE<br>const verifyAuth = require(&#39;../middleware/verifyAuth&#39;)</pre><pre>// GET | /api/v1/posts | public | get all posts <br>router.get(&#39;/posts&#39;, async (req, res) =&gt; {<br>    try {<br>        const posts = await Post.find()<br>        return res.status(200).json({<br>            data: posts,<br>            success: true<br>        })<br>    } catch (error) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>// GET | /api/v1/followers-posts | private | get all posts from the users that logged in user follow<br>router.get(&#39;/followers-posts&#39;, verifyAuth, async (req, res) =&gt; {</pre><pre>try {<br>        const get_user = await User.findById(req.user.id)</pre><pre>const posts  = await Post.find({UserId: get_user.following}).populate(&#39;posted_by&#39;)<br>     <br>        res.status(200).json({<br>            data: posts,<br>            success: true<br>        })<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>// GET | /api/v1/post/:id | public | get a single post by id<br>router.get(&#39;/post/:id&#39;, async (req, res) =&gt; {<br>    try {<br>        const post  = await Post.findById(req.params.id)</pre><pre>if(!post){<br>            res.status(400).json({success: false})<br>        }<br>        <br>        res.status(200).json({<br>            data: post,<br>            success: true<br>        })</pre><pre>} catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>// POST | /api/v1/add-new| private | add a new post<br>router.post(&#39;/add-new&#39;, verifyAuth, async (req, res) =&gt; {<br>    try {</pre><pre>const newPost = await Post.create({<br>            UserId: req.user.id,<br>            title: req.body.title,<br>            description: req.body.description,<br>            post_image: req.body.image_url,<br>        })</pre><pre>res.status(200).json({<br>            data: newPost,<br>            success: true<br>        })<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>// PUT | /api/v1/post/edit-post/:id| Private | Edit a post<br>router.put(&#39;/edit-post/:id&#39;, verifyAuth, async (req, res) =&gt;{<br>    try {<br>        const post = await Post.findById(req.params.id)<br>        if (!post) {<br>            return res.status(400).json({<br>                success: false<br>            })<br>        }</pre><pre>if(!post.UserId == req.user.id){<br>            return res.status(400).json({<br>                success: false<br>            })<br>        }else{<br>            await post.update({   <br>                UserId: req.user.id,<br>                title: req.body.title,<br>                description: req.body.description,<br>                post_image: req.body.image_url,<br>            })<br>        }</pre><pre>res.status(200).json({ <br>            success: true,<br>            data: {}<br>        })<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>// DELETE | /api/v1/post/delete-post/:id | Private | delete a post<br>router.delete(&#39;/delete-post/:id&#39;,verifyAuth, async (req, res) =&gt;{<br>    try {<br>        const post = await Post.findById(req.params.id)<br>        if (!post) {<br>            return res.status(400).json({<br>                success: false<br>            })<br>        }<br>        <br>        if(!post.UserId == req.user.id){<br>            return res.status(400).json({<br>                success: false<br>            })<br>        }else{<br>            await post.delete()<br>        }<br>        <br>        res.status(200).json({ <br>            success: true,<br>            data: {}<br>        })<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>module.exports = router</pre><p>Now that we have created both posts and the authentication, let’s add some additional features to the API.</p><h4>Features</h4><blockquote><strong>Note:</strong> uncomment the post route from index.js if you have it commented</blockquote><p><em>well, think about this.. Lets allow users to follow each other and keep them up to date also lets allow them to like a post. This is going to be great for data analysis in the last stages of this series when we start implementing data models to improve the API. Without further ado let’s get into it.</em></p><p>Open the <strong>features.js </strong>file in the routes folder and import the required resources as before. Here we are going to create 5 routes which are to get the user profile by id, to like and unlike a post and also to follow and unfollow a user. Allow me to explain how each one of his works.</p><p><strong>/like/:id</strong>: GET request which will add a like to a post by Id. how this works is by pushing the id of the user that sent the request to the likes array of that post, we created that while creating the post data model.<br><strong>/unlike/:id</strong>: GET request which unlike a post by id. This route will remove the users id in the likes array of that post<br><strong>/follow/:id</strong>: GET request. This route will allow the current logged in user to follow another user. How this works is by adding the current users id to the followers array of the targeted user and targeted users id to the following array of the logged in user.<br><strong>/unfollow/:id</strong>: GET request used to unfollow a followed user. This works the opposite way of the follow request<br><strong>/profile/:id</strong>: GET request which will get a user by id. No authentication is required for this route</p><p><strong>Security alert</strong>: both liking and following features has a bug where you can add as much as likes you want and also can follow 1 user more then once. We can fix this by an easy if else statement but I’m going to leave it that way, because I’m planning big on the series, might end up introducing a level of hacking as well</p><p><strong>routes/features.js</strong></p><pre>const router = require(&#39;express&#39;).Router()</pre><pre>const Post = require(&#39;../models/Post&#39;)<br>const User = require(&#39;../models/User&#39;)<br>const verifyAuth = require(&#39;../middleware/verifyAuth&#39;)</pre><pre>// GET | /api/v1/post/like/:id| Private | Like a post<br>router.get(&#39;/like/:id&#39;, verifyAuth, async (req, res) =&gt; {<br>    try {<br>        const liked = await Post.updateOne(<br>            {<br>                _id: req.params.id<br>            },<br>            {<br>                $push: {<br>                    likes:  req.user.id <br>                }<br>            }<br>            )<br>            <br>            <br>            if(!liked){<br>                return res.status(401).json({success: false})<br>            }<br>            <br>            res.status(200).json({success: true})<br>            <br>        } catch (err) {<br>            console.log(err)<br>            res.status(400).json({success: false})<br>        }<br>    })<br>    <br>// GET | /api/v1/post/unlike/:id| Private | unlike a post<br>router.get(&#39;/unlike/:id&#39;, verifyAuth, async (req, res) =&gt; {<br>    try {<br>        const liked = await Post.updateOne(<br>            {<br>                _id: req.params.id<br>            },<br>            {<br>                $pull: {<br>                    likes:  req.user.id <br>                }<br>            }<br>            )<br>            <br>            if(!liked){<br>                return res.status(401).json({success: false})<br>            }<br>            <br>            <br>            res.status(200).json({success: true})<br>            <br>        } catch (err) {<br>            console.log(err)<br>            res.status(400).json({success: false})<br>        }<br>    })<br>    <br>    <br>    <br>// GET | /api/v1/post/follow/:id| Private | follow a User<br>router.get(&#39;/follow/:id&#39;, verifyAuth, async (req, res) =&gt; {<br>    try {<br>        const followed = await User.updateOne(<br>            {<br>                _id: req.user.id <br>            },<br>            {<br>                $push: {<br>                    following:  req.params.id <br>                }<br>            }<br>        )<br>    <br>        const followersAdded = await User.updateOne(<br>            {<br>                _id: req.params.id<br>            },<br>            {<br>                $push: {<br>                    followers:  req.user.id<br>                }<br>            }<br>        <br>        )<br>        <br>        if(!followed || !followersAdded){<br>            return res.status(401).json({success: false})<br>        }<br>        <br>        res.status(200).json({success: true})<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})<br>        <br>        <br>// GET | /api/v1/post/unfollow/:id| Private | unfollow a User<br>router.get(&#39;/unfollow/:id&#39;, verifyAuth, async (req, res) =&gt; {<br>    try {<br>        const followFixed = await User.updateOne(<br>            {<br>                _id: req.user.id <br>            },<br>            {<br>                $pull: {<br>                    following:  req.params.id <br>                }<br>            }<br>        )<br>            <br>        const followersFixed = await User.updateOne(<br>            {<br>                _id: req.params.id<br>            },<br>            {<br>                $pull: {<br>                    followers:  req.user.id<br>                }<br>            }</pre><pre>)</pre><pre>if(!followFixed || !followersFixed){<br>            return res.status(401).json({success: false})<br>        }</pre><pre>res.status(200).json({success: true})<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>// GET | /api/v1/post/profile/:id| public | get a users profile by iD<br>router.get(&#39;/profile/:id&#39;, async (req, res) =&gt; {<br>    try {<br>        const user = await User.findById(req.params.id).populate(&#39;posts&#39;)<br>        <br>        if(!user){<br>            return res.status(401).json({success: false})<br>        }<br>        res.status(200).json({<br>            data: user,<br>            success: true<br>        })<br>    } catch (err) {<br>        console.log(err)<br>        res.status(400).json({success: false})<br>    }<br>})</pre><pre>module.exports = router</pre><h4><strong>Let’s test the API</strong></h4><p>To test the API we will use a program called postmen if you don’t have it make sure to install it and also we won’t be testing for checking if all the routes works or not since it’s gonna only make this post longer and longer.<br>Make sure to run the server, cd into the backend folder and use the command ‘<strong>npm run dev</strong>’ this will run the development server and also open the postmen app<br>Here we are only going to test 4 routes if you want to try all feel free to do it We will try /register, /user, /add-new and /posts.</p><p><strong>/register</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKIHuMBWDpdVa-T_88u2-g.png" /><figcaption>screenshot — test register route</figcaption></figure><p>We successfully got the access token, now let’s verify the user</p><p><strong>/user</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXUxgtsYCsopbAGbXfk4RQ.png" /><figcaption>screenshot — test user</figcaption></figure><p>We verified the user as well by using the access token. Lets create a post</p><p><strong>/add-new</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LX7MDb-5lKwb3xMZitv4Tw.png" /><figcaption>screenshot — added new post</figcaption></figure><p>New we have successfully created a post let see if we can get the post by the /posts route.</p><p><strong>/posts</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hGMDQQJo_5FPvrJdvjapA.png" /><figcaption>screenshot — get all posts</figcaption></figure><p>Yes, we got the posts as well<br>Try testing all the routes</p><h4><strong>Conclusion</strong></h4><p>Well this is the end of building this version of the backend API hope you enjoyed it. Next hopefully we will be building the front end of the application. But <strong>before </strong>that I would like to know if you guys want to add more features which will help the project series.</p><p>Trying to make things simple here but I personally think adding more features will be great.<br>example :</p><ul><li>Add comments (will be great for ML/AI)</li><li>Allow image upload from local (post, image and user profile)</li></ul><p>And more, let me know and don’t forget to follow</p><p><strong>link to the github repo</strong>: <a href="https://github.com/nafiu-dev/full_stack_app_with_AI-ML_models/tree/backend_v1">https://github.com/nafiu-dev/full_stack_app_with_AI-ML_models</a></p><p><strong>You can connect with me here:</strong></p><p><a href="https://www.instagram.com/nafiu.dev">https://www.instagram.com/nafiu.dev</a></p><p><strong>Linkedin</strong>: <a href="https://www.linkedin.com/in/nafiu-nizar-93a16720b">https://www.linkedin.com/in/nafiu-nizar-93a16720b</a></p><p><strong>Posts related to series:</strong></p><p><a href="https://medium.com/@nafiu.dev/end-to-end-full-stack-project-from-backend-frontend-and-machine-learning-to-ethical-hacking-series-3e53779e5aff">End to End full stack project from backend, frontend and machine learning to ethical hacking series.</a></p><p><strong>part 2</strong></p><p><a href="https://medium.com/@nafiu.dev/building-an-advanced-backend-api-from-scratch-using-node-js-5eccb35adbe6">Building an advanced backend API from scratch using Node.js;</a></p><p><strong>My other posts</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/highlighting-the-most-popular-machine-learning-algorithms-implementing-it-4bf18b645163">Highlighting the most popular machine learning algorithms; Implementing it</a></li><li><a href="https://medium.com/@nafiu.dev/stock-market-prediction-using-lstm-will-the-price-go-up-tomorrow-practical-guide-d1df2d54a517">Stock market prediction using LSTM; will the price go up tomorrow. Practical guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26ed5c7092c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End to End full stack project from backend, frontend and machine learning to ethical hacking series.]]></title>
            <link>https://medium.com/@nafiu.dev/end-to-end-full-stack-project-from-backend-frontend-and-machine-learning-to-ethical-hacking-series-3e53779e5aff?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e53779e5aff</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[series]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 12:19:51 GMT</pubDate>
            <atom:updated>2022-11-06T09:28:35.738Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hi, I welcome you all to this series of building an end to end project starting from backend development, front-end development, artificial intelligence and machine learning to ethical hacking.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pgsi0TJfsZz97IVf" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this series my goal is to build a full stack app from scratch and keep improving the app using different technologies.</p><p><strong>Approach</strong></p><p>I am going to start by building a backend RESTFUL API using a selected technologies, after that I will start building the front end web application for the API. This is going to be the version 1 of the backend and frontend. I will improve both the backend API and the front if needed. Before we move into machine learning, artificial intelligence or ethical hacking I will make sure that the backend and the frontend is satisfied.</p><ul><li><a href="#2213">Backend</a></li><li><a href="#d3a5">Frontend</a></li><li>Machine learning and artificial intelligence</li><li>Ethical hacking</li></ul><p><strong>Project idea</strong></p><p>Create a blogging platform which has a lot of features as a modern application, where users can interact, and play around with. The application will be created using multiple technologies and programming languages. Example: backend might be Node.js and machine learning models will be coded using python. As we go along we will enhance the application using machine learning models for multiple reasons such as to handle post recommendations, users behaviors and much more. And at the end we will make sure to make the application as secure as possible and generate a VAPT report based on security vulnerabilities.</p><blockquote><strong>Note</strong>: This is the basic idea for now, I will keep updating the project idea as we go along.</blockquote><p><strong>Let’s get to it.</strong></p><h3><strong>Backend</strong></h3><h4><strong>Description</strong></h4><p>Language we are going to use is JavaScript, to build the backend API we will be using express.js which is a Node.js framework specified for building RESTFUL API. Here my goal is to create a RESTFUL API with a great amount of functionalities. In this version of the app users must be able to authenticate themselves to the API and create a post, edit and also delete a post if the creator wants to. Users must be able to view and read posts from other users and like and unlike the post, also follow and unfollow a targeted user.</p><p><strong>Features and what we going to implement are listed below</strong></p><ul><li>Authentication — login and register</li><li>CRUD — post</li><li>Follow and unfollow a user</li><li>Like and unlike a post</li><li>comment a targeted post</li></ul><p>more will be detailed once we start with the project.</p><p><strong>What will you learn?</strong></p><ul><li>Structure files and folder</li><li>Configure environment variables</li><li>Connect and create database schemas</li><li>Populate database Schemas using mongoose virtuals</li><li>Create express server</li><li>Create different types of routes</li><li>Handle authentication</li><li>Logic and to implement awesome features</li><li>Test an API</li></ul><blockquote><strong>Note</strong>: I will keep updating the description above as we go further down the project. If you (<strong>readers</strong>) have any suggestion about adding anything to the project you can let me know I might consider adding it, Depending on how helpful the suggestion is to the series.</blockquote><h4>backend — part 1 (v1 — starting the project)</h4><p><a href="https://medium.com/@nafiu.dev/building-an-advanced-backend-api-from-scratch-using-node-js-f26ed5c7092c">Building an advanced backend API from scratch using Node.js;</a></p><h4>backend — part 2 (Adding extra features)</h4><p><a href="https://medium.com/@nafiu.dev/building-an-advanced-backend-api-from-scratch-using-node-js-5eccb35adbe6">Building an advanced backend API from scratch using Node.js;</a></p><h4>Frontend</h4><blockquote>Coming next…</blockquote><p><strong>You can connect with me here:</strong></p><p><a href="https://www.instagram.com/nafiu.dev">https://www.instagram.com/nafiu.dev</a></p><p>Linkedin: <a href="https://www.linkedin.com/in/nafiu-nizar-93a16720b">https://www.linkedin.com/in/nafiu-nizar-93a16720b</a></p><p><strong>My other posts</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/highlighting-the-most-popular-machine-learning-algorithms-implementing-it-4bf18b645163">Highlighting the most popular machine learning algorithms; Implementing it</a></li><li><a href="https://medium.com/@nafiu.dev/stock-market-prediction-using-lstm-will-the-price-go-up-tomorrow-practical-guide-d1df2d54a517">Stock market prediction using LSTM; will the price go up tomorrow. Practical guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e53779e5aff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Highlighting the most popular machine learning algorithms; Implementing it]]></title>
            <link>https://medium.com/@nafiu.dev/highlighting-the-most-popular-machine-learning-algorithms-implementing-it-4bf18b645163?source=rss-8ec1182d9733------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf18b645163</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[artficial-intelligence]]></category>
            <dc:creator><![CDATA[Nafiu]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 08:16:38 GMT</pubDate>
            <atom:updated>2022-11-06T09:31:09.790Z</atom:updated>
            <content:encoded><![CDATA[<h4>Overview of the most popular machine learning models, implementing and comparing the accuracy using iris dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UgI_O63BrWQULIzn" /><figcaption>Photo by <a href="https://unsplash.com/@ekrull?utm_source=medium&amp;utm_medium=referral">Eric Krull</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post I’m going to go through an overview of the most popular machine learning models. Remember we are <strong>NOT</strong> gonna go through much detail about any of these models. We just find out how it does what it does and implement it using python and compare the results to check which one is better in our case.</p><p>Dataset is available at: <a href="https://www.kaggle.com/datasets/uciml/iris">https://www.kaggle.com/datasets/uciml/iris</a></p><p><strong>let’s get started. : )</strong></p><p>first let’s import the required libraries</p><pre>import pandas as pd<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import LabelEncoder<br>from matplotlib import pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import accuracy_score</pre><p>Since we are also gonna implement the models we need some data to work with. Therefore let’s start by loading the dataset (Iris Species dataset) using pandas.</p><pre>dataset = pd.read_csv(&#39;Iris.csv&#39;)<br>dataset.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*n_GZptwCsfoPwBZuzCpKrA.png" /><figcaption>screenshot</figcaption></figure><p>Now that the dataset is loaded, let’s see some more details about dataset such as data type of the features and to check if there is any null values</p><pre>dataset.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*WAABUHQ5zjuk5lWpvONTIQ.png" /><figcaption>screenshot</figcaption></figure><p>The dataset contains <strong>6</strong> features. These features are described below:</p><ol><li>Id = datasets unique identifier</li><li>SepalLengthCm — sepal length of the flower</li><li>SepalWidthCm — sepal width of the flower</li><li>PetalLengthCm — petal length of the flower</li><li>PetalWidthCm — petal width of the flower</li><li>Species — iris species. — also our target variable</li></ol><p>we don’t need ‘Id’ so we will not use it in the process of data processing.</p><h3><strong>Data processing</strong></h3><p>For data processing we are going to create a function which is gonna return train and test data after the process of splitting, standardizing and label encoding.</p><pre>def process_iris_data(x,y, Scaler, encoder, test_size=0.2):<br> x_train,x_test,y_train,y_test = train_test_split(x,y,test_size =0.2,random_state=100)<br> print({&#39;x_train&#39;: x_train.shape, &#39;x_test&#39;: x_test.shape,   &#39;y_train&#39;:y_train.shape, &#39;y_test&#39;:y_test.shape})<br> x_train = Scaler.fit_transform(x_train) # StandardScaler<br> x_test = Scaler.transform(x_test) # StandardScaler<br> y_train = Le.fit_transform(y_train) # LabelEncoder<br> y_test = Le.transform(y_test) # LabelEncoder<br> return (x_train, x_test, y_train, y_test)</pre><p>Here we going to create StandardScaler and the LabelEncoder and and split the X and Y data from the dataset and call the function to get the train and test data</p><pre>Sc = StandardScaler()<br>Le = LabelEncoder()</pre><pre>x = dataset[<br>[&#39;SepalLengthCm&#39;,<br>&#39;SepalWidthCm&#39;,<br>&#39;PetalLengthCm&#39;,<br>&#39;PetalWidthCm&#39;]<br>].values<br>y = dataset[&#39;Species&#39;].values</pre><pre># calling the function<br>x_train, x_test, y_train, y_test = process_iris_data(x,y,Sc,Le)</pre><p>Our data is now processed and prepared for training. So now we can start building and training the models using the data with simple explanation of how it works and also we will compare the models accuracy to check which model performs the best on our dataset</p><h3><strong>Modelling</strong></h3><p><strong>Logistic Regression</strong></p><p>Logistic Regression is a type of supervised learning, it is mostly used in Classification problems to predict the probability of something that might be true or false. we are <strong>NOT </strong>going to implement it here since I have already done it in another post.</p><p><a href="https://medium.com/@nafiu.dev/predicting-the-success-of-bank-telemarketing-using-logistic-regression-2bae00220912">Predicting the success of bank telemarketing using logistic regression</a></p><p><strong><em>Well, but what is supervised learning?</em></strong></p><p><em>In supervised machine learning models are trained using labelled input and output data. where the input data will fit into the model by making brute force predictions on the data and adjusting its weights for the correct answer.</em></p><p><strong>Linear Regression</strong></p><p>Linear Regression is another model which is based on supervised learning, in simple terms Linear Regression is used to find the relationship between two quantitative variables, which is known as the Dependent variable (y) and independent variable (X).</p><p>The prediction is done by using a straight line to estimate the changes of the dependent variable (target) as the independent variable (features) changes, to get the best results out of this model, it’s important to use clear data without much noise and without correlated input values (features).</p><pre>from sklearn.linear_model import LinearRegression<br>ler_model = LinearRegression() # creating the model<br>ler_model.fit(x_train, y_train) # training the model</pre><pre>ler_model.score(x_test,y_test) # checking model accuracy</pre><p><em>Accuracy score: 0.95</em></p><p><strong>Support Vector Machine</strong></p><p>Support Vector Machine (SVM) in another supervised learning algorithm which can be used for both regression and classification problems. (mostly classification). SVM works by separating classes by generating hyperlines with the maximum possible margins between data points</p><pre>from sklearn import svm<br>svm_model = svm.SVC() # creating the model<br>svm_model.fit(x_train, y_train) # training the model</pre><pre># checking model accuracy<br>svm_model.score(x_test,y_test)</pre><p><em>Got an accuracy score of: 1.0</em></p><p><strong>Decision Trees</strong></p><p>Decision Trees are supervised learning algorithms that can be used in both regression and classification problems. Decision tree uses a set of if-else conditions to decide if it needs to split a node into two or more sub-nodes until it reaches the final node. Think of a Decision Tree as a simple binary tree with 0 or 1 decision at each split until the model reaches the result node.</p><pre>from sklearn.tree import DecisionTreeClassifier<br>Dt_clf = DecisionTreeClassifier() # creating the model<br>Dt_clf.fit(x_train, y_train) # training the model</pre><pre>Dt_clf.score(x_test,y_test) # checking model accuracy</pre><p><em>Accuracy score: 0.96</em></p><p><strong>Random Forest</strong></p><p>Random forest is also a supervised learning algorithm that can be used in both regression and classification problems. (mostly classification). Random forest is a combination of multiple Decision Trees where the data is processed by Decision Trees and the results are combined. Instead of finding a single optimal route, random forest will define multiple suboptimal routes, which most of the time will make the overall result better.</p><pre>from sklearn.ensemble import RandomForestClassifier<br>Rfc = RandomForestClassifier() # creating the model<br>Rfc.fit(x_train, y_train) # training the model</pre><pre># checking model accuracy<br>Rfc.score(x_test, y_test)</pre><p><em>Accuracy score: 0.96</em></p><p><strong>Naive Bayes</strong></p><p>Naive Bayes is another easy to implement supervised learning algorithm mostly focused on classification problems. Naive Bayes is not just one algorithm, it’s a collection of algorithms based on Bayes’ Theorem works under the principle of conditional probability. i.e: predict the probability of the target based on the given feature values.</p><pre>from sklearn.naive_bayes import GaussianNB<br>gnb = GaussianNB()  # creating the model<br>gnb.fit(x_train, y_train) # training the model</pre><pre># checking model accuracy<br>gnb.score(x_test, y_test)</pre><p><em>Accuracy score: 0.96</em></p><p><strong>K-Means Clustering</strong></p><p>K-means clustering is an <strong>unsupervised machine learning</strong> model that is used for clustering problems. In simple terms K-means clustering works by selecting k points which are known as centroids and by assigning each data point to the closest centroid, therefore forming a cluster. The centroid will be reassigned after calculating the mean of each cluster to the calculated mean value and this process continues with the newly assigned centroid until the centroid stops moving.</p><p><strong>Some important steps involved while implementing k means:</strong></p><ul><li><strong>n_clusters:</strong> the number of K — well in this case we already know the answer is 3 (3 Species categories). But what if we didn’t know that well? In that case we have to use the “elbow method” to find the optimum number of clusters for classification.</li><li><strong>n_init</strong>: algorithm will initialise the centroids n times and select the best fit</li><li><strong>max_iter</strong>: number of times each n_init will run</li><li><strong>random_state</strong>: random seed value</li></ul><p><strong>Implementing and plotting the results.</strong></p><pre>from sklearn.cluster import KMeans<br>kmeans = KMeans(n_clusters = 3, max_iter = 300, n_init = 10, random_state = 0) # creating the model</pre><pre>kmeans.fit(x_train) # training the model</pre><pre># making predictions<br>y_kmeans = kmeans.fit_predict(x_train)</pre><pre># plotting the results<br>plt.scatter(x_train[y_kmeans == 0, 0], x_train[y_kmeans == 0, 1],  label = &#39;Iris-setosa&#39;)<br>plt.scatter(x_train[y_kmeans == 1, 0], x_train[y_kmeans == 1, 1], label = &#39;Iris-versicolour&#39;)<br>plt.scatter(x_train[y_kmeans == 2, 0], x_train[y_kmeans == 2, 1], label = &#39;Iris-virginica&#39;)<br>plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,1], color=&quot;black&quot;, label = &#39;Centroids&#39;)</pre><pre>plt.legend();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*MwT2YoVxHizTPsZ0SH9mPg.png" /><figcaption>screenshot</figcaption></figure><p><strong><em>What is unsupervised learning?</em></strong></p><p><em>In unsupervised machine learning, models are trained using unlabeled data, in order to find the underlying pattern of the dataset. The main goal of unsupervised learning is to analyze and cluster unlabeled datasets.</em></p><p><strong><em>Cluster</em></strong><em>: is a group of data points that are similar to each other</em></p><p><strong>K-Nearest Neighbors</strong></p><p>K-nearest neighbors is a type of supervised learning algorithm used for both regression and classification problems. KNN algorithm calculates the probability of new data points which are close to the classes ‘K’ of training data then assigns the data point to the class where the majority of the K data points belong.</p><pre>from sklearn.neighbors import KNeighborsClassifier<br>knn_clf = KNeighborsClassifier(n_neighbors=3) # creating the model<br>knn_clf.fit(x_train, y_train)  # training the model</pre><pre>y_pred_knn = knn_clf.predict(x_test) # making predictions<br>accuracy_score(y_test, y_pred_knn) # checking accuracy score</pre><p><em>Got an accuracy score of: 1.0</em></p><h3><strong>Conclusion</strong></h3><p>The results are amazing, we can see that the best performing model on iris dataset is both KNN and SVM models with the accuracy score of 100% which is great. Also we can see that other 3 models is also performing very well with accuracy score above 90% and the score of those 3 models are almost the same.</p><p>well this is the end of this post, hope you got some helpful information out of this..</p><p><strong>link to github repo:</strong> <a href="https://github.com/nafiu-dev/most_populer_ML_models">https://github.com/nafiu-dev/most_populer_ML_models</a></p><p><strong>you can connect with me here:</strong></p><p><a href="https://www.instagram.com/nafiu.dev"></a></p><p><strong>my other posts:</strong></p><ul><li><a href="https://medium.com/@nafiu.dev/stock-market-prediction-using-lstm-will-the-price-go-up-tomorrow-practical-guide-d1df2d54a517">Stock market prediction using LSTM; will the price go up tomorrow. Practical guide</a></li><li><a href="https://medium.com/@nafiu.dev/predicting-the-success-of-bank-telemarketing-using-logistic-regression-2bae00220912">Predicting the success of bank telemarketing using logistic regression</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf18b645163" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>