<?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 Vivek on Medium]]></title>
        <description><![CDATA[Stories by Vivek on Medium]]></description>
        <link>https://medium.com/@vivekpothina?source=rss-66d6483c019e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*I_iW79bLnh7EqrXN.</url>
            <title>Stories by Vivek on Medium</title>
            <link>https://medium.com/@vivekpothina?source=rss-66d6483c019e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:31:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vivekpothina/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[Working with Kaggle Dataset on Google Colab(Free GPU)]]></title>
            <link>https://medium.com/robotics-club-sastra/working-with-kaggle-dataset-on-google-colab-d3d4a77ead62?source=rss-66d6483c019e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3d4a77ead62</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vivek]]></dc:creator>
            <pubDate>Wed, 30 May 2018 16:44:42 GMT</pubDate>
            <atom:updated>2019-03-18T07:08:24.368Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with Kaggle Dataset on Google Colab(Free GPU)</p><p>Hello! Many of you will be grateful after reading this blog. Probably, you might have already heard of Google Colab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eVj4oYbhhhAfxlixTwMmA.png" /></figure><p>Colab is a Google’s free cloud service which will let you run your deep learning or machine learning models in cloud.<strong><em> And the best part is, it is completely free. There’s more, you can even run it on a GPU! Don’t believe me, </em></strong><a href="https://colab.research.google.com/"><strong><em>take a look yourself</em></strong></a><strong><em>.</em></strong></p><p>I used Google Colab to complete my Capstone project for my Udacity Machine Learning Nanodegree. I worked on <a href="https://www.kaggle.com/c/planet-understanding-the-amazon-from-space/">Planet: Understanding the Amazon from Space</a>, a completed competition on Kaggle.</p><p>But in this blog, we won’t be going through my capstone. In this, I’ll go through the basic stuff. I’ll just try to build a CNN model in Keras solving Dog Breed Classification.</p><p>In this blog, you will see how to:</p><ul><li>Use Google Colab</li><li>Load data from Kaggle</li><li>Pre-process data</li><li>Build a deep learning model for the data</li></ul><h3><strong>How to use Google Colab?</strong></h3><p>OK, for starters, Google Colab is free Google customized jupyter notebook, which runs on Google’s servers. There is an option to run these notebooks on GPU too. Like I mentioned before, you can run your code on free GPU.</p><p>If you don’t know what jupyter notebook is and how to use it, and if you’re fairly new to the whole Machine Learning world, don’t worry, there are a lot of tutorials out there and you can use them. Try <a href="https://github.com/nborwankar/LearnDataScience">https://github.com/nborwankar/LearnDataScience</a>. It’s one of the best places to start.</p><p>Using Google Colab is similar to using your jupyter notebook. To try it out, just go to <a href="https://colab.research.google.com/">https://colab.research.google.com/</a></p><h3><strong>Moving on, let’s see how to load data from Kaggle.</strong></h3><p>Kaggle provides a command line tool to make downloading datasets easier.</p><p>To install Kaggle CLI in Colab, use this command</p><pre># To install Kaggle CLI<br>!pip install kaggle</pre><p>But for the Kaggle-CLI to work, a kaggle.json specific to the user needs to be in the system of usage. As you can see, we don’t have direct system access in Google Colab. Follow these simple steps:</p><ul><li>Go to <a href="https://www.kaggle.com/%7BUsername%7D/account">https://www.kaggle.com/{Username}/account</a></li><li>Scroll down and download the kaggle.json by clicking ‘Create New API Token’</li><li>Upload the kaggle.json file to your Google Drive</li><li>Then, run the below script</li><li>A new tab will open, select your google account</li><li>Copy the authentication code and paste it in the field of the below cell.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/937c7256e347d6f2ef3b167fca621dc0/href">https://medium.com/media/937c7256e347d6f2ef3b167fca621dc0/href</a></iframe><p>I, personally, thank <a href="https://medium.com/@move37timm/using-kaggle-api-for-google-colaboratory-d18645f93648">https://medium.com/@move37timm/using-kaggle-api-for-google-colaboratory-d18645f93648</a>, for this part.</p><p>Now, that our Kaggle CLI is set, let’s download the dataset.</p><pre># Use this command in new cell<br>!kaggle datasets download -d stanfordu/street-view-house-numbers -w -f street-view-house-numbers.zip</pre><pre># Unzip the data<br>!unzip street-view-house-numbers.zip<br>!unzip train.zip</pre><pre># Use this command to view your files<br>!ls</pre><h3><strong>Now that Data is here, it’s time to play with it.</strong></h3><pre># Importing modules<br>from matplotlib import pyplot as plt<br>import numpy as np<br>import pandas as pd<br>import os, random, cv2<br>%matplotlib inline</pre><pre># Let&#39;s check the labels<br>labels_df = pd.read_csv(&quot;labels.csv&quot;)<br>labels_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*jpMEdwA5JnjRcBUKTOCzWQ.png" /><figcaption>labels_df.head( )</figcaption></figure><pre># Let&#39;s encode the labels<br>labels_map = {}<br>inv_labels_map = {}<br>count = 0<br>for label in labels_df[&#39;breed&#39;]:<br>  if(label in labels_map):<br>    continue<br>  labels_map[label] = count<br>  inv_labels_map[count] = label<br>  count = count + 1<br># print(&quot;Label Map: &quot;, labels_map)<br># print(&quot;No. of Labels are: &quot;, count)</pre><pre># Let&#39;s check the distribution of the classes we have<br>labels_count = {}<br>for label in labels_df[&#39;breed&#39;]:<br>  if(label in labels_count):<br>    labels_count[label] = labels_count[label] + 1<br>  else:<br>    labels_count[label] = 0<br># print(labels_count)<br>plt.figure(figsize=(40,10))<br>plt.bar(list(labels_count.keys()), list(labels_count.values()),width=0.6)<br>plt.xticks(rotation = 90)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_JfGlSVAAiMcyluAFo_WQ.png" /><figcaption>I know the image is large, but we are working on 120 labels here</figcaption></figure><p>For each breed, there’s at least 60 images, but this data is not enough for training our model. But for simplicity, let’s not dwell into image augmentation.</p><pre># Now, let&#39;s check the images we have in training data<br>example_img = random.choice(os.listdir(&quot;train&quot;))<br>print(&quot;Label:&quot;, labels_df.loc[labels_df[&#39;id&#39;] == example_img[:-4]][&#39;breed&#39;].all())<br>example_img = plt.imread(&quot;train/&quot;+example_img)<br>plt.grid(False)<br>plt.imshow(example_img)<br>print(&quot;Shape of the image is:&quot;, example_img.shape)<br>print(&quot;Max:&quot;, example_img.max(), &quot;, Min:&quot;, example_img.min())</pre><pre># Running this cell for few, we can understand that the shapes of the images keep varying, we solve this problem by resizing the images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*UxPTbwuX_jGw05GkU1rstQ.png" /><figcaption>The above cell will select random images from the dataset</figcaption></figure><p>Now, it’s time to create training, validation and test set. We’ll be using some standard proportion like 60:20:20.</p><pre>x_train = []<br>y_train = []</pre><pre>for ids, label in labels_df.values:<br>  img_path = &quot;train/&quot;+ids+&quot;.jpg&quot;<br>  img = cv2.imread(img_path)<br>  target = np.zeros(120)<br>  x_train.append(np.array(cv2.resize(img,(224,224))))<br>  target[labels_map[label]] = 1<br>  y_train.append(target)</pre><pre># Converting lists into numpy arrays<br># Our training set is divided by 255 to normalize the image data<br>y_train = np.array(y_train, np.uint8)<br>x_train = np.array(x_train, np.float16) / 255.<br># print(len(x_train), len(y_train), x_train.shape, y_train.shape)</pre><pre># Splitting the data into Training, Validation and Test set</pre><pre>test_split = int(length*0.8)<br>x_train, x_test, y_train, y_test = x_train[:test_split], x_train[test_split:], y_train[:test_split], y_train[test_split:]</pre><pre>valid_split = int(length*0.6)<br>print(&quot;Training set: &quot;, valid_split)<br>x_train, x_valid, y_train, y_valid = x_train[:valid_split], x_train[valid_split:], y_train[:valid_split], y_train[valid_split:]</pre><pre>print(&quot;Validation set: &quot;, str(test_split - valid_split))<br>print(&quot;Test set: &quot;, str(length - test_split))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*Dp8nS2UfsliavBS7GoEksQ.png" /></figure><h3>Time to Build the CNN model</h3><p>Finally, let’s build our CNN model and train it to see how it performs on the dataset.</p><pre># Importing<br>import tensorflow as tf<br>from tensorflow.python.keras.layers import BatchNormalization, Conv2D, MaxPooling2D, Dense, Dropout, Flatten, Activation, GlobalAveragePooling2D<br>from tensorflow.python.keras import Model, Sequential, optimizers</pre><pre>model = Sequential()<br>model.add(BatchNormalization(input_shape=(224, 224, 3)))<br>model.add(Conv2D(filters=16, kernel_size=3, kernel_initializer=&#39;he_normal&#39;, activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=2))<br>model.add(BatchNormalization())</pre><pre>model.add(Conv2D(filters=32, kernel_size=3, kernel_initializer=&#39;he_normal&#39;, activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=2))<br>model.add(BatchNormalization())</pre><pre>model.add(Conv2D(filters=64, kernel_size=3, kernel_initializer=&#39;he_normal&#39;, activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=2))<br>model.add(BatchNormalization())</pre><pre>model.add(Conv2D(filters=128, kernel_size=3, kernel_initializer=&#39;he_normal&#39;, activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=2))<br>model.add(BatchNormalization())</pre><pre>model.add(Conv2D(filters=256, kernel_size=3, kernel_initializer=&#39;he_normal&#39;, activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=2))<br>model.add(BatchNormalization())</pre><pre>model.add(GlobalAveragePooling2D())</pre><pre>model.add(Dense(num_classes, activation=&#39;softmax&#39;))</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*6ndC-R32lrOAuzFwSKk0Gw.png" /><figcaption>Architecture of CNN model</figcaption></figure><p>Set up the hyper parameters and tune it for better performance.</p><pre>batch_size = 128<br>epochs = 20<br>learning_rate = 0.001<br>num_classes = 120</pre><p>Time to train the model and evaluate on the validation set.</p><pre># Training the model</pre><pre>opt = optimizers.Adam(lr = learning_rate)</pre><pre>model.compile(loss=&#39;categorical_crossentropy&#39;,optimizer=opt,metrics=[&#39;accuracy&#39;])<br>m = model.fit(x_train, y_train, validation_data=(x_valid, y_valid),<br>                  batch_size=batch_size,verbose=2, epochs=epochs, shuffle = True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*i0Bcr1Se0XHwQrK7iDqlVg.png" /></figure><p><em>20 epochs completed in almost 500 sec, that’s like 8 min!</em> This is how GPU can speed up your Deep Neural Nets!</p><p>Notice the huge difference between training accuracy and validation accuracy, the model is clearly overfitting. This is the advantage of using validation set. But for this dataset, this model is performing well. Usually, better performance can be achieved on this model using data augmentation or Transfer Learning. <em>Like I already mentioned, this is out of scope of this tutorial.</em></p><pre># Running the model on test set<br>scores = model.evaluate(x_test, y_test, verbose = 1)<br>print(scores[1])</pre><pre># Graph of loss per epoch<br>plt.plot(m.history[&#39;loss&#39;])<br>plt.plot(m.history[&#39;val_loss&#39;])<br>plt.xlabel(&quot;epoch&quot;, fontsize = &quot;16&quot;)<br>plt.ylabel(&quot;loss/validation_loss&quot;, fontsize = &quot;16&quot;)<br>plt.show()</pre><pre># Graph of accuracy per epoch<br>plt.plot(m.history[&#39;acc&#39;])<br>plt.plot(m.history[&#39;val_acc&#39;])<br>plt.xlabel(&quot;epoch&quot;, fontsize = &quot;16&quot;)<br>plt.ylabel(&quot;accuracy/validation_accuracy&quot;, fontsize = &quot;16&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXKZOPjc1GXI9M_FDNvAog.png" /><figcaption>Evaluation of the model (it’s overfitting)</figcaption></figure><p>That’s it! We built a CNN model in Google Colab. Using GPU, we finished the training in 8 min. Further, you can work on the accuracy issue of the model.</p><p><strong><em>All the code is in my </em></strong><a href="https://github.com/ViveK-PothinA/Misc-Notebooks-Scripts/blob/master/Blog1_DogBreedClassification(Keras).ipynb"><strong><em>Github</em></strong></a><strong><em> or you can refer to my </em></strong><a href="https://drive.google.com/file/d/1y_yjREG_qpjhK1rndedUZaJp8bk6BQ5s/view?usp=sharing"><strong><em>Colab notebook</em></strong></a><strong><em> (You can use it after adding it your drive).</em></strong></p><p>It’s just great that Google is offering free GPU on cloud. There are some issues like sometimes the Runtime gets disconnected abrupting your workflow, <em>but come on you’re using a GPU on cloud for free!</em></p><p>There’s lot of other cool features. Like all your Colab Notebooks are saved in your Google Drive. You can check out Revision History and revert back to code you’ve written before. You can directly upload your Notebooks to Github repos or Github Gists. And your notebooks can be shared to your friends who have Google accounts, which makes collaborative working easier.</p><p>Use this cool tool for your Deep Learning projects. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3d4a77ead62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/robotics-club-sastra/working-with-kaggle-dataset-on-google-colab-d3d4a77ead62">Working with Kaggle Dataset on Google Colab(Free GPU)</a> was originally published in <a href="https://medium.com/robotics-club-sastra">Robotics Club @ SASTRA</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>