<?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 Divyanshu Sundriyal on Medium]]></title>
        <description><![CDATA[Stories by Divyanshu Sundriyal on Medium]]></description>
        <link>https://medium.com/@divyanshuDeveloper?source=rss-6e46e6c81f6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5BjN-3gwzW68VOpbHRoyXw.jpeg</url>
            <title>Stories by Divyanshu Sundriyal on Medium</title>
            <link>https://medium.com/@divyanshuDeveloper?source=rss-6e46e6c81f6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:45:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@divyanshuDeveloper/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[A Simple Animal classifier from scratch using Keras]]></title>
            <link>https://medium.com/@divyanshuDeveloper/a-simple-animal-classifier-from-scratch-using-keras-61ef0edfcb1f?source=rss-6e46e6c81f6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/61ef0edfcb1f</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Divyanshu Sundriyal]]></dc:creator>
            <pubDate>Wed, 11 Apr 2018 01:35:17 GMT</pubDate>
            <atom:updated>2018-04-11T01:35:17.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*toBL6XleRkwABSwTAFaY_g.png" /></figure><p>In this blog I will show you how to make a simple animal classifier using keras.</p><h3>Prerequisite</h3><p>Basics of convolutional neural netwok</p><h3><strong>Step 1 — Install libraries</strong></h3><p>For this project you will need following python libraries installed on your machine-</p><p>Keras, Open cv, Pillow ( For image manipulation), Numpy</p><h3><strong>Step 2 — Prepare Dataset</strong></h3><p>I downloaded nearly 500 photos each for cat, dog, bird and fish categories. You can download photos in batch using some great chrome extensions. In my case I used Download All Images extension in Chrome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C6dKoXXXHdWLdWzJswb8qw.png" /></figure><p>Now I will tell you about the programming part that I used to make the images in the right format as required by model.</p><p>Import Image and numpy library</p><pre>from PIL import Image<br>import numpy as np</pre><p>Code for making images into array -</p><pre>data=[]<br>labels=[]</pre><pre>cats=os.listdir(&quot;cats&quot;)<br>for cat in cats:<br>    imag=cv2.imread(&quot;cats/&quot;+cat)<br>    img_from_ar = Image.fromarray(imag, &#39;RGB&#39;)<br>    resized_image = img_from_ar.resize((50, 50))<br>    data.append(np.array(resized_image))<br>    labels.append(0)</pre><pre>dogs=os.listdir(&quot;dogs&quot;)<br>for dog in dogs:<br>    imag=cv2.imread(&quot;dogs/&quot;+dog)<br>    img_from_ar = Image.fromarray(imag, &#39;RGB&#39;)<br>    resized_image = img_from_ar.resize((50, 50))<br>    data.append(np.array(resized_image))<br>    labels.append(1)<br>    <br>birds=os.listdir(&quot;birds&quot;)<br>for bird in birds:<br>    imag=cv2.imread(&quot;birds/&quot;+bird)<br>    img_from_ar = Image.fromarray(imag, &#39;RGB&#39;)<br>    resized_image = img_from_ar.resize((50, 50))<br>    data.append(np.array(resized_image))<br>    labels.append(2)</pre><pre>fishs=os.listdir(&quot;fishs&quot;)<br>for fish in fishs:<br>    imag=cv2.imread(&quot;fishs/&quot;+fish)<br>    img_from_ar = Image.fromarray(imag, &#39;RGB&#39;)<br>    resized_image = img_from_ar.resize((50, 50))<br>    data.append(np.array(resized_image))<br>    labels.append(3)</pre><p>“data” is the array of all images converted to numpy array and “labels” is the array of corresponding labels.</p><p><strong>How it works</strong> —</p><p>We go into each directory and go through all the files inside it. Then we read the images using cv2.imread. After that using Image object from PIL we convert the image into array. Since while training the convolutional neural network it is required that you have images of same size we resize the images to width and height of 50px. Then we convert it to numpy array just by passing the image array in the function np.array() and we append the numpy array in our data array. Also add corresponding label to the image. Eg for cat label is 0, for dog label is 1 and so on. Labels are required as the training is done in supervised manner.</p><p>Since the “data” and “labels” are normal array , convert them to numpy arrays-</p><pre>animals=np.array(data)<br>labels=np.array(labels)</pre><p>Now save these numpy arrays so that you dont need to do this image manipulation again.</p><pre>np.save(&quot;animals&quot;,animals)<br>np.save(&quot;labels&quot;,labels)</pre><p>Load the arrays ( Optional : Required only if you have closed your jupyter notebook after saving numpy array )</p><pre>animals=np.load(&quot;animals.npy&quot;)<br>labels=np.load(&quot;labels.npy&quot;)</pre><p>Now shuffle the “animals” and “labels” set so that you get good mixture when you separate the dataset into train and test</p><pre>s=np.arange(animals.shape[0])<br>np.random.shuffle(s)<br>animals=animals[s]<br>labels=labels[s]</pre><p>Make a variable num_classes which is the total number of animal categories and a variable data_length which is size of dataset</p><pre>num_classes=len(np.unique(labels))<br>data_length=len(animals)</pre><p><strong>Divide data into test and train</strong></p><p>Take 90% of data in train set and 10% in test set</p><pre>(x_train,x_test)=animals[(int)(0.1*data_length):],animals[:(int)(0.1*data_length)]</pre><pre>x_train = x_train.astype(&#39;float32&#39;)/255<br>x_test = x_test.astype(&#39;float32&#39;)/255</pre><pre>train_length=len(x_train)<br>test_length=len(x_test)</pre><p><strong>Divide labels into test and train</strong></p><pre>(y_train,y_test)=labels[(int)(0.1*data_length):],labels[:(int)(0.1*data_length)]</pre><p><strong>Make labels into One Hot Encoding</strong></p><pre>import keras<br>from keras.utils import np_utils</pre><pre>#One hot encoding<br>y_train=keras.utils.to_categorical(y_train,num_classes)<br>y_test=keras.utils.to_categorical(y_test,num_classes)</pre><p>Conratulations !! Your data preparation part is over</p><h3>Step 3 — Making Keras model</h3><p>It is a very easy process to make your deep learning model. Thanks to the great Keras library. All you have to do is think about hyper parameters like Filter size, number of filters, which type of padding to use, which activatioon functions to use etc.</p><p>Here is my Keras model-</p><pre># import sequential model and all the required layers<br>from keras.models import Sequential<br>from keras.layers import Conv2D,MaxPooling2D,Dense,Flatten,Dropout</pre><pre>#make model<br>model=Sequential()</pre><pre>model.add(Conv2D(filters=16,kernel_size=2,padding=&quot;same&quot;,activation=&quot;relu&quot;,input_shape=(50,50,3)))</pre><pre>model.add(MaxPooling2D(pool_size=2))</pre><pre>model.add(Conv2D(filters=32,kernel_size=2,padding=&quot;same&quot;,activation=&quot;relu&quot;))</pre><pre>model.add(MaxPooling2D(pool_size=2))</pre><pre>model.add(Conv2D(filters=64,kernel_size=2,padding=&quot;same&quot;,activation=&quot;relu&quot;))</pre><pre>model.add(MaxPooling2D(pool_size=2))<br>model.add(Dropout(0.2))<br>model.add(Flatten())<br>model.add(Dense(500,activation=&quot;relu&quot;))<br>model.add(Dropout(0.2))<br>model.add(Dense(4,activation=&quot;softmax&quot;))</pre><pre>model.summary()</pre><p>I added 3 pairs of Conv2D layer and Maxpool2D layer with increasing filter sizes ( 16,32 ,64) . This helps to make image grow more in depthwise and become more flatten. Maxpool layers are great as they optimize the training time. I have also add Dropout layers to reduce overfitting.</p><p>In final Dense layer there are 4 nodes because we have 4 categories of animals (cat,dog,bird,fish). Softmax activation is used to give scores to these categories which lie between 0 and 1.</p><p>You will get following model summary after running above code</p><pre>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>conv2d_1 (Conv2D)            (None, 50, 50, 16)        208       <br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 25, 25, 16)        0         <br>_________________________________________________________________<br>conv2d_2 (Conv2D)            (None, 25, 25, 32)        2080      <br>_________________________________________________________________<br>max_pooling2d_2 (MaxPooling2 (None, 12, 12, 32)        0         <br>_________________________________________________________________<br>conv2d_3 (Conv2D)            (None, 12, 12, 64)        8256      <br>_________________________________________________________________<br>max_pooling2d_3 (MaxPooling2 (None, 6, 6, 64)          0         <br>_________________________________________________________________<br>dropout_1 (Dropout)          (None, 6, 6, 64)          0         <br>_________________________________________________________________<br>flatten_1 (Flatten)          (None, 2304)              0         <br>_________________________________________________________________<br>dense_1 (Dense)              (None, 500)               1152500   <br>_________________________________________________________________<br>dropout_2 (Dropout)          (None, 500)               0         <br>_________________________________________________________________<br>dense_2 (Dense)              (None, 4)                 2004      <br>=================================================================<br>Total params: 1,165,048<br>Trainable params: 1,165,048<br>Non-trainable params: 0<br>_________________________________________________________________</pre><p><strong>Compile the model</strong></p><p>We use loss function as categorical_crossentropy and Adam optimizer</p><pre># compile the model<br>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;, <br>                  metrics=[&#39;accuracy&#39;])</pre><h3>Step 4 — Train the model</h3><p>Congrats on reaching upto this step. Your all work is over. Now just train the model and wait patiently.</p><pre>model.fit(x_train,y_train,batch_size=50<br>          ,epochs=100,verbose=1)</pre><p>“epochs” is the number of steps you want to train the model. Batch size is the size of dataset that is thrown to the model at a time. It is really important to set this because if you have a lower memory problem in your computer you cant train the model by throwing all the data at once.</p><p>After running above snippet you can it running —</p><pre>Epoch 1/100<br>1932/1932 [==============================] - 5s 3ms/step - loss: 1.3583 - acc: 0.3649<br>Epoch 2/100<br>1932/1932 [==============================] - 4s 2ms/step - loss: 1.1083 - acc: 0.5078<br>Epoch 3/100<br>1932/1932 [==============================] - 4s 2ms/step - loss: 1.0123 - acc: 0.5424<br>Epoch 4/100<br>1932/1932 [==============================] - 4s 2ms/step - loss: 0.9267 - acc: 0.5983<br>Epoch 5/100<br>1932/1932 [==============================] - 4s 2ms/step - loss: 0.8474 - acc: 0.6284<br>Epoch 6/100<br>1932/1932 [==============================] - 4s 2ms/step - loss: 0.8145 - acc: 0.6620<br>Epoch 7/100<br>1932/1932 [==============================] - 4s 2ms/step - loss: 0.7584 - acc: 0.6848<br>.......<br>.......<br>.......</pre><h3>Step 5 — Test the model</h3><p>Use model.evaluate to see how model work on test set</p><pre>score = model.evaluate(x_test, y_test, verbose=1)<br>print(&#39;\n&#39;, &#39;Test accuracy:&#39;, score[1])</pre><p>I got an accuracy of 72% on the test set</p><pre>238/238 [==============================] - 0s 929us/step<br><br> Test accuracy: 0.7226890766320109</pre><h3>Step 6 — Predicting on single images</h3><p>If you want to predict on a single image use this code-</p><pre>def convert_to_array(img):<br>    im = cv2.imread(img)<br>    img = Image.fromarray(im, &#39;RGB&#39;)<br>    image = img.resize((50, 50))<br>    return np.array(image)</pre><pre>def get_animal_name(label):<br>    if label==0:<br>        return &quot;cat&quot;<br>    if label==1:<br>        return &quot;dog&quot;<br>    if label==2:<br>        return &quot;bird&quot;<br>    if label==3:<br>        return &quot;fish&quot;</pre><pre>def predict_animal(file):<br>    print(&quot;Predicting .................................&quot;)<br>    ar=convert_to_array(file)<br>    ar=ar/255<br>    label=1</pre><pre>    a=[]<br>    a.append(ar)<br>    a=np.array(a)<br>    score=model.predict(a,verbose=1)<br>    print(score)</pre><pre>    label_index=np.argmax(score)<br>    print(label_index)<br>    acc=np.max(score)</pre><pre>    animal=get_animal_name(label_index)<br>    print(animal)<br>    print(&quot;The predicted Animal is a &quot;+animal+&quot; with accuracy =    &quot;+str(acc))</pre><p>Now run the predict_animal function on the image. Make sure your image is in same directory as your code.</p><pre>predict_animal(&quot;cat.jpg&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*SXVEnM645RfH0nQGjEui3Q.jpeg" /><figcaption>cat.jpg</figcaption></figure><pre>Predicting .................................<br>1/1 [==============================] - 0s 46ms/step<br>[[9.8973280e-01 1.0265494e-02 6.8336470e-07 9.8519263e-07]]<br>0<br>cat<br>The predicted Animal is a cat with accuracy = 0.9897328</pre><p><strong>Congratulations you have successfully build your image classifier !!</strong></p><h3>Step 7 — Save the model</h3><p>It is important to save the trained model as if you dont you have to train it again. So save it and then use it when required. It will basically save the weights in a file. Use below code to save-</p><pre>from keras.models import model_from_json</pre><pre># serialize model to JSON<br>model_json = model.to_json()<br>with open(&quot;model.json&quot;, &quot;w&quot;) as json_file:<br>    json_file.write(model_json)<br># serialize weights to HDF5<br>model.save_weights(&quot;model.h5&quot;)</pre><pre>print(&quot;Saved model to disk&quot;)</pre><h3>Step 8 —(Optional ) Export to protobuf file if you want to use your saved model in some other device like Android</h3><p>Use the below code to do it</p><pre>def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):<br>    &quot;&quot;&quot;<br>    Freezes the state of a session into a pruned computation graph.</pre><pre>Creates a new computation graph where variable nodes are replaced by<br>    constants taking their current value in the session. The new graph will be<br>    pruned so subgraphs that are not necessary to compute the requested<br>    outputs are removed.<br>    <a href="http://twitter.com/param">@param</a> session The TensorFlow session to be frozen.<br>    <a href="http://twitter.com/param">@param</a> keep_var_names A list of variable names that should not be frozen,<br>                          or None to freeze all the variables in the graph.<br>    <a href="http://twitter.com/param">@param</a> output_names Names of the relevant graph outputs.<br>    <a href="http://twitter.com/param">@param</a> clear_devices Remove the device directives from the graph for better portability.<br>    <a href="http://twitter.com/return">@return</a> The frozen graph definition.<br>    &quot;&quot;&quot;<br>    from tensorflow.python.framework.graph_util import convert_variables_to_constants<br>    graph = session.graph<br>    with graph.as_default():<br>        freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))<br>        output_names = output_names or []<br>        output_names += [v.op.name for v in tf.global_variables()]<br>        input_graph_def = graph.as_graph_def()<br>        if clear_devices:<br>            for node in input_graph_def.node:<br>                node.device = &quot;&quot;<br>        frozen_graph = convert_variables_to_constants(session,     input_graph_def,output_names, freeze_var_names)<br>        return frozen_graph</pre><p>Run the freeze session function-</p><pre>from keras import backend as K<br>import tensorflow as tf<br># Create, compile and train model...</pre><pre>frozen_graph = freeze_session(K.get_session(),<br>                              output_names=[out.op.name for out in model.outputs])</pre><pre>tf.train.write_graph(frozen_graph, &quot;export&quot;, &quot;my_model.pb&quot;, as_text=False)</pre><p>Hope you like the tutorial and if you do don’t forget to hit the clap button</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61ef0edfcb1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>