<?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 Nisarg Kapkar on Medium]]></title>
        <description><![CDATA[Stories by Nisarg Kapkar on Medium]]></description>
        <link>https://medium.com/@nisargkapkar?source=rss-74613c72030f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lWwbuBaMZSLBKTmOE4MEZg.jpeg</url>
            <title>Stories by Nisarg Kapkar on Medium</title>
            <link>https://medium.com/@nisargkapkar?source=rss-74613c72030f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:26:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nisargkapkar/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[ELI5 JavaScript: The Spread Operator]]></title>
            <link>https://nisargkapkar.medium.com/eli5-javascript-the-spread-operator-a884e7b6835?source=rss-74613c72030f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a884e7b6835</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webdev]]></category>
            <dc:creator><![CDATA[Nisarg Kapkar]]></dc:creator>
            <pubDate>Thu, 21 Oct 2021 15:54:58 GMT</pubDate>
            <atom:updated>2021-10-21T15:54:58.446Z</atom:updated>
            <content:encoded><![CDATA[<h4>The spread operator (…) introduced in JavaScript ES6 is used to ‘unpack’ elements of an iterable. Read the article to learn more about it!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uixiFCJpjKHKumOQEL0NpA.png" /><figcaption>ELI5 JavaScript: The Spread Operator cover image</figcaption></figure><p>One of the most useful features introduced in ES6 is the Spread Operator. It is denoted by three dots (…).</p><p>According to MDN Web Docs:</p><blockquote>Spread syntax (…) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FWRQBXSCnEFJIuxktnw%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FWRQBXSCnEFJIuxktnw%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExeDJ6eG5yaG1iNHZtMGZ4cWN2ZTd1aTJibmxzOTkyaDJtdTF1d3ppMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FWRQBXSCnEFJIuxktnw%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="278" frameborder="0" scrolling="no"><a href="https://medium.com/media/81589a9157db1c2cec662896c0fcfaec/href">https://medium.com/media/81589a9157db1c2cec662896c0fcfaec/href</a></iframe><p>Sounds complex right?<br>Don’t worry, read this article till the end, and I will make sure you know the ins and outs of the Spread Operator :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5zf2M4HgjjWszLd4a5%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5zf2M4HgjjWszLd4a5%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExODhsMmNqYnZpYnNocjd3MTFkd2k2Mm96dzEwbTg2OGdwcGplMzQ1bSZlcD12MV9naWZzX2dpZklkJmN0PWc%2F5zf2M4HgjjWszLd4a5%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="181" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceb4fd2380af661521a6e88c61bea3a3/href">https://medium.com/media/ceb4fd2380af661521a6e88c61bea3a3/href</a></iframe><p>As the name suggests, the spread operator is used to ‘spread’ out the elements of an iterable (string, array, etc.). Let’s look at an example:</p><pre>let arr = [“This”, “is”, “an”, “array”]<br>console.log(arr) <br>console.log(…arr) //with spread operator</pre><pre>//output<br>[&quot;This&quot;, &quot;is&quot;, &quot;an&quot;, &quot;array&quot;]<br>This is an array</pre><p>Okay! Now let’s look at some use cases of the spread operator.</p><p><strong>Table of Content</strong><br>1. Passing arguments to functions<br>2. Copying arrays/objects<br> 2.1 Arrays<br> 2.2 Objects<br>3. Combining arrays/objects<br> 3.1 Arrays<br> 3.2 Objects<br>4. String to characters</p><p><strong>Passing arguments to functions</strong></p><pre>let num = [1, 2, 3 ,4]<br>console.log(Math.min(num[0], num[1], num[2], num[3]))</pre><p>Instead of passing each element separately, you can use the spread operator!</p><pre>console.log(Math.min(...num))</pre><p><strong>Copying arrays/objects</strong></p><p>Use the spread operator to create copies of arrays &amp; objects.</p><ul><li><strong>Arrays</strong></li></ul><pre>let arr1=[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]<br>let arr2 = arr1 <br>let arr3 = [...arr1]<br>arr1.push(&quot;e&quot;)<br>console.log(&quot;arr1 = &quot;, arr1)<br>console.log(&quot;arr2 = &quot;, arr2)<br>console.log(&quot;arr3 = &quot;, arr3)</pre><p>Can you guess the output?</p><pre>//output <br>&quot;arr1 = &quot; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;]<br>&quot;arr2 = &quot; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;]<br>&quot;arr3 = &quot; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]</pre><p>Let’s understand what happened…</p><ol><li>The assignment operator (=) creates a reference to the original array. So here, arr2 is just a reference to arr1. Both arr1 and arr2 point to the same array in memory!</li><li>To make a copy, we use the spread operator! By using the spread operator we make a new copy of the array in the memory. Now changes made to arr1 will not be reflected in arr3 (and vice-versa)</li></ol><ul><li><strong>Objects</strong></li></ul><pre>let obj1 = {<br>    firstName: &quot;Nisarg&quot;,<br>    lastName: &quot;Kapkar&quot;,<br>    website: &quot;Hashnode&quot;,<br>    twitter: &quot;<a href="http://twitter.com/nnkkaapp">@nnkkaapp</a>&quot;<br>}<br>let obj2 = obj1 <br>let obj3 = {...obj1}<br>obj1.website = &quot;Medium&quot;</pre><p>Similar to arrays, changing obj1 changes obj2 but not obj3.</p><p><strong>NOTE: <br>While copying arrays/objects, the spread operator only goes one level deep.</strong></p><pre>let num1 = [[1, 2], [3, 4], [5, 6]]<br>let num2 = [...num1]<br>num1[0][0] = 100<br>console.log(num1)<br>console.log(num2)</pre><p>Here, both num1 and num2 will be equal to [[100, 2], [3, 4], [5,6]]. <br>A similar thing happens when you copy nested objects using the spread operator.<br>The nested arrays/objects inside an array/object are just references. So when you use the spread operator to copy, the nested arrays/objects are not copied (rather their references are copied)</p><p><strong>Combining arrays/objects</strong></p><p>Use the spread operator to combine arrays &amp; objects (and insert elements in arrays &amp; objects)</p><ul><li><strong>Arrays</strong></li></ul><pre>let arr1 = [1, 2, 3, 4]<br>let arr2 = [4, 5, 6]<br>let arr3 = [...arr1, 7, ...arr2, 8]<br>console.log(arr3)</pre><p>arr3 will be equal to [1, 2, 3, 4, 7, 4, 5, 6, 8] (arr1 elements+7+arr2 elements+8)</p><ul><li><strong>Objects</strong></li></ul><pre>let obj1 = {<br>    firstName: &quot;Nisarg&quot;,<br>    lastName: &quot;Kapkar&quot;,<br>    website: &quot;Hashnode&quot;<br>}<br>let obj2 = {<br>    twitter: &quot;<a href="http://twitter.com/nnkkaapp">@nnkkaapp</a>&quot;,<br>    website: &quot;Medium&quot;<br>}<br>let obj3 = {...obj1, ...obj2, dob: &quot;23/12/2000&quot;}<br>console.log(obj3)</pre><pre>//output<br>{<br>    firstName: &quot;Nisarg&quot;,<br>    lastName: &quot;Kapkar&quot;,<br>    website: &quot;Medium&quot;,<br>    twitter: &quot;<a href="http://twitter.com/nnkkaapp">@nnkkaapp</a>&quot;,<br>    dob: &quot;23/12/2000&quot;<br>}</pre><p><strong>NOTE: <br>If there are multiple values for the same key (in the above example: ‘website’), the last encountered value is assigned, and all the previous values are overwritten (in the above example, ‘Hashnode’ is overwritten by ‘Medium’)</strong></p><p><strong>String to characters</strong></p><pre>let firstName = &quot;Nisarg&quot; <br>console.log([...firstName])</pre><p>Since a string is iterable, we can use the spread operator on it. The output of the above code will be [“N”, “i”, “s”, “a”, “r”, “g”]</p><p>Woooo! Thank you for reading 😄</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F2E6OYt2yphlWTGZeYK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F2E6OYt2yphlWTGZeYK%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F2E6OYt2yphlWTGZeYK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e85a2c380cb8320a2ecea5891341889/href">https://medium.com/media/5e85a2c380cb8320a2ecea5891341889/href</a></iframe><p>If you have any questions about the Spread Operator (or about JavaScript in general), feel free to ask them in the comments 👇</p><p>This article is part of my ELI5 JavaScript series.<br>If you want to read &amp; learn more about JavaScript, don’t forget to subscribe (more articles coming soon!)</p><p>Follow me 👇 for more content on full-stack development, software engineering &amp; data structures/algorithms.</p><ul><li><a href="https://twitter.com/nnkkaapp">Twitter</a></li><li><a href="https://www.linkedin.com/in/nisarg-kapkar/">Linkedin</a></li><li><a href="https://github.com/Nkap23">Github</a></li></ul><p>Thank you again :)<br>Have an awesome day and happy coding 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a884e7b6835" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training your First Machine Learning Model with sklearn]]></title>
            <link>https://medium.com/analytics-vidhya/training-your-first-machine-learning-model-with-sklearn-e03d5de3bfba?source=rss-74613c72030f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e03d5de3bfba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nisarg Kapkar]]></dc:creator>
            <pubDate>Fri, 23 Oct 2020 05:48:21 GMT</pubDate>
            <atom:updated>2020-10-24T16:19:25.713Z</atom:updated>
            <content:encoded><![CDATA[<h4>STEP BY STEP GUIDE</h4><h3>Training your First Machine Learning Model with Python’s sklearn</h3><h4>This article will guide you through all the steps required for Machine Learning Model Training, from data preprocessing to model evaluation!</h4><figure><img alt="Image with text Machine Learning" src="https://cdn-images-1.medium.com/max/1024/1*fSCVtg54LRWs1zDSiPCqyg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@markus-winkler-1430818?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Markus Winkler</a> from <a href="https://www.pexels.com/photo/working-industry-internet-writing-4578660/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p><strong>Machine Learning</strong> is teaching a computer to make predictions (on new unseen data) using the data it has seen in the past. Machine Learning involves building a model based on training data, to make predictions on other unseen data.<br>Some applications of machine learning: Recommendation system (for example, recommending new movies to a user based on movies he has seen and liked), Stock Market (predicting trends of stocks), Virtual Personal Assistants, etc.</p><p>Machine learning is generally split into three categories: Supervised Learning, Unsupervised Learning, and Reinforcement Learning.<br>This tutorial will focus on training a machine learning model using <strong>Supervised Learning</strong>.<br>In supervised learning, we train the computer on data containing both input (features) and output (target), and the goal is to learn a function that maps input to an output.<br>You can read more about machine learning approaches <a href="https://en.wikipedia.org/wiki/Machine_learning#Machine_learning_approaches">here</a>.</p><blockquote>For this tutorial, we will use Python’s <a href="https://scikit-learn.org/stable/">sklearn</a> library (sklearn is a Machine Learning library and it contains implementation of various Machine Learning Algorithms) and <a href="https://www.kaggle.com/c/home-data-for-ml-course">Kaggle’s Housing Price Prediction Dataset</a>.</blockquote><p>Considering that you know the basics of Machine Learning and Supervised Learning, let’s start with our Machine Learning model!</p><p>Let’s first create a new notebook on Kaggle.<br>Login to your Kaggle account and go to the <a href="https://www.kaggle.com/c/home-data-for-ml-course/notebooks">Notebook Section</a> of Housing Price Competition. <br>Click on the ‘New Notebook’ option. It will redirect you to the Notebook settings page.<br>Keep everything as default and click on Create.</p><p>You should now have a new notebook similar to the one shown below. <br>(Delete the given default code block)</p><figure><img alt="Image showing default Kaggle notebook" src="https://cdn-images-1.medium.com/max/960/1*UJhAVxBlttPfDwPZYYjnQg.png" /></figure><blockquote>I have made a Notebook containing all the relevant steps and code. <br>You can access the <a href="https://www.kaggle.com/nisargkapkar/basic-ml-model">Notebook</a> on Kaggle.</blockquote><h4><strong>Step 1- Import necessary libraries/functions</strong></h4><p>Let’s import all the required libraries and functions we would need.</p><pre><em>#Import necessary libraries/functions</em></pre><pre><strong>import pandas as pd<br>import numpy as np<br>from sklearn.model_selection import train_test_split<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import OneHotEncoder<br>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.metrics import mean_absolute_error</strong></pre><p>Explanation and link to documentation for each function are provided in subsequent steps.</p><h4><strong>Step 2- Load the data</strong></h4><p>You should have an arrow symbol on the top right corner, clicking on it will open a new panel. The panel shows details about input data.</p><p>Click on ‘<strong>home-data-for-ml-course</strong>’ and then click on ‘<strong>train.csv</strong>’. Clicking on ‘train.csv’ will open a new panel. The panel shows the path and the data stored in ‘train.csv’<br>Store the ‘<strong>train.csv</strong>’ data in ‘<strong>X dataset</strong>’<br>Similarly, store the ‘<strong>test.csv</strong>’ data in ‘<strong>X_test dataset</strong>’</p><pre><em>#Load the data</em></pre><pre><em>#read train.csv and store it in &#39;X&#39;<br></em><strong>X=pd.read_csv(&#39;../input/home-data-for-ml-course/train.csv&#39;,index_col=&#39;Id&#39;)</strong></pre><pre><em>#read test.csv and store it in &#39;X_test&#39;</em><br><strong>X_test=pd.read_csv(&#39;../input/home-data-for-ml-course/test.csv&#39;,index_col=&#39;Id&#39;)</strong></pre><p>As the name suggests, <strong>read_csv</strong> is used to read a comma-separated values (CSV) file. You can read more about function <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html">here</a>.</p><h4><strong>Step 3- Examine the data</strong></h4><p>Before proceeding to further steps, let’s examine our data.</p><pre><em>#Examine the data</em></pre><pre><strong>print(X.shape)<br>print(X.columns)<br>print(X.head(n=5))</strong></pre><ul><li><strong>X.shape</strong> returns the dimensions (number of rows, number of columns) of DataFrame</li><li><strong>X.columns</strong> returns the column labels of DataFrame</li><li><strong>X.head()</strong> returns the first n rows of DataFrame</li></ul><p>Similarly, you can examine data in the ‘X_test’ dataset.</p><p>Below is an image showing the first 5 rows of the ‘X’ Dataset (X.head(n=5))</p><figure><img alt="Image showing first 5 rows of ‘X’ database" src="https://cdn-images-1.medium.com/max/1024/1*5YuitzH0TlNRAK63J2TVzg.png" /></figure><p><strong>Some observations:</strong></p><ul><li>‘X’ dataset contains a column named ‘SalePrice’, but this column is not present in the ‘X_test’ dataset. This is because ‘SalePrice’ is our target variable (more on target variable in step 4) and we will predict the values of ‘SalePrice’ for ‘X_test’.</li><li>There are two types of columns, columns containing numbers (numerical columns) and columns containing non-numerical values (categorical columns).</li><li>A categorical column only takes a fixed number of values.</li><li>Some cells have value as ‘NaN’, these are cells with missing values. (More on missing data in step 6)</li></ul><h4><strong>Step 4- Separate the Target variable</strong></h4><p><strong>Some key definitions:</strong></p><ul><li><strong>Features</strong>: Features are basically the independent columns/variables used by models to make predictions.</li><li><strong>Target</strong>: Target is the output obtained by making predictions.</li></ul><p>In our database, <strong>SalePrice</strong> is Target and all other remaining columns are the Features.</p><p>Generally, real-world datasets have a lot of missing values. (More on missing data in Step 6)<br>There is a chance that our target value is itself missing for some rows in the dataset. For cases like this, we drop the rows with missing target values from the dataset.</p><pre><em>#drop rows with missing target values from &#39;X&#39;</em></pre><pre><strong>X.dropna(axis=0,subset=[&#39;SalePrice&#39;],inplace=True)</strong></pre><p><strong>dropna()</strong> is a function available in Pandas. It is used to drop rows/columns with NaN (or Null) values.<br>You can read more about the function and its parameters <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html">here</a>.</p><p>After dropping, we will separate our target from other features.<br>We will store our target in ‘<strong>y</strong>’ and then drop the target column from the dataset.</p><pre><em>#Store target in &#39;y&#39; and drop the target column from &#39;X&#39;</em></pre><pre><strong>y=X.SalePrice<br>X.drop([&#39;SalePrice&#39;],axis=1,inplace=True)<br>print(y)</strong></pre><p><strong>drop()</strong> is a function available in Pandas. It is used to drop rows and columns.<br>You can read more about the function and its parameters <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html">here</a>.</p><h4><strong>Step 5- Extract categorical and numerical columns</strong></h4><p>We saw that there are two types of columns present in the dataset: Numerical columns and Categorical columns.</p><p>Let’s first see the cardinality (number of unique values in a column) of our categorical columns.</p><pre><em>#print categorical column labels with cardinality</em></pre><pre><strong>for i in X.columns:<br>    if X[i].dtype==&quot;object&quot;:<br>        print(i,X[i].nunique(),sep=&#39; &#39;)</strong></pre><p>The above code prints categorical column labels with the corresponding cardinality. (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.nunique.html"><strong>nunique()</strong></a> is used to count distinct values)</p><p>We will divide columns labels into 3 parts: categorical_columns, columns_to_drop, numerical_columns</p><pre><em>#Divide columns in 3 parts: categorical_columns, numerical_columns and columns_to_drop</em></pre><pre><strong>categorical_columns=[]<br>numerical_columns=[]<br>columns_to_drop=[]</strong></pre><pre><strong>for i in X.columns:<br>    if X[i].nunique()&lt;15 and X[i].dtype==&quot;object&quot;:<br>        categorical_columns.append(i)<br>    elif X[i].nunique()&gt;=15 and X[i].dtype==&quot;object&quot;:<br>        columns_to_drop.append(i)<br>    elif X[i].dtype in [&quot;int64&quot;,&quot;float64&quot;]:<br>        numerical_columns.append(i)<br>        <br>print(categorical_columns)<br>print(columns_to_drop)<br>print(numerical_columns)</strong></pre><ul><li><strong>categorical_columns</strong> is a list containing all column labels with non-numerical value and cardinality less than 15.</li><li><strong>numerical_columns</strong> is a list containing all column labels with numerical values.</li><li><strong>columns_to_drop</strong> is a list containing all column labels with non-numerical value and cardinality greater than/equal to 15.</li></ul><pre><em>#drop &#39;columns_to_drop&#39; from &#39;X&#39; and &#39;X_test&#39;</em></pre><pre><strong>X=X.drop(columns_to_drop,axis=1)<br>X_test=X_test.drop(columns_to_drop,axis=1)</strong></pre><p>The above code will drop all the categorical columns with cardinality greater than/equal to 15 from both ‘X’ and ‘X_test’ dataset.</p><p>The explanation for why we are selecting categorical columns with cardinality less than 15 and dropping other categorical columns in Step 7</p><h4><strong>Step 6- Impute missing data</strong></h4><p>Real-world datasets might contain many missing values (NaN, Null). There are many reasons why data could be missing. <br>For example, A house without a ‘Garage’ won’t have a ‘GarageQual’ (garage quality) data (since there is no Garage in the house)</p><p>Scikit-learn (sklearn) will throw an error if we try training a model on data containing missing values. So, we need to impute (fill in/replace) the missing values before training the model.</p><p>Before imputing, let’s check how many cells contain a missing value!</p><pre><em>#optional<br>#print column labels with number of missing cells in that corresponding column</em></pre><pre><em>#for X dataset</em><br><strong>missing_columns=X.isnull().sum()<br>print(&quot;X dataset&quot;)<br>print(missing_columns[missing_columns&gt;0])</strong></pre><pre><strong>print()</strong></pre><pre><em>#for X_test</em><br><strong>missing_columns_test=X_test.isnull().sum()<br>print(&quot;For X_test set&quot;)<br>print(missing_columns_test[missing_columns_test&gt;0])</strong></pre><p>The code prints column labels with the number of missing cells in that corresponding column.</p><figure><img alt="Image showing missing column label with count (before imputing)" src="https://cdn-images-1.medium.com/max/326/1*mXY0V0jeGXtFxIhQYtY0AA.png" /></figure><p>We will first impute numerical columns</p><pre><em>#impute numerical_columns</em><br><strong>numerical_imputer=SimpleImputer()</strong></pre><pre><em>#for X</em><br><strong>for i in numerical_columns:<br>    current_column=np.array(X[i]).reshape(-1,1)<br>    updated_column=numerical_imputer.fit_transform(current_column)<br>    X[i]=updated_column</strong></pre><pre><em>#for X_test</em><br><strong>for i in numerical_columns:<br>    current_column=np.array(X_test[i]).reshape(-1,1)<br>    updated_column=numerical_imputer.fit_transform(current_column)<br>    X_test[i]=updated_column</strong></pre><p>For imputing, we have used the inbuilt Imputer provided in sklearn (<strong>SimpleImputer()</strong>)</p><p>This imputer will replace all the missing values in a particular column with the <strong>mean</strong> of that column values.<br>More details on SimpleImputer <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html">here</a>.</p><p>We iterate over all numerical columns (for both ‘X’ and ‘X_test’ dataset) and store them in np.array (current_column)<br>Our imputing method (numerical_imputer.fit_transform) expects a 2D array, so we use reshape(-1,1) to convert our 1D array into 2D array.<br>We store the final column (with imputed values) in ‘updated_column’ and finally, we replace that corresponding column in the dataset with the obtained ‘updated_column’</p><p>Similarly, we will impute categorical columns</p><pre><em>#impute categorical_columns</em><br><strong>categorical_imputer=SimpleImputer(strategy=&quot;most_frequent&quot;)</strong></pre><pre><em>#for X</em><br><strong>for i in categorical_columns:<br>    current_column=np.array(X[i]).reshape(-1,1)<br>    updated_column=categorical_imputer.fit_transform(current_column)<br>    X[i]=updated_column</strong></pre><pre><em>#for X_test</em><br><strong>for i in categorical_columns:<br>    current_column=np.array(X_test[i]).reshape(-1,1)<br>    updated_column=categorical_imputer.fit_transform(current_column)<br>    X_test[i]=updated_column</strong></pre><p>Here, we replace the missing value in a particular column with the <strong>most_frequent</strong> value of that column.</p><p>Now, let’s recheck the number of missing cells!</p><pre><em>#optional<br>#print column labels with number of missing cells in that corresponding column</em></pre><pre><em>#for X dataset</em><br><strong>missing_columns=X.isnull().sum()<br>print(&quot;X dataset&quot;)<br>print(missing_columns[missing_columns&gt;0])</strong></pre><pre><strong>print()</strong></pre><pre><em>#for X_test</em><br><strong>missing_columns_test=X_test.isnull().sum()<br>print(&quot;For X_test set&quot;)<br>print(missing_columns_test[missing_columns_test&gt;0])</strong></pre><pre><em>#after imputation, there would be no columns with missing data</em></pre><p>You should see output similar to one shown in the image below.</p><figure><img alt="Image showing missing column label with count (after imputing)" src="https://cdn-images-1.medium.com/max/283/1*miiGJTn8pUHtDtF2ZoWPbw.png" /></figure><h4><strong>Step 7- Encode Categorical columns</strong></h4><p>A categorical column takes a fixed number of values. For example, a column ‘pet’ would contain some fixed numbers of values only like Cat, Dog, Bird, etc.</p><p>We need to preprocess (encode them) these types of columns before using them in a Machine Learning model, or else it will throw an error.</p><p>We will use the inbuilt <strong>OneHotEncoder</strong> provided in sklearn.</p><p>OneHotEncoder creates a new boolean column for every unique value in the column to be encoded.</p><p>Consider a column named ‘pets’ which contain 5 unique values [‘Cat’,’Dog’,’Bird’,’Fish’,’Rabbit’].<br>After applying OneHotEncoding we will get 5 new columns</p><figure><img alt="Image showing OneHot encoding example table" src="https://cdn-images-1.medium.com/max/1024/1*teBKBdGb4-WeAKxNSQjEDw.png" /></figure><p>One disadvantage of one-hot encoding is that it can increase the size of the dataset.<br>For the above example, we have 35–7 = 28 new cells (35 new boolean cells — 7 original cells we will drop)<br>Now consider a dataset of 1000 rows with 50 categorical columns, and the cardinality of each categorical column is 30.<br>So, we each categorical column, we will have 1000*30–1000 = 29000 new cells.<br>For all 50 categorical columns, 29000*50 new cells</p><p>This is the reason why we are dropping categorical columns with cardinality greater than/equal to in Step 5</p><pre><em>#Encode categorical columns</em></pre><pre><em>#STEPS:<br>#get one-hot encoded columns for X and X_test (using fit_transform/transform)<br>#give names to one-hot encoded columns (using get_feature_names)<br>#drop categorical columns from X and X_test (using drop)<br>#oh encoding removes index, add back index (using .index)<br>#add one-hot encoded columns to X and X_test (using pd.concat)</em></pre><pre><strong>ohencoder=OneHotEncoder(handle_unknown=&#39;ignore&#39;,sparse=False)</strong></pre><pre><em>#for X</em><br><strong>ohe_X=pd.DataFrame(ohencoder.fit_transform(X[categorical_columns]))<br>ohe_X.columns=ohencoder.get_feature_names(categorical_columns)<br>X.drop(categorical_columns,axis=1,inplace=True)<br>ohe_X.index=X.index<br>X=pd.concat([X,ohe_X],axis=1)</strong></pre><pre><em>#for X_test</em><br><strong>ohe_X_test=pd.DataFrame(ohencoder.transform(X_test[categorical_columns]))<br>ohe_X_test.columns=ohencoder.get_feature_names(categorical_columns)<br>X_test.drop(categorical_columns,axis=1,inplace=True)<br>ohe_X_test.index=X_test.index<br>X_test=pd.concat([X_test,ohe_X_test],axis=1)</strong></pre><p>OneHotEncoder is an inbuilt function available in sklearn.</p><p>Sometimes that validation set might some categorical features that are not present in training data, by default, OneHotEncoder will raise an error when such features are encountered.<br>To avoid error, we set the <strong>handle_unknown</strong> parameter to ‘ignore’. Now, if an unknown feature is encountered, the one-hot encoded column for that feature will be all zeros.</p><p>More details on OneHotEncoder <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html">here</a>.</p><p>‘oh_X’ and ‘oh_X_test’ contain our one-hot encoded columns for the ‘X’ and ‘X_test’ dataset, respectively.</p><p>By default, one-hot encoded columns are given names like 1, 2, 3… To get column names based on feature values, we use the <strong>get_feature_names</strong> function.<br>OneHot encoding removes the index, so we add back the indexes.</p><p>Next, we drop the categorical columns from the X and X_test dataset.<br>Then we concatenate (using inbuilt <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html"><strong>Concat function</strong></a> from Pandas) the ‘X’ and ‘X_test’ dataset with their one-hot encoded columns. (‘oh_X’ and ‘oh_X_test’)</p><p><strong>NOTE:<br></strong>We have used <strong>fit_transform</strong> for ‘oh_X’ and <strong>transform</strong> for ‘oh_X_test’. You can read about the difference between fit_transform and transform <a href="https://stackoverflow.com/questions/23838056/what-is-the-difference-between-transform-and-fit-transform-in-sklearn">here</a>.</p><h4><strong>Step 8- Split Dataset into train and validation set</strong></h4><p>Three types of datasets are usually used in different stages of model training: Training set, Validation set, and Test set.</p><p>You can read more about these types of datasets <a href="https://en.wikipedia.org/wiki/Training,_validation,_and_test_sets">here</a>.</p><p>We already have our test set (X_test).</p><p>We will split the ‘X’ dataset into 2 parts: Training set and Validation Set.</p><pre><em>#Split Dataset in train and validation set</em></pre><pre><strong>X_train,X_valid,y_train,y_valid=train_test_split(X,y,train_size=0.8,test_size=0.2)</strong></pre><p>(<strong>X_train</strong>, <strong>y_train</strong>) are the <strong>training</strong> set features and target, respectively.(<strong>X_valid</strong>,<strong> y_valid</strong>) are the <strong>validation</strong> set features and target, respectively.</p><p>We have used a 0.8 proportion of the dataset for the training set and the remaining 0.2 for the validation set.</p><p>More details on the <strong>train_test_split</strong> function <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html">here</a>.</p><h4><strong>Step 9- Define the model</strong></h4><p>We will use Random Forests for our Machine Learning model.</p><p>Random Forests constructs multiple <strong>decision trees</strong> and merges their outputs to provide more accurate predictions.</p><p>I recommend reading and understanding <a href="https://www.javatpoint.com/machine-learning-decision-tree-classification-algorithm">decision trees</a> and <a href="https://en.wikipedia.org/wiki/Random_forest">random forests</a> properly before proceeding further.</p><p>We will use the inbuilt <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html"><strong>RandomForestRegressor</strong></a> function available in sklearn.</p><pre><em>#Define the model</em></pre><pre><strong>model=RandomForestRegressor()</strong></pre><h4><strong>Step 10- Fit the model</strong></h4><p>Fitting the model basically means training the model on training data.</p><p>We will use the <strong>.fit</strong> method provided in sklearn to fit our model on training data.</p><pre><em>#Fit the model</em></pre><pre><strong>model.fit(X_train,y_train)</strong></pre><h4><strong>Step 11- Predict and evaluate on the validation set</strong></h4><p>Let’s test our trained model on the validation set.</p><pre><em>#Predict and Evaluate on validation set</em></pre><pre><strong>preds_valid=model.predict(X_valid)<br>score_valid=mean_absolute_error(y_valid,preds_valid)<br>print(&quot;MAE: &quot;,score_valid)</strong></pre><p><strong>.predict()</strong> method (available in sklearn) will make predictions on validation data. These predictions are stored in ‘<strong>preds_valid</strong>’.</p><p>We have used<strong> </strong><a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html"><strong>mean_absolute_error</strong></a> (from sklearn) to estimate how far our predicted values (preds_valid) are from actual values (y_valid).</p><p>We define the error as the difference between actual and predicted value. (error = actual-predicted)</p><p>MAE (mean_absolute_error) takes the absolute value of error for every row and then takes the average of these absolute errors.</p><p>In the above code, ‘<strong>score_valid</strong>’ stores our MAE score.</p><h4><strong>Step 12- Generate test prediction</strong></h4><pre><em>#Generate Test Prediction</em></pre><pre><strong>preds_test=model.predict(X_test)<br>submission=pd.DataFrame({&#39;Id&#39;:X_test.index,&#39;SalePrice&#39;:preds_test})<br>submission.to_csv(&#39;submission.csv&#39;,index=False)</strong></pre><p>Our predictions on the test set (X_test) are stored in the ‘<strong>preds_test’</strong>.</p><p>We then make a DataFrame (with Id and SalePrice (our predicted SalePrice) column) and convert it to .csv.<br>This .csv will be used for Kaggle Contest Evaluation.</p><p><strong>To submit your predictions in the Kaggle Contest:</strong></p><ul><li>Click on Save Version (blue button, top right corner) and select the ‘Save &amp; Run All’ option and then click on Save.</li><li>After saving, click on the number next to the Save Button.</li><li>A new window will open up, and you should have the Version History panel on the right side. Click on the ellipsis (…) button next to Version 1.</li><li>Click on the ‘Submit to Competition’ option.</li></ul><p>You can view your submission and see your Score (MAE for test set) and position on the leaderboard.</p><h4><strong>BONUS SECTION</strong></h4><p>Congratulations on training your first Machine Learning Model! <br>Want to decrease your MAE and improve your rank on the leaderboard? Here are a few things you can try!</p><ul><li>Test using different models (such as <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a>, <a href="https://lightgbm.readthedocs.io/en/latest/">LightGBM</a>, etc.) and see which model provides better accuracy.</li><li><a href="https://en.wikipedia.org/wiki/Feature_engineering#:~:text=Feature%20engineering%20is%20the%20process,as%20applied%20machine%20learning%20itself.">Feature Engineering</a> (extracting additional features from existing data) and <a href="https://en.wikipedia.org/wiki/Feature_selection">Feature Selection</a> (selecting the best subset of features to use for model training)</li><li>Try using various imputation methods for missing data. SimpleImputer can impute missing data with mean, median, mode, and constant. You can also try imputing using <a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.KNNImputer.html">KNNImputer</a>.</li><li><a href="https://en.wikipedia.org/wiki/Hyperparameter_optimization">Hyperparameter tuning</a> (refer to the documentation of each model to learn more about their hyperparameters). Sklearn learn has an inbuilt function (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">GridSearchCV</a>) which you can use to search for optimal hyperparameter. (you can also use a simple loop to search for optimal hyperparameters)</li><li><a href="https://en.wikipedia.org/wiki/Ensemble_learning">Ensemble learning</a> (Ensembling is a technique of combining multiple machine learning algorithms to get better prediction). You can read more about sklearn inbuilt modules for ensemble methods <a href="https://scikit-learn.org/stable/modules/ensemble.html">here</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e03d5de3bfba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/training-your-first-machine-learning-model-with-sklearn-e03d5de3bfba">Training your First Machine Learning Model with sklearn</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TensorFlow 2 Object Detection API With Google Colab]]></title>
            <link>https://medium.com/swlh/tensorflow-2-object-detection-api-with-google-colab-b2af171e81cc?source=rss-74613c72030f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2af171e81cc</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Nisarg Kapkar]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 16:17:38 GMT</pubDate>
            <atom:updated>2021-09-29T09:17:51.819Z</atom:updated>
            <content:encoded><![CDATA[<h4>STEP BY STEP GUIDE</h4><h4>This article will guide you through all the steps required for object recognition model training, from collecting images for the model to testing the model!</h4><figure><img alt="A simple Dog Breed Classifier! Can recognize 10 different breeds of dogs!" src="https://cdn-images-1.medium.com/max/1024/1*LWK1Tb8WjJdmD7Q_bcbOFQ.png" /></figure><p><strong>UPDATE:<br></strong>Thank you all for your amazing support. Recently hit almost 35k views on this blog!</p><ul><li>I am also currently sharing more amazing content about javascript, web development, software engineering, etc. on my Twitter. Let’s connect: <a href="https://twitter.com/nnkkaapp">@nnkkaapp</a></li><li><a href="https://nisargkapkar.medium.com/subscribe">Subscribe</a> to get an email whenever I publish a new article</li></ul><p>In this tutorial, we will use Google Colab (for model training) and Google Drive (for storage).</p><p>Colab is a free Jupyter NoteBook environment hosted by Google that runs on the cloud. Google Colab provides free access to GPUs (Graphical Processing Units) and TPUs (Tensor Processing Units).</p><p>You can read more about Google Colab on their <a href="https://colab.research.google.com/notebooks/intro.ipynb">Intro</a> and <a href="https://research.google.com/colaboratory/faq.html">FAQ</a> page.</p><p><strong>NOTE:</strong><br>Sessions on Google Colab are 12 hours long. After 12 hours everything on Colab storage is wiped out (Notebooks will also disconnect from Virtual Machines if they are left idle for too long). So, it is advisable to use Google Drive for storage rather than using Colab’s storage.</p><p>Considering that you know the basics of Colab, let’s start with our Object Recognition Model!</p><h4>Step 1- Prerequisites (Gather/Label images, Create label_map… )</h4><ul><li><strong>Gather and Label images</strong></li></ul><p>We need to provide properly labeled images to the Object Detection API. These images will be used to train our model.</p><p>The first step is to gather images for all the objects you want your model to classify. You can collect images from the internet, or use some public datasets. You can search for public datasets using <a href="https://datasetsearch.research.google.com/">Google’s Dataset Search</a>.</p><p>Next, we need to label all the desired objects in the collected images. LabelImg is a superb tool for annotating images. You can find the installation and usage instructions on its <a href="https://github.com/tzutalin/labelImg">GitHub page</a>. (skip this step if you are using a public dataset and you already have labeled images)</p><p>After labeling, divide the dataset into two parts- <strong>train </strong>(80% of images with their corresponding XML files) and <strong>test </strong>(remaining 20% of images with their corresponding XML files).</p><blockquote>For this tutorial, I am using <a href="https://www.kaggle.com/mbkinaci/fruit-images-for-object-detection">Fruit Image for Object Detection Dataset</a> from <a href="https://www.kaggle.com/">Kaggle</a>. The database already contains labeled images divided into two sets (train and test).</blockquote><ul><li><strong>Create label_map.pbtxt</strong></li></ul><p>A label_map maps each class(label) to an int value. label_map file should have the extension as .pbtxt.</p><p>Below is the label_map file for the Fruit Detection dataset:</p><pre>item {<br>      id: 1<br>      name: &#39;apple&#39;<br>}<br>item {<br>     id: 2<br>     name: &#39;orange&#39;<br>}<br>item {<br>     id: 3<br>     name: &#39;banana&#39;<br>}</pre><p>Similarly, you must make a label_map.pbtxt file for your dataset.</p><ul><li><strong>Download a pre-trained model to apply transfer learning</strong></li></ul><p>We will use pre-trained models provided by TensorFlow for training.<br>Download any per-trained model of your choice from the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md">TensorFlow 2 Detection Model Zoo</a>. (just click on the name of the model you want to use to start the download)</p><blockquote>For this tutorial, I am using the SSD Resnet50 V1 FPN 640X640 model.</blockquote><ul><li><strong>Download generate_tfrecords.py script</strong></li></ul><p>This script(generate_tfrecords.py) will be used to covert the annotations into the TFRecord format. Download the script from <a href="https://github.com/sglvladi/TensorFlowObjectDetectionTutorial/tree/master/docs/source/scripts">here</a>.</p><blockquote>Huge thanks to <a href="http://pcwww.liv.ac.uk/~sglvladi/">Lyudmil Vladimirov</a> for allowing me to use some of the content from their amazing <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/index.html">TensorFlow 2 Object Detection API Tutorial</a> for Local Machines!</blockquote><h4>Step 2- Set up the directory structure on Google Drive</h4><p>Go to your Google Drive and make a new folder named “<strong>TensorFlow</strong>”.</p><p>Make a directory structure in your TensorFlow folder as shown below.<br>(You can give names of your choice to folders. If you are using different names, change all the paths in Jupyter NoteBook according to your folder names)</p><pre>TensorFlow<br>├───scripts<br>│   └───preprocessing<br>└───workspace<br>    └───training_demo<br>        ├───annotations<br>        ├───exported-models<br>        ├───images<br>        │   ├───test<br>        │   └───train<br>        ├───models<br>        └───pre-trained-models</pre><p>We will now add all the collected files (from Step 1) to their respective directories.</p><ul><li>Add the <strong>train </strong>and <strong>test images </strong>(with their corresponding XMLfiles) to <strong>‘training_demo/images/train’</strong> and <strong>‘training_demo/images/test’</strong> folder respectively.</li><li>Add the <strong>label_map.pbtxt</strong> file to <strong>‘training_demo/annotations’</strong>.</li><li>Add the <strong>generate_tfrecord.py</strong> script to <strong>‘scripts/preprocessing’</strong>.</li><li>Extract the <strong>downloaded pre-trained-model</strong> and add the extracted folder to <strong>‘training_demo/pre-trained-models’</strong>.</li><li>Go to ‘training_demo/models’ and make a new folder named ‘my_ssd_resnet_v1_fpn’ (name the folder according to the pre-trained-model you have downloaded)<br>Copy the <strong>pipeline.config file</strong> from ‘training_demo/pre-trained-models/ssd_resnet50_v1_fpn_640x640_coco17_tpu-8’ (or from the respective folder of the pre-trained-model you have downloaded and extracted) and <strong>paste it into the newly created ‘my_ssd_resnet_v1_fpn’ folder </strong>(or the folder new you created in ‘training_demo/models’ according to your pre-trained-model).</li></ul><p>After uploading all the files, this is how your directory structure should look like: (new files and folders highlighted in bold)</p><pre>TensorFlow<br>├───scripts<br>│   └───preprocessing<br>│     └───<strong>generate_tfrecord.py </strong><br>└───workspace<br>    └───training_demo<br>        ├───annotations<br>        │   └───<strong>label_map.pbtxt </strong><br>        ├───exported-models<br>        ├───images<br>        │   ├───test<br>        │   │     └───<strong>test images with corresponding XML files</strong><br>        │   └───train<br>        │         └───<strong>train images with corresponding XML files</strong><br>        ├───models<br>        │   └───<strong>my_ssd_resnet50_v1_fpn</strong><br>        │     └───<strong>pipeline.config</strong><br>        └───pre-trained-models<br>            └───<strong>ssd_resnet50_v1_fpn_640x640_coco17_tpu-8</strong></pre><p>We will now do most of the steps on Google Colab.</p><p>I have made a Notebook containing all the steps and relevant codes. (Run the cell with a particular step number to execute that step)<br>You can download the NoteBook from my <a href="https://github.com/Nkap23/TensorFlow_with_Colab_tutorial">GitHub Repository</a>.</p><p>Open Colab and load the downloaded Notebook.</p><h4>Step 3- Select the Hardware Accelerator</h4><p>On Colab, go to Runtime→Change Runtime Type and select Hardware accelerator as GPU.</p><p><strong>NOTE:</strong><br>If you have given different names to your folders and files, don’t forget to change the paths in cells according to your files and folder in Colab Notebook!</p><h4>Step 4- Mount Google Drive</h4><pre><strong>from google.colab import drive<br>drive.mount(&#39;/content/gdrive&#39;)</strong></pre><p>You will be given a URL and you will be asked to enter an authentication code to mount your google drive.</p><h4>Step 5- Download TensorFlow Model Garden</h4><pre><em>#cd into the TensorFlow directory in your Google Drive</em><br><strong>%cd &#39;/content/gdrive/My Drive/TensorFlow&#39;</strong></pre><pre><em>#and clone the TensorFlow Model Garden repository</em><br><strong>!git clone </strong><a href="https://github.com/tensorflow/models.git"><strong>https://github.com/tensorflow/models.git</strong></a></pre><pre><em>#using a older version of repo</em><br><strong>%cd &#39;/content/gdrive/MyDrive/TensorFlow/models&#39;<br>!git checkout -f e04dafd04d69053d3733bb91d47d0d95bc2c8199</strong></pre><p>You should now have a new folder named ‘<strong>models</strong>’ in your TensorFlow directory!</p><p><strong>NOTE:</strong><br>Some steps in the tutorial are not compatible with the latest version of TensorFlow 2. So, we will be using an older version of the repository for this tutorial (Date of older version: 21st Sept 2020)</p><h4>Step 6- Install some required libraries and tools</h4><pre><strong>!apt-get install protobuf-compiler python-lxml python-pil<br>!pip install Cython pandas tf-slim lvis</strong></pre><h4>Step 7- Compile the Protobuf libraries</h4><pre><em>#cd into &#39;TensorFlow/models/research&#39;</em><br><strong>%cd &#39;/content/gdrive/My Drive/TensorFlow/models/research/&#39;</strong></pre><pre><strong>!protoc object_detection/protos/*.proto --python_out=.</strong></pre><h4>Step 8- Set the environment</h4><pre><strong>import os<br>import sys</strong></pre><pre><strong>os.environ[&#39;PYTHONPATH&#39;]+=&quot;:/content/gdrive/My Drive/TensorFlow/models&quot;</strong></pre><pre><strong>sys.path.append(&quot;/content/gdrive/My Drive/TensorFlow/models/research&quot;)</strong></pre><h4>Step 9- Build and Install setup.py</h4><pre><strong>!python setup.py build<br>!python setup.py install</strong></pre><h4>Step 10- Test the Installation</h4><pre><em>#cd into &#39;TensorFlow/models/research/object_detection/builders/&#39;</em><br><strong>%cd &#39;/content/gdrive/My Drive/TensorFlow/models/research/object_detection/builders/&#39;</strong></pre><pre><strong>!python model_builder_tf2_test.py<br>from object_detection.utils import label_map_util<br>from object_detection.utils import visualization_utils as viz_utils<br>print(&#39;Done&#39;)</strong></pre><p>If all the installations were successful, you should see output similar to the one shown below.</p><pre>…<br>[       OK ] ModelBuilderTF2Test.test_invalid_model_config_proto<br>[ RUN      ] ModelBuilderTF2Test.test_invalid_second_stage_batch_size<br>[       OK ] ModelBuilderTF2Test.test_invalid_second_stage_batch_size<br>[ RUN      ] ModelBuilderTF2Test.test_session<br>[  SKIPPED ] ModelBuilderTF2Test.test_session<br>[ RUN      ] ModelBuilderTF2Test.test_unknown_faster_rcnn_feature_extractor<br>[       OK ] ModelBuilderTF2Test.test_unknown_faster_rcnn_feature_extractor<br>[ RUN      ] ModelBuilderTF2Test.test_unknown_meta_architecture<br>[       OK ] ModelBuilderTF2Test.test_unknown_meta_architecture<br>[ RUN      ] ModelBuilderTF2Test.test_unknown_ssd_feature_extractor<br>[       OK ] ModelBuilderTF2Test.test_unknown_ssd_feature_extractor<br>----------------------------------------------------------------------<br>Ran 20 tests in 42.274s</pre><pre>OK (skipped=1)<br>Done</pre><h4>Step 11- Generate Tfrecords</h4><pre><em>#cd into preprocessing directory</em><br><strong>%cd &#39;/content/gdrive/My Drive/TensorFlow/scripts/preprocessing&#39;</strong></pre><pre><em>#run the cell to generate test.record and train.record</em></pre><pre><strong>!python generate_tfrecord.py -x &#39;/content/gdrive/My Drive/TensorFlow/workspace/training_demo/images/train&#39; -l &#39;/content/gdrive/My Drive/TensorFlow/workspace/training_demo/annotations/label_map.pbtxt&#39; -o &#39;/content/gdrive/My Drive/TensorFlow/workspace/training_demo/annotations/train.record&#39;</strong></pre><pre><strong>!python generate_tfrecord.py -x &#39;/content/gdrive/My Drive/TensorFlow/workspace/training_demo/images/test&#39; -l &#39;/content/gdrive/My Drive/TensorFlow/workspace/training_demo/annotations/label_map.pbtxt&#39; -o &#39;/content/gdrive/My Drive/TensorFlow/workspace/training_demo/annotations/test.record&#39;</strong></pre><pre><em># !python generate_tfrecord.py -x &#39;[path_to_train_folder]&#39; -l &#39;[path_to_annotations_folder]/label_map.pbtxt&#39; -o &#39;[path_to_annotations_folder]/train.record&#39;</em></pre><pre><em># !python generate_tfrecord.py -x &#39;[path_to_test_folder]&#39; -l &#39;[path_to_annotations_folder]/label_map.pbtxt&#39; -o &#39;[path_to_annotations_folder]/test.record&#39;</em></pre><p>You should now have two new files “<strong>test.record</strong>” and “<strong>train.record</strong>” in <strong>‘workspace/training_demo/annotations’ </strong>folder.</p><h4>Step 12- Copying some files</h4><ul><li>Copy the “<strong>model_main_tf2.py</strong>” file from “TensorFlow\models\research\object_detection” and paste it in training_demo folder. We will need this file for training the model.</li><li>Copy the “<strong>exporter_main_v2.py</strong>” file from “TensorFlow\models\research\object_detection” and paste it in training_demo folder. We will need this file to export the trained model.</li></ul><h4>Step 13- Configure the pipeline file</h4><p>Go to ‘training_demo/models/my_ssd_resnet50_v1_fpn’. (or the folder you have created for the downloaded model in your ‘training_demo/models’ directory)</p><p>Open the pipeline.config file. (you can open a file in Colab by simply double-clicking it)</p><p>Change the lines shown below according to your dataset. (set paths according to your folders name and downloaded pre-trained-model)</p><pre><strong>Line 3:</strong><br>num_classes: 3 (#number of classes your model can classify/ number of different labels)</pre><pre><strong>Line 131:</strong><br>batch_size: 16 (#you can read more about batch_size <a href="https://stats.stackexchange.com/questions/153531/what-is-batch-size-in-neural-network">here</a>)</pre><pre><strong>Line 161:</strong><br>fine_tune_checkpoint: &quot;pre-trained-models/ssd_resnet50_v1_fpn_640x640_coco17_tpu-8/checkpoint/ckpt-0&quot; (#path to checkpoint of downloaded pre-trained-model)</pre><pre><strong>Line 162:</strong><br>num_steps: 250000 (#maximum number of steps to train model, note that this specifies the maximum number of steps, you can stop model training on any step you wish)</pre><pre><strong>Line 167:</strong><br>fine_tune_checkpoint_type: &quot;detection&quot; (#since we are training full detection model, you can read more about model fine-tuning <a href="https://stackoverflow.com/questions/56012092/tensorflow-object-detection-api-how-does-the-fine-tuning-of-a-model-works/56041400">here</a>)</pre><pre><strong>Line 168:</strong><br>use_bfloat16: false (#Set this to true only if you are training on a TPU)</pre><pre><strong>Line 172:</strong><br>label_map_path: &quot;annotations/label_map.pbtxt&quot; (#path to your label_map file)</pre><pre><strong>Line 174:</strong><br>input_path: &quot;annotations/train.record&quot; (#path to train.record)</pre><pre><strong>Line 182:</strong><br>label_map_path: &quot;annotations/label_map.pbtxt&quot; (#path to your label_map file)</pre><pre><strong>Line 186:</strong><br>input_path: &quot;annotations/test.record&quot; (#Path to test.record)</pre><h4>Step 14- Start TensorBoard</h4><p>TensorBoard allows you to track and visualize various training metrics while training is ongoing.<br>You can read more about TensorBoard <a href="https://www.tensorflow.org/tensorboard">here</a>.</p><pre><em>#cd into training_demo</em><br><strong>%cd &#39;/content/gdrive/My Drive/TensorFlow/workspace/training_demo&#39;</strong></pre><pre><em>#start the Tensorboard</em><br><strong>%load_ext tensorboard<br>%tensorboard --logdir=models/my_ssd_resnet50_v1_fpn</strong></pre><pre><em># %load_ext tensorboard<br># %tensorboard --logdir=models/[name_of_pre-trained-model_you_downloaded]</em></pre><p>Initially, you will get a message saying “No dashboards are active for the current data set”.<br>But once the training start, you will see various training metrics.</p><h4>Step 15- Train the Model</h4><pre><strong>!python model_main_tf2.py --model_dir=models/my_ssd_resnet50_v1_fpn --pipeline_config_path=models/my_ssd_resnet50_v1_fpn/pipeline.config</strong></pre><pre><em># !python model_main_tf2.py --model_dir=models/[name_of_pre-trained-model_you_downloaded] --pipeline_config_path=models/[name_of_pre-trained-model_you_downloaded]/pipeline.config</em></pre><p>Once your model training starts, you should see output similar to one shown below:</p><pre>INFO:tensorflow:Step 100 per-step time 1.154s loss=0.899<br>I0918 04:22:33.549013 140442778175360 model_lib_v2.py:652] Step 100 per-step time 1.154s loss=0.899<br>INFO:tensorflow:Step 200 per-step time 1.133s loss=0.861<br>I0918 04:24:27.194712 140442778175360 model_lib_v2.py:652] Step 200 per-step time 1.133s loss=0.861<br>INFO:tensorflow:Step 300 per-step time 1.138s loss=0.685<br>I0918 04:26:20.992518 140442778175360 model_lib_v2.py:652] Step 300 per-step time 1.138s loss=0.685<br>INFO:tensorflow:Step 400 per-step time 1.131s loss=0.546<br>I0918 04:28:14.755549 140442778175360 model_lib_v2.py:652] Step 400 per-step time 1.131s loss=0.546<br>…</pre><p>You can see various training parameters/metrics (like classification_loss, total_loss,learning_rate…) in your TensorBoard. The training log displays loss once after every 100 steps.</p><p>Training time depends on several factors, such as batch_size, the complexity of objects, hyper-parameters, etc; so be patient and don’t cancel the process.</p><p>A new checkpoint file is saved every 1000 steps. (These checkpoints can be used to restore training progress and continue model training)</p><p>It is advisable to train the model until the loss is constantly below 0.3! If you do not achieve good results, you can continue training the model (the checkpoints will allow you to restore training progress) until you get satisfactory results!</p><h4>Step 16- Export the Trained Model</h4><p>We have finished training our model, it’s time to extract our saved_model. This saved_model will be used to perform object recognition.</p><pre><strong>!python exporter_main_v2.py --input_type image_tensor --pipeline_config_path ./models/my_ssd_resnet50_v1_fpn/pipeline.config --trained_checkpoint_dir ./models/my_ssd_resnet50_v1_fpn/ --output_directory ./exported-models/my_model</strong></pre><pre><em># !python exporter_main_v2.py --input_type image_tensor --pipeline_config_path ./models/[name_of_pre-trained-model you downloaded]/pipeline.config --trained_checkpoint_dir ./models/[name_of_pre-trained-model_you_downloaded]/ --output_directory ./exported-models/my_model</em></pre><p>You should now have a new folder named ‘<strong>my_model</strong>’ inside your<strong> </strong>‘training_demo/exported-models’ directory. This folder contains our saved_model.</p><p>Now it’s time to test our trained model!</p><h4>Step 17- Testing the model (Loading saved_model)</h4><pre><em>#Loading the saved_model(change the path according to your directory names)</em></pre><pre><strong>import tensorflow as tf<br>import time<br>from object_detection.utils import label_map_util<br>from object_detection.utils import visualization_utils as viz_utils</strong></pre><pre><strong>PATH_TO_SAVED_MODEL=&quot;/content/gdrive/My Drive/TensorFlow/workspace/training_demo/exported-models/my_model/saved_model&quot;</strong></pre><pre><strong>print(&#39;Loading model...&#39;, end=&#39;&#39;)</strong></pre><pre><em># Load saved model and build the detection function</em><br><strong>detect_fn=tf.saved_model.load(PATH_TO_SAVED_MODEL)</strong></pre><pre><strong>print(&#39;Done!&#39;)</strong></pre><h4>Step 18- Testing the model (Loading label_map)</h4><pre><em>#Loading the label_map</em><br><strong>category_index=label_map_util.create_category_index_from_labelmap(&quot;/content/gdrive/My Drive/TensorFlow/workspace/training_demo/annotations/label_map.pbtxt&quot;,use_display_name=True)</strong></pre><pre><em>#category_index=label_map_util.create_category_index_from_labelmap([path_to_label_map],use_display_name=True)</em></pre><h4>Step 19- Testing the model (Loading images)</h4><pre><em>#Loading the image</em><br><strong>img=[&#39;/content/img1.jpg&#39;,&#39;/content/img2.jpg&#39;]<br>print(img)</strong></pre><pre><em>#list containing paths of all the images</em></pre><h4>Step 20- Running the Inference</h4><pre><strong>import numpy as np<br>from PIL import Image<br>import matplotlib.pyplot as plt<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</strong></pre><pre><strong>def load_image_into_numpy_array(path):<br>    return np.array(Image.open(path))</strong></pre><pre><strong>for image_path in img:</strong></pre><pre><strong>print(&#39;Running inference for {}... &#39;.format(image_path), end=&#39;&#39;)<br>    image_np=load_image_into_numpy_array(image_path)</strong></pre><pre><strong>input_tensor=tf.convert_to_tensor(image_np)<br>    input_tensor=input_tensor[tf.newaxis, ...]</strong></pre><pre><strong>detections=detect_fn(input_tensor)</strong></pre><pre><strong>num_detections=int(detections.pop(&#39;num_detections&#39;))<br>    detections={key:value[0,:num_detections].numpy()<br>                   for key,value in detections.items()}<br>    detections[&#39;num_detections&#39;]=num_detections</strong></pre><pre><strong>detections[&#39;detection_classes&#39;]=             detections[&#39;detection_classes&#39;].astype(np.int64)</strong></pre><pre><strong>image_np_with_detections=image_np.copy()</strong></pre><pre><strong>viz_utils.visualize_boxes_and_labels_on_image_array(<br>          image_np_with_detections,<br>          detections[&#39;detection_boxes&#39;],<br>          detections[&#39;detection_classes&#39;],<br>          detections[&#39;detection_scores&#39;],<br>          category_index,<br>          use_normalized_coordinates=True,<br>          max_boxes_to_draw=100,     <br>          min_score_thresh=.5,      <br>          agnostic_mode=False)</strong></pre><pre><strong>%matplotlib inline<br>    plt.figure()<br>    plt.imshow(image_np_with_detections)<br>    print(&#39;Done&#39;)<br>    plt.show()</strong></pre><p>If everything is successful, you should see your loaded images with bounding boxes, labels, and accuracy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*T6a2KSL6-Zo-kAkwUYS1ZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*DsfmJzlv-7Znvw_vyBi8pw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*wSdVezBbS6fIBRUoE9sLpw.png" /><figcaption>Output with Bounding Boxes, Labels, and Accuracy!</figcaption></figure><h4>Acknowledgments and References:</h4><p>Huge Thanks to <a href="http://pcwww.liv.ac.uk/~sglvladi/">Lyudmil Vladimirov</a> for allowing me to use some of the content from their amazing <a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/index.html">TensorFlow 2 Object Detection API</a> for Local Machines!<br>Link to their <a href="https://github.com/sglvladi/TensorFlowObjectDetectionTutorial">GitHub Repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2af171e81cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/tensorflow-2-object-detection-api-with-google-colab-b2af171e81cc">TensorFlow 2 Object Detection API With Google Colab</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>