<?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 Soorya Prakash on Medium]]></title>
        <description><![CDATA[Stories by Soorya Prakash on Medium]]></description>
        <link>https://medium.com/@sooryaprakash84?source=rss-bf1cf93a6241------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T7EJyVTqPGDWji4jH9WuSg.jpeg</url>
            <title>Stories by Soorya Prakash on Medium</title>
            <link>https://medium.com/@sooryaprakash84?source=rss-bf1cf93a6241------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:34:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sooryaprakash84/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[Hands-On Practice with Time Distributed Layers using Tensorflow]]></title>
            <link>https://levelup.gitconnected.com/hands-on-practice-with-time-distributed-layers-using-tensorflow-c776a5d78e7e?source=rss-bf1cf93a6241------2</link>
            <guid isPermaLink="false">https://medium.com/p/c776a5d78e7e</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Soorya Prakash]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 13:52:20 GMT</pubDate>
            <atom:updated>2022-02-07T00:00:45.774Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will guide you to solve a problem that involves a sequence of images as input with Tensorflow that I have faced in the final round of Data Unchained-an Machine Learning competition by Elysium IIIT Delhi.</p><h3>Problem Statement</h3><blockquote>You are the tech guy in the Los Angeles Police Department. The recent surge in illegal racing is causing a lot of trouble to the citizens. So now the police have been on alert. Yesterday they brought in a person for the same reason. We got access to his dashboard cam but we can’t determine if he is over speeding or not because the hard drive was corrupted. Still, you managed to get some pieces of the video clip, but from that, his speed is not conclusive by just seeing.<br>Being a highly motivated person, you decide to fetch the clips from another car’s dash-cam with velocity noted down. Now your task is to train a model which determines the speed of the car using a series of dash-cam images (i.e. 8 frames). The camcorder recodes the clip at 20 fps.</blockquote><p><a href="https://www.kaggle.com/c/final-showdown/overview">Kaggle Link for the Competition</a></p><p><strong>An example of training data:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tbRiyODldZkIA-IhWs3PQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WViWMr_jjiMd6wnLeWNTqw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SztWt9zKyfLdbXo3D9om8g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Q8AhrWx0LJEOOXsO7ExdQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rtX9zniz36M7clqf1lw0A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjeSmiXhNmUcVh4IR5_tRw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8D7n58JHPhqkYVoggvk4IA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xPjljprzgFmJAPpT5AKRGg.jpeg" /><figcaption>Image Sequence in Order</figcaption></figure><blockquote><strong>Output</strong>: Car’s Velocity in X and Y direction: [-1.2287469463, -0.0101401592]</blockquote><blockquote>Velocity values are scaled.</blockquote><h3>Understanding the Problem Statement</h3><p>The problem here is to train a model which can determine the speed of the car using just a series of images taken from dash camera. We have to <strong>input</strong> <strong>8 images</strong> to the model and it outputs X and Y components of velocity of the car. In simple terms, we have to predict the speed of the car with 8 images taken from its dashboard camera.</p><h3>Understanding Time Distributed Layers</h3><p>Normally, in Computer Vision we will have a problem building a model that can classify images (for ex. dog or cat ). You will input a single image to the model and it gives an output of 0 or 1 (0 being Cat and 1 being Dog).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUBdDSVPpbC5VHvzTaZK0w.png" /><figcaption>Dog Cat Classifier</figcaption></figure><h3>But in our case, we have 8 images per sample.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l66eo4GkNkRfe8-Zywp4Hw.jpeg" /></figure><p>One way to approach this problem is to merge all the images into a single image and input the merged image to the model but here we will lose key information which can help the model to predict. In our problem statement, <strong>Small differences in the location of objects in the images can help the model determine the speed of the car</strong> but by merging the image we will be losing this information.</p><p>So we have to find a way to not lose information and at the same time pass 8 images to the model and get an output. Here comes our Savior the <strong>Time Distributed Layer </strong>from Tensorflow<strong>.</strong></p><p>This Specialized Layer applies the same layer to several inputs and get output for each input such that we can combine them and pass it to another layer to make predictions.</p><p>In this way, we use only one layer that performs its operations on 8 separate images and gives output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TlRx1_ci-ertAFULdjq2zQ.png" /><figcaption>Key Note:<strong> All the Convolution Layers share the same weights. So They are technically the same layer. For easy understanding, you can think of them as Clones of the layer.</strong></figcaption></figure><p>The Time Distributed Layer applies the same instance of the layer to each of the 8 images. So we don’t have 8 different sets of weights for this layer. The same set of weights are applied to all images.</p><p>So By using this layer, we will not be increasing the complexity of the model(number of parameters) yet give the model the ability to learn from 8 different images separately with just one layer.</p><p>Intuitively, These images are taken at different timestamps that doesn’t have any major difference so one layer is enough to key features. It’s like taking photos in burst mode on Mobile. So the same layer can be applied to 8 images and yet identity key features from each of them.</p><p><em>To Learn More about Time Distributed Layers:</em><strong> </strong><a href="https://medium.com/smileinnovation/how-to-work-with-time-distributed-data-in-a-neural-network-b8b39aa4ce00"><strong>How to work with Time Distributed data in a neural network</strong></a></p><p>I thank the writer of the article <a href="https://medium.com/u/63647e779dd9">Patrice Ferlet</a> for this article. it is Gold and has helped me a lot in solving this problem.</p><h3>Knowing the basics required to solve this problem, let us dive deep into the code</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F16733376&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Ffox-cute-jump-dive-gif-16733376&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fimages%2F718d7ebc1b866c912223c774385302ff%2Ftenor.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e04fbe8a830cdd36c5ca2e16cf132cd/href">https://medium.com/media/9e04fbe8a830cdd36c5ca2e16cf132cd/href</a></iframe><p><strong>Structure of the Data provided</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gk0BkPdH7Mb1WdxAxzCtug.png" /></figure><p><strong>Importing necessary libraries:</strong></p><pre><strong>import</strong> <strong>cv2<br>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np<br>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br>%matplotlib inline<br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>keras<br>import</strong> <strong>json</strong><br><strong>import</strong> <strong>tensorflow</strong> <strong>as tf</strong> <br><strong>from</strong> <strong>keras.layers</strong> <strong>import</strong> Input<br><strong>from</strong> <strong>keras</strong> <strong>import</strong> Sequential<br><strong>from</strong> <strong>keras.layers</strong> <strong>import</strong> Dense, LSTM,Flatten, TimeDistributed, Conv2D, Dropout<br><strong>from</strong> <strong>keras.applications.inception_v3</strong> <strong>import</strong> InceptionV3<br><strong>from</strong> <strong>keras.applications.vgg16</strong> <strong>import</strong> VGG16</pre><p><strong>Mounting Google drive and Extracting the Data:</strong></p><pre><strong>from</strong> <strong>google.colab</strong> <strong>import</strong> drive<br>drive.mount(&#39;/content/gdrive/&#39;)</pre><pre><strong>import</strong> <strong>zipfile</strong></pre><pre>final_showdown_zip = &#39;/content/gdrive/My Drive/final-showdown.zip&#39;</pre><pre>zip_ref = zipfile.ZipFile(final_showdown_zip, &#39;r&#39;)<br>zip_ref.extractall(&#39;/content/gdrive/My Drive/final_showdown&#39;)<br>zip_ref.close()</pre><p>The dimensions of the images in our problem are (720, 1280, 3). We have to reduce the dimensions of the image for faster processing and training of our data. To preserve the ratio at the same time while reducing dimension we divide the dimension by 4. (720/4,1280/4) =(180,320,3)</p><p><strong>Function to Resize the image from (720,1280,3) to (180,320,3) for faster computation still preserving the Image Aspect ratio:</strong></p><pre><strong>def</strong> get_img(img_path, printer=<strong>True</strong>):<br>  original_img = cv2.imread(img_path, cv2.IMREAD_COLOR)<br>  <strong>if</strong> printer: print (&quot;original dim:&quot;,original_img.shape)</pre><pre>resized_img = cv2.resize(original_img, (320,180), interpolation=cv2.INTER_CUBIC)<br>  <strong>if</strong> printer: print (&quot;resized dim:&quot;, resized_img.shape)</pre><pre><strong>return</strong> resized_img</pre><p><strong>Testing our Function:</strong></p><pre>img_path = &quot;/content/gdrive/My Drive/final_showdown/Train/Train/422/imgs/001.jpg&quot;<br>resized_img = get_img(img_path)<br>plt.imshow(resized_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*ge8v-gdHOjNihFU950ytUA.png" /></figure><p><strong>Next step is To Concatenate 8 Images in a sample for our Time Distributed Layer.</strong></p><blockquote>Input shape of our Time Distributed Layer = (No. of Images per sample,height of the image, width of the image, No. of channels)</blockquote><pre>prefix = &quot;/content/gdrive/My Drive/final_showdown/Train/Train/400/imgs/00&quot;<br> <em>## Testing the Concatenation method</em></pre><pre>X_sample = []<br><strong>for</strong> idx <strong>in</strong> range (1, 9):<br>  img_path = prefix + str(idx) + &quot;.jpg&quot;<br>  resized_img = get_img(img_path, printer=<strong>False</strong>)<br>  X_sample.append(resized_img)</pre><pre>print (np.array(X_sample).shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*rewBhPfTSp7fxV1D3WbZyw.png" /></figure><p><strong>To Convert the Training data into Required format to feed the data into a model.</strong></p><pre>main_prefix=&quot;/content/gdrive/My Drive/final_showdown/Train/Train/&quot;<br>X_train_check=[]<br><strong>for</strong> i <strong>in</strong> range(1,457):<br>  path=main_prefix+str(i)+&quot;/imgs/00&quot;<br>  X_sample = []<br>  <strong>for</strong> idx <strong>in</strong> range(1, 9):<br>    img_path = path + str(idx) + &quot;.jpg&quot;<br>    resized_img = get_img(img_path, printer=<strong>False</strong>)<br>    X_sample.append(resized_img)<br>  X_train_check.append(np.array(X_sample))<br>np.array(X_train_check).shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*TcmkhaAXFnBk6KhhH7t0jA.png" /></figure><p><em>Our Numpy array </em><strong><em>X_train_check</em></strong><em> has the above shape which corresponds with our idea of (456 Training Examples, 8 images in each example, the dimensions of images)</em></p><p>Extracting Velocity in X and Y Direction from the annotation file and make a NumPy array with 2 columns (Velocity in X and Y).</p><pre>main_prefix=&quot;/content/gdrive/My Drive/final_showdown/Train/Train/&quot;<br>y_train_check=[]<br><strong>for</strong> i <strong>in</strong> range (1,457):<br>  path=main_prefix+str(i)+&quot;/annotation.json&quot;<br>  f = open(path,)  <br>  data = json.load(f) <br>  f.close()<br>  y_train_check.append(np.array((data[0][&quot;velocity&quot;])))<br>np.array(y_train_check).shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*gCIxO6clHo5MoRtzfENlfA.png" /></figure><pre>print(np.array(y_train_check)[:5])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*VWFRngy9j3i8KX_8IbTG3w.png" /></figure><h3>Model Structure</h3><p>We will be using Time Distributed Convolutional layers followed by LSTM to capture the sequential data then proceeding with Dense layers to get our final output. As we have a limited amount of data for training, we use the <strong>pre-trained model</strong> InceptionResNetV2 as a Time-Distributed layer to capture details from the image.</p><p>LSTMs are a special kind of RNN, capable of learning long-term dependencies. We use LSTM to capture the chronological information attained from the Time Distributed layers above and get meaningful information out of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*6SmOOW_YJwOrvIdqnIrBzQ.gif" /><figcaption>Visual Explanation of the Model.<a href="https://medium.com/smileinnovation/how-to-work-with-time-distributed-data-in-a-neural-network-b8b39aa4ce00"> Image Source</a></figcaption></figure><h3>What are Pretrained Models?</h3><p>A pre-trained model has been previously trained on a dataset and contains the weights and biases that represent the features of whichever dataset it was trained on. Learned features are often transferable to different data.</p><p>Inception-ResNet-v2 is a convolutional neural network that is trained on more than a million images from the ImageNet database. The network is 164 layers deep and can classify images into 1000 object categories, such as a keyboard, mouse, pencil, and many animals. As a result, the network has learned rich feature representations for a wide range of images.</p><p>Using the weights of this pre-trained model on top our LSTM will increase our accuracy. We use Inception-ResNetv2 model but we only train the last 4 layers of it. Training the huge model fully again will take a lot of computation power and defies the use of pretraining.</p><pre><em>#Best Model to this problem was InceptionResNet V2</em></pre><pre>inceptionresnet=tf.keras.applications.InceptionResNetV2(                                       <br>    include_top=<strong>False</strong>,<br>    weights=&quot;imagenet&quot;,<br>    input_tensor=<strong>None</strong>,<br>    input_shape=(180,320,3)<br>)<br>  <br><strong>for</strong> layer <strong>in</strong> inceptionresnet.layers[:-4]:                                                       <br>    layer.trainable = <strong>False</strong></pre><pre><em>#We train only the last 4 layers this Model while Freezing the other #Layers.</em></pre><p><strong>Building the Model:</strong></p><pre>model = Sequential()</pre><pre><em>#add Inception model for 8 input images (keeping the right shape)</em></pre><pre>model.add(TimeDistributed(inceptionresnet, input_shape=(8, 180, 320, 3)))     <br>                     <br><em>#Using TimeDistributed Layer to Feed the Image Sequence</em></pre><pre><em># now, flatten  each output to send 8 outputs with one dimension to #LSTM</em></pre><pre>model.add( TimeDistributed( Flatten() ))</pre><pre><em>##Added LSTM to Capture the Sequencial Information</em></pre><pre>model.add(LSTM (256, activation=&#39;relu&#39;, return_sequences=<strong>False</strong>))</pre><pre><em># Dense Layer</em></pre><pre>model.add(Dense (64, activation=&#39;relu&#39;))</pre><pre><em>#Final Dense Layer</em></pre><pre>model.add(Dropout(.5))</pre><pre>model.add(Dense(2))  <br>                     <br><em># Final Layer is of 2 Neurons [Velocity in X Direction and Y Direction]</em></pre><pre>model.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;, metrics=tensorflow.keras.metrics.RootMeanSquaredError())</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*tX8ww9u4FlkR4OcmsehWsg.png" /><figcaption>Summary of the model describes the layers used and the no. of parameters in it.</figcaption></figure><p><strong>Similar Model Structure:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FUQ39KESKNNrsKh3h48ww.png" /><figcaption>Model Structure. <a href="https://medium.com/smileinnovation/how-to-work-with-time-distributed-data-in-a-neural-network-b8b39aa4ce00">Image Source</a></figcaption></figure><pre>#Fitting the model to our training data r=model.fit(np.array(X_train_check),np.array(y_train_check),validation_split=0.2,batch_size=38,epochs=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORF8ZLU8OmHDoRxyg47Fzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*BCvvlje5NU97GiHlSRuY0A.png" /><figcaption>Metrics</figcaption></figure><p>Training the model for <strong>10 epochs</strong> was found to be efficient to avoid the <strong>overfitting</strong> problem.</p><p>Loss reduces with each epoch. Training Error and Validation Losses converge down significantly per each epoch signifying that the model has performed well.</p><p>Predicting with this model on the test data gave me a Root mean squared error of 1.76 and helped me securing <strong>Second Position</strong> in the Competition.</p><p><a href="https://github.com/Sooryak12/Data-Unchained-By-IIIT-Delhi">GitHub Link to access the notebook</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c776a5d78e7e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/hands-on-practice-with-time-distributed-layers-using-tensorflow-c776a5d78e7e">Hands-On Practice with Time Distributed Layers using Tensorflow</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>