<?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 Vishakha Hegde on Medium]]></title>
        <description><![CDATA[Stories by Vishakha Hegde on Medium]]></description>
        <link>https://medium.com/@vishakhahegde23?source=rss-12aabeae13ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3DbrG2fP4oDH-FUsMV5kCQ.jpeg</url>
            <title>Stories by Vishakha Hegde on Medium</title>
            <link>https://medium.com/@vishakhahegde23?source=rss-12aabeae13ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:02:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vishakhahegde23/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[Zone Violation Detector Using Streamlit and MMDetection]]></title>
            <link>https://medium.com/@vishakhahegde23/zone-violation-detector-using-streamlit-and-mmdetection-8d41902294ca?source=rss-12aabeae13ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d41902294ca</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mmdetection]]></category>
            <dc:creator><![CDATA[Vishakha Hegde]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 12:33:35 GMT</pubDate>
            <atom:updated>2023-08-26T12:33:35.982Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qu-1_DBzIPGacVse4JiLTg.jpeg" /></figure><p>In this project, we will see how to build a zone violation detector using pre-trained object detection models and then deploy it using Streamlit.</p><blockquote><strong>Streamlit</strong> is an open-source app framework for Machine Learning and Data Science projects. Create beautiful web apps in minutes, without any knowledge of front-end development.</blockquote><p>The goal of this project would be to detect a violation when a person is walking in a no-walking zone. This is a relevant problem statement whose solution could be implemented in various places — from industries/factories for workers’ safety, to pedestrian crossings and schools.</p><p>Although we will eventually use Ubuntu to deploy our model on Streamlit, we will first test different models on Google Colabs.</p><p>Let’s get started!</p><h3>STEP 1: Data Collection and Annotation</h3><p>First, create a new project folder on your Google Drive where we will store all our images.</p><p>Download around 50 different images of people walking, running, sitting, etc. Make sure you have images of various different angles — top, side, straight, bottom, and so on. Doing so will ensure that you pick the most appropriate model later on.</p><p>The next thing is to annotate these images. I used LabelImg to annotate them and stored the annotations in .xml format.</p><p>On the Anaconda prompt, these commands should open LabelImg after installing it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*kYo1k6vgQKKn5J1M3TK0nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JgCYSi3I3O1HeUKA1G_iw.png" /><figcaption>Annotating on LabelImg</figcaption></figure><p>The .xml annotations should be saved in a separate folder. Don’t forget to add this annotation folder to your Drive as well!</p><h3>STEP 2: Find a Suitable Object Detector</h3><p>The world of computer vision is vast and there are many detectors to choose from. For this project, let’s look at the MMDetection model zoo.</p><blockquote>MMDetection is <strong>a Python toolbox built as a codebase exclusively for object detection and instance segmentation tasks</strong>.</blockquote><p>Read about the installation and model zoo from the documentation <a href="https://mmdetection.readthedocs.io/en/latest/">here</a>.</p><h4><strong>1. Install MMDetection:</strong></h4><p>Open a new notebook on Google Colab, mount your drive and <strong>install the</strong> <strong>necessary dependencies</strong> in your project folder for MMDetection to run.</p><pre>#mounting the drive<br>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)</pre><pre>#installing dependencies in your project folder<br>%cd &#39;/content/drive/MyDrive/Project Data&#39;<br>!pip install -U openmim<br>!mim install mmcv-full<br>!git clone <a href="https://github.com/open-mmlab/mmdetection.git">https://github.com/open-mmlab/mmdetection.git</a><br>%cd mmdetection<br>!pip install -v -e .</pre><p>On successful installation, you should see a folder named ‘mmdetection’ in your project folder.</p><p>Now, let us choose which models to test our images on. For this project, I picked <strong>Retinanet, Faster RCNN, YOLOv3 and YOLOx, </strong>which are<strong> </strong>all available in the MMDetection framework.</p><h4>2. Download Checkpoints</h4><p>All these models are pre-trained on the <a href="https://cocodataset.org/#home">COCO dataset</a>, so we will need to load the pre-trained <strong>weights/checkpoints </strong>of the model. Navigate to your Drive, and create a new folder named ‘checkpoints’ inside your mmdetection folder.</p><p>Follow the links from this <a href="https://mmdetection.readthedocs.io/en/latest/model_zoo.html">benchmark page</a>, choose your desired model and download the checkpoints from Github. Below is the Github result for FasterRCNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiOUPQVb5AMTRL4-gm4nvw.png" /><figcaption>Click on ‘model’ to download the checkpoints for the corresponding backbone</figcaption></figure><p>Once you have downloaded checkpoints for all desired models, put them in the checkpoint folder.</p><h4>3. Comparing Annotations and Model Results</h4><p>Now, we will <strong>compare our annotations with the result of every model</strong> and choose the one that’s best suited for our project.</p><pre>from mmdet.apis import init_detector,inference_detector<br>import mmcv<br>import matplotlib.pyplot as plt<br>import cv2<br>import os<br>import xml.etree.ElementTree as ET<br>import matplotlib.pyplot as plt</pre><p>Function to <strong>extract bounding box coordinates from xml files</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ded2a5aa6c9fab6da338ae9f593f265f/href">https://medium.com/media/ded2a5aa6c9fab6da338ae9f593f265f/href</a></iframe><p>Function to <strong>extract model-detected coordinates, plot both annotations and model results</strong> for every image, and store these new images in a different folder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b3fc08bd5aac34cd0363bf88f022b64/href">https://medium.com/media/8b3fc08bd5aac34cd0363bf88f022b64/href</a></iframe><p>For ease of usage, I named every image in my dataset by numbers. Their corresponding annotations too have the same name. The below code creates a list of all the image and annotation file names from their respective folders:</p><pre>#getting the images and xml annotation files</pre><pre>%cd /content/drive/My Drive/Project Data/data/test<br>list_img=os.listdir(&quot;.&quot;)<br>%cd ..<br>%cd test_anno<br>list_anno=os.listdir(&quot;.&quot;)<br>list_img.sort()<br>list_anno.sort()</pre><p>We are now ready to test our images on different models. First, we load the config and checkpoint files, declare the path where we want to save the resultant images and give a confidence score. Then we pass all of these into the functions we declared earlier.</p><pre>config_file=&#39;/content/drive/My Drive/Project Data/mmdetection/configs/yolo/yolov3_d53_320_273e_coco.py&#39;</pre><pre>checkpoint_file=&#39;/content/drive/My Drive/Project Data/mmdetection/checkpoints/yolov3_d53_mstrain-416_273e_coco-2b60fcd9.pth&#39;</pre><pre>save_dir=&#39;/content/drive/MyDrive/Project Data/data/results/YOLOv3&#39;</pre><pre>confidence_score=0.6</pre><pre>Result(list_img,list_anno,config_file,checkpoint_file,confidence_score,save_dir)</pre><p>The above example is for YOLOv3. Cross-check the config and checkpoint files to see if they are for the same model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iwe-8TJC2x2NDdocLaZ4DA.png" /><figcaption>Green boxes correspond to annotations, Blue boxes correspond to what the model predicted.</figcaption></figure><p>Try the same for different models to see what suits your project the best. Save the results of each in a different folder.</p><h4>4. Analyze</h4><p>Once the images have been generated for all models, you can either manually go through the images or write a function that calculates the IOU of annotated boxes and detected boxes to determine the model&#39;s accuracy.</p><p>Experiment and play around — try changing the confidence threshold to see if you get better results. It is a good practice to tabulate your findings like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*MSNByZq56EWcYoT9WmGrcg.png" /></figure><p>Personally, I decided <strong>FasterRCNN</strong> would be the best fit for my project since it gave a decent accuracy and was faster than the others.</p><p>Phew, that was a lot to take in! With our desired model in hand, it’s time to set up everything on Ubuntu.</p><h3>STEP 3: Setting It Up On Ubuntu</h3><p>I ran into quite a few problems while using Colabs and hence decided to shift to Ubuntu on my VirtualBox.</p><p>Make sure you have Git and Anaconda/Miniconda installed beforehand. Create a new project folder on your Ubuntu and navigate to it on the command line. Then type out the following commands to <a href="https://mmdetection.readthedocs.io/en/v1.2.0/INSTALL.html">install MMDetection:</a></p><p>a. Create a conda virtual environment and activate it.</p><pre>conda create -n open-mmlab python=3.7 -y<br>conda activate open-mmlab</pre><p>b. Install PyTorch and torchvision.</p><pre>conda install pytorch torchvision -c pytorch</pre><p>c. Clone the mmdetection repository.</p><pre>git clone https://github.com/open-mmlab/mmdetection.git<br>cd mmdetection</pre><p>d. Install build requirements and then install mmdetection.</p><pre>pip install -r requirements/build.txt<br>pip install &quot;git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI&quot;<br>pip install -v -e .  <em># or &quot;python setup.py develop&quot;</em></pre><p>e. Set up Streamlit within the same environment.</p><pre>pip install streamlit</pre><p>f. Test that the installation worked:</p><pre>streamlit hello</pre><p>If you’ve done everything right, Streamlit’s Hello app should appear in a new tab in your web browser!</p><h3>STEP 4: Integrating With Streamlit</h3><p>First, we allow the user to upload an image using the st.file_uploader() function.</p><p>Next, we need to write a block of code that will enable users to draw a safe zone (in the form of a polygon) on the image. For this, I used the <a href="https://pypi.org/project/streamlit-drawable-canvas/">Streamlit drawable canvas</a> library. We must also make sure that the coordinates of this polygon can be extracted and used in another function to detect violations.</p><p>The major logic of the code is to detect people’s feet to determine whether or not they are within the safe zone. To detect people’s feet approximately, we can use the below formula, where (x1,y1) are coordinates in the top left corner and (x2,y2) are coordinates in the bottom right corner of the bounding boxes detected by our model:</p><blockquote>midx=x1+(x2-x1)/2</blockquote><blockquote>midy=y2</blockquote><p>After this, we can ascertain whether (midx,midy) lies within the polygon coordinates or not using the function <a href="https://stackoverflow.com/questions/57312028/problem-with-using-cv2-pointpolygontest-and-cv2-polylines">cv2.pointPolygonTest</a>(). The people inside the safe zone will have green bounding boxes, while violations will have red bounding boxes.</p><p>Here is the code for the entire single-page app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74140cf8833e31974d7499ecf1a79a69/href">https://medium.com/media/74140cf8833e31974d7499ecf1a79a69/href</a></iframe><p>To run the app, go to your project folder on the terminal and activate your environment.</p><pre>conda activate open-mmlab</pre><p>Then run your Streamlit app.</p><pre>streamlit run &lt;name_of_app&gt;.py</pre><p>Here is what the final page looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*hg1h2XQyn0YKs8jlKyGjWQ.png" /><figcaption>After user draws the polygon</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*A8DxB2bApk8QqwzeDinUQQ.png" /><figcaption>Results</figcaption></figure><p>I also converted this into a <a href="https://docs.streamlit.io/library/get-started/main-concepts#pages">multipage app</a> to detect multiple other violations and I suggest trying that out as it will give you a better grip working with Streamlit.</p><h3>STEP 5: Hosting Your App Onto Streamlit Cloud</h3><p>First, create a repository on GitHub with all dependencies and files. Then follow the instructions in this link <a href="https://docs.streamlit.io/streamlit-cloud/get-started/deploy-an-app">https://docs.streamlit.io/streamlit-cloud/get-started/deploy-an-app</a>. Your app is now deployed!</p><h3>Conclusion</h3><p>This project was instrumental in helping me get my hands dirty with various machine learning models and the Streamlit framework as well.</p><p>Here is the Github link for the project: <a href="https://github.com/vishakhahegde/Violation-Detector">https://github.com/vishakhahegde/Violation-Detector</a></p><p>Hope you enjoyed reading as much as I enjoyed innovating! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d41902294ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convolutional Neural Networks with Keras]]></title>
            <link>https://medium.com/@vishakhahegde23/convolutional-neural-networks-with-keras-2935d01e7072?source=rss-12aabeae13ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/2935d01e7072</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[mnist]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Vishakha Hegde]]></dc:creator>
            <pubDate>Sun, 10 Jul 2022 16:58:33 GMT</pubDate>
            <atom:updated>2022-07-11T05:23:31.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/926/0*2RWBEOxVTz8OBQ4Z" /></figure><p>The intent of this blog is to get you familiarised with the basics of how to build a CNN using Keras and Tensorflow.</p><p>As the Keras documentation says:</p><blockquote>Keras is an API designed for human beings, not machines.</blockquote><p>It is indeed very beginner-friendly and the perfect API to kick-start your deep learning journey.</p><p>I would recommend reading up a bit about CNNs and deep learning before you delve into this blog to fully understand its contents.</p><p>In this tutorial, we will explore the MNIST data set — the ‘hello world’ of computer vision. The MNIST data set is an extensive database of handwritten digits commonly used to train image processing systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*rXgJjMVFVp0JSWlIhMezwA.jpeg" /><figcaption>MNSIT Dataset</figcaption></figure><p>Personally, I find the Jupyter Notebook highly convenient for deep learning and ML, so that is what I will be using for this tutorial, but you’re free to use any other platform you like. That being said, let’s dive right in.</p><h4><strong>Import Required Modules</strong></h4><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from random import randint</pre><pre>#keras and tensorflow modules<br>from keras.models import Sequential<br>from keras.layers import Dense, Activation, Dropout, Flatten<br>from keras.layers import Conv2D, MaxPooling2D<br>from tensorflow.keras.optimizers import Adam<br>from keras.datasets import mnist<br>from tensorflow.keras.utils import to_categorical,plot_model<br>from keras.models import load_model</pre><p>All of these libraries can be installed using the simple pip install command.</p><p>The <em>NumPy</em> library supports large, multi-dimensional arrays and matrices, along with multiple mathematical functions to operate on these arrays.</p><p><em>Pandas</em> is used for data manipulation, analysis and operations on data structures.</p><p><em>Matplotlib</em> is a plotting library used to create interactive visualizations in Python.</p><p>We’ll look at the <em>Keras</em> and <em>Tensorflow</em> functions a bit later.</p><h4><strong>Load the Data</strong></h4><p>The MNIST dataset is already present in the Keras library, so there is no need to externally download it.</p><pre>(x_train,y_train),(x_test,y_test)=mnist.load_data()</pre><p>Here we load the data into two different sets — training and test sets. We will first train our model on the training data and then evaluate its accuracy using the test data.</p><h4><strong>Analyze the Data</strong></h4><p>Before we start building our model, we need to know what our data looks like.</p><pre>print(x_train.shape,x_test.shape)<br>#output: (60000, 28, 28) (10000, 28, 28)</pre><p>This tells us that our training and test datasets have 60,000 and 10,000 images respectively, each of size 28x28 pixels. Let’s look at one of the images from the set.</p><pre>plt.imshow(x_train[9],cmap=&#39;gray&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*3XRnDEQv4XvijiIY0ttKQw.png" /></figure><p>Let’s now analyze the labels.</p><pre>print(y_train.shape,y_test.shape)<br>#output: (60000,) (10000,)</pre><pre>print(y_train[9])<br>#output: 4</pre><p>From this, we can infer that our input to the model would be a 28x28 image and the output would be a correct prediction of the digit — a number between 0 and 9.</p><h4><strong>Clean, Reshape and Normalize the Data</strong></h4><p>Now that we’ve seen what kind of data we’re dealing with, let’s go ahead and tweak the data as per our requirements.</p><p>We need to reshape the images into something that our model can recognize. When using Tensorflow, we must explicitly declare the number of channels in our image. Thus, we want to transform our dataset from having shape (no. of images, width, height) to (no. of images, width, height, channels). 1 represents grayscale (single channel) in the below code.</p><pre>#reshape the data<br>x_train=x_train.reshape(x_train.shape[0],28,28,1)<br>x_test=x_test.reshape(x_test.shape[0],28,28,1)</pre><p>Next, we convert the values to float and normalize the pixel values in the range [0,1].</p><pre>#normalize values<br>x_train = x_train.astype(&#39;float32&#39;)<br>x_test = x_test.astype(&#39;float32&#39;)<br>x_train/=255<br>x_test/=255</pre><p>Since we want our model to predict digits, our output/labels will be in the range (0,9). This can be easily represented using <em>one-hot encoding. </em>For example, if we want to represent the digit 4, then the one-hot encoding would be an array as such: [0,0,0,0,1,0,0,0,0,0]. Use the Keras to_categorical() function to do so.</p><pre>#one hot encoding<br>y_train=to_categorical(y_train)<br>y_test=to_categorical(y_test)</pre><p>Our data is now ready to be used!</p><h4><strong>Build the Model Architecture</strong></h4><p>We’ll use the Keras Sequential() function to create a layer-by-layer sequential model.</p><pre>model=Sequential()</pre><p>Layers can be added to the sequential model using the add() function.</p><p>First, we’ll add two convolutional layers with 64 and 32 nodes in each layer respectively and a 3x3 kernel. The ReLu activation function is used.</p><pre>model.add(Conv2D(64,kernel_size=3,activation=&#39;relu&#39;,input_shape=(28,28,1)))<br>model.add(Conv2D(32,kernel_size=3,activation=&#39;relu&#39;))</pre><p>This will be followed by a Max Pooling layer of pool size 2x2.</p><pre>model.add(MaxPooling2D(pool_size=(2,2)))</pre><p>To prevent model overfitting, we use <em>Dropout Regularization. </em>The Dropout layer randomly sets input units to 0 with a certain frequency at each step during training time.</p><pre>model.add(Dropout(0.25))</pre><p>Our model will have both <em>convolutional</em> and <em>dense</em> (fully connected) layers. Hence, to connect these two, we use a <em>‘Flatten’</em> layer. This is followed by regularization again.</p><pre>model.add(Flatten()) #connection bw conv and dense layers<br>model.add(Dense(128,activation=&#39;relu&#39;)) #fully connected layer with 128 nodes<br>model.add(Dropout(0.25))</pre><p>Our final layer will be a softmax that has 10 nodes — corresponding to the 10 different output digits that we can get.</p><pre>model.add(Dense(10,activation=&#39;softmax&#39;)) </pre><p>All of the functions used above have already been imported from their respective libraries in the first step.</p><p>We finally have the skeleton of our CNN!</p><h4><strong>Compiling the Model</strong></h4><p>The compile function has three parameters: loss, optimizer and metrics.</p><p>We’ll use categorical_crossentropy as our loss function as it is commonly used for multi-class classification models where there are two or more output labels.</p><p>To optimize the loss function using gradient descent, the Adam optimizer is used. Using this, the model can backpropagate and change the weight and bias values to be more optimal to reduce loss.</p><p>To assess how well our model has trained, we need a metric such as accuracy to measure model performance. This gives us the accuracy score on the validation/test set.</p><pre>model.compile(loss=&#39;categorical_crossentropy&#39;,<br>              optimizer=&#39;adam&#39;,<br>              metrics=[&#39;accuracy&#39;])</pre><h4><strong>Adding Callbacks</strong></h4><p>According to the Keras documentation,</p><blockquote>A callback is a set of functions to be applied at given stages of the training procedure. You can use callbacks to get a view on internal states and statistics of the model during training.</blockquote><p>We can use callbacks to automate certain tasks after every training set/epoch. Since model training can take quite some time, depending on your system capabilities, number of training epochs, etc., we would like to save our model to avoid retraining it everytime we want to reload the model.</p><p>The ModelCheckpoint callback does just this. It saves the model after every epoch in a specified filepath, but since the ‘save_best_only’ parameter is set to True, the model saves only the best epoch (with highest accuracy) in this case.</p><pre>from keras.callbacks import ModelCheckpoint</pre><pre>filepath=&#39;best_model.h5&#39;<br>checkpoint=ModelCheckpoint(filepath=filepath,monitor=&#39;val_loss&#39;,verbose=1,save_best_only=True,mode=&#39;min&#39;)<br>callbacks=[checkpoint]</pre><p>The callbacks are stored in a list which will be used during model training.</p><h4><strong>Fitting/Training the Model</strong></h4><p>Time to finally train our model and validate it on the test set to check our accuracy. This could take some time, especially if you decide to increase the number of epochs. It took me around 12 minutes to train five epochs.</p><p>We also pass the callbacks into the fit() function.</p><pre>model.fit(x_train,y_train,epochs=5,validation_data=(x_test,y_test),callbacks=callbacks)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZP7XEH0lY8xE5kUUFTyUg.png" /></figure><p>Notice how the accuracy keeps increasing and loss keeps decreasing as the model trains on the data.</p><p>At the end of training, we can see our model has a training accuracy of around 99.12% and a test accuracy of 98.99%. Brilliant!</p><h4><strong>Load and Evaluate Model</strong></h4><p>Congrats! You’ve just finished building a convolutional neural network to classify handwritten digits! Time for the ultimate test — let’s randomly select an image from the test dataset and feed it to our model. The NumPy argmax() function chooses the class with the highest confidence value as the output of our model.</p><pre>rand=randint(0,10000)<br>inp=np.expand_dims(x_test[rand],axis=0)<br><br>model=load_model(filepath) <br>arr=model.predict(inp)[0]</pre><pre>print(&quot;Model prediction: &quot;, np.argmax(arr))<br>        <br>img=np.reshape(x_test[rand],(28,28))<br>plt.imshow(img,cmap=&#39;gray&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*AlbTE8fpLAi7awX_gb29wA.png" /></figure><p>Looks like our model works just fine! You can rerun this particular cell multiple times to feed a random image each time and get its prediction.</p><h4><strong>Summary</strong></h4><p>Here is the entire code for reference:</p><pre>#import modules<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>from random import randint<br>from keras.models import Sequential<br>from keras.layers import Dense, Activation, Dropout, Flatten<br>from keras.layers import Conv2D, MaxPooling2D<br>from tensorflow.keras.optimizers import Adam<br>from keras.datasets import mnist<br>from tensorflow.keras.utils import to_categorical,plot_model<br>from keras.models import load_model</pre><pre>#load the data<br>(x_train,y_train),(x_test,y_test)=mnist.load_data()</pre><pre>#analyze the data<br>print(x_train.shape,x_test.shape)<br>plt.imshow(x_train[9],cmap=&#39;gray&#39;)<br>print(y_train.shape,y_test.shape)<br>print(y_train[9])</pre><pre>#reshape and normalize the data<br>x_train=x_train.reshape(x_train.shape[0],28,28,1)<br>x_test=x_test.reshape(x_test.shape[0],28,28,1)</pre><pre>x_train = x_train.astype(&#39;float32&#39;)<br>x_test = x_test.astype(&#39;float32&#39;)<br>x_train/=255<br>x_test/=255</pre><pre>y_train=to_categorical(y_train)<br>y_test=to_categorical(y_test)</pre><pre>#build the model<br>model=Sequential()<br>model.add(Conv2D(64,kernel_size=3,activation=&#39;relu&#39;,input_shape=(28,28,1)))<br>model.add(Conv2D(32,kernel_size=3,activation=&#39;relu&#39;))<br>model.add(MaxPooling2D(pool_size=(2,2)))<br>model.add(Dropout(0.25))<br>model.add(Flatten()) <br>model.add(Dense(128,activation=&#39;relu&#39;)) <br>model.add(Dropout(0.25))<br>model.add(Dense(10,activation=&#39;softmax&#39;))</pre><pre>#compile the model<br>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])</pre><pre>#callbacks and model fitting<br>from keras.callbacks import ModelCheckpoint<br>filepath=&#39;best_model.h5&#39;<br>checkpoint=ModelCheckpoint(filepath=filepath,monitor=&#39;val_loss&#39;,verbose=1,save_best_only=True,mode=&#39;min&#39;)<br>callbacks=[checkpoint]</pre><pre>model.fit(x_train,y_train,epochs=5,validation_data=(x_test,y_test),callbacks=callbacks)</pre><pre>#load and evaluate model<br>rand=randint(0,10000)<br>inp=np.expand_dims(x_test[rand],axis=0)<br>model=load_model(filepath) <br>arr=model.predict(inp)[0]<br>print(&quot;Model prediction: &quot;, np.argmax(arr))      <br>img=np.reshape(x_test[rand],(28,28))<br>plt.imshow(img,cmap=&#39;gray&#39;)</pre><h4><strong>Conclusion</strong></h4><p>Do try messing around with the code by adding or removing layers, changing kernel sizes and using a different optimizer to see how it affects the accuracy.</p><p>Thank you for reading and hope you learnt something new today! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2935d01e7072" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>