<?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 Tanmay Chauhan on Medium]]></title>
        <description><![CDATA[Stories by Tanmay Chauhan on Medium]]></description>
        <link>https://medium.com/@tanmaychauhan111?source=rss-d8852cd62096------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NbpSQMWlLcN1pTIMx_m6PQ.jpeg</url>
            <title>Stories by Tanmay Chauhan on Medium</title>
            <link>https://medium.com/@tanmaychauhan111?source=rss-d8852cd62096------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:09:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanmaychauhan111/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[Human Activity Recognition using LSTM-CNN]]></title>
            <link>https://medium.com/@tanmaychauhan111/human-activity-recognition-using-lstm-cnn-8ccb1a42cb81?source=rss-d8852cd62096------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ccb1a42cb81</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <dc:creator><![CDATA[Tanmay Chauhan]]></dc:creator>
            <pubDate>Fri, 08 Jul 2022 18:18:13 GMT</pubDate>
            <atom:updated>2022-07-09T16:57:07.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qcuvkXl6Uv8FEev3" /><figcaption>Photo by <a href="https://unsplash.com/@pietrozj?utm_source=medium&amp;utm_medium=referral">Pietro Jeng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Human Activity Recognition (HAR) is a means by which we can recognize human activities using Artificial Intelligence (AI) from raw data generated by activity recording devices like smartwatches. These human activity recording devices have sensors installed that produce signals when a person performs some kind of action. Some of these sensors that collect information are accelerometers, gyroscopes, and magnetometers. Human Activity Recognition has various applications from providing assistance to the sick and disabled to fields like gaming which heavily rely on analyzing motor skills. There are two categories in which we can widely divide these human activity recognition technologies: Fixed sensors and Mobile Sensors. In this article, we are using raw data produced by Mobile Sensors for recognizing human activity.</p><p>The activities that we will be predicting are:</p><ul><li>Downstairs</li><li>Jogging</li><li>Sitting</li><li>Standing</li><li>Upstairs</li><li>Walking</li></ul><p>In this article, I will be using LSTM (Long Short-Term Memory) and CNN (Convolutional Neural Network) for recognizing the above-listed human activities.</p><h3><strong>Overview</strong></h3><p>You may be thinking as to why are we using an LSTM-CNN model instead of a basic neural network/machine learning method?</p><p>Machine Learning methods rely heavily on heuristic manual feature extraction for human activity recognition tasks, while a basic neural network method will not give the accuracy that a deep neural network (DNN) method will.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*wBiTYAoa4YWHTGuykBHX3g.png" /><figcaption><strong>Working of HAR</strong></figcaption></figure><p>Thus the model that I will be using is a deep neural network that is a combination of LSTM and CNN and has the ability to extract activity features and classify them with only a few model parameters which makes it simple for doing feature extraction.</p><p>The WISDM dataset has a total of 1,098,209 samples. Using raw data from the WISDM dataset we will extract its features by performing different data preprocessing methods and feeding it to the model for training from where we can test our model’s accuracy.</p><blockquote>This model on training gives an F1 score of 0.96 and on the Test set, it gives an F1 score of 0.89.</blockquote><p>This article will help you understand step by step how you can implement the LSTM-CNN method for Human Activity Recognition.</p><h3><strong>Importing Libraries</strong></h3><p>First, we will import all the necessary libraries that we will be needing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0dd72eda477b257193b9185d09ed374/href">https://medium.com/media/e0dd72eda477b257193b9185d09ed374/href</a></iframe><p>We will be using Sklearn, TensorFlow, Keras, SciPy, and NumPy frameworks for building our model and data preprocessing. For data loading, we use the Pandas module. For data Visualization, we are using Matplotlib.</p><h3><strong>Dataset</strong></h3><p>The data set that we are using is raw data recorded by an accelerometer from a mobile device carried around a person’s waist. This data collection was supervised by a single person to ensure the quality of data. You can download this dataset from the link provided <a href="https://www.cis.fordham.edu/wisdm/dataset.php">here</a>. The data set file that we will use is WISDM_ar_v1.1_raw.txt. Using Pandas we will load our dataset into a DataFrame. We will also need to remove ‘;’ from the last column and convert the data to float.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c465a778a0e64f01eaa6ab56dd0b090f/href">https://medium.com/media/c465a778a0e64f01eaa6ab56dd0b090f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*uWZ-F5xYu8W90tr72K1naw.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b8d67acd37f39fcafa88177a9917bd6/href">https://medium.com/media/8b8d67acd37f39fcafa88177a9917bd6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_uTiorXQnpAQSsyhh0o6w.png" /></figure><p>Now I will show you the visualization of the accelerometer data collected from the mobile on all three axes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65577c9a1e9c6fcc848c5080028b2ff4/href">https://medium.com/media/65577c9a1e9c6fcc848c5080028b2ff4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*-fCRIN9AMuqXyVMQeYi8KA.png" /></figure><h3><strong>Data preprocessing</strong></h3><p>Data preprocessing is a very important task in preparing our raw data to easily parse through our model. The data preprocessing methods that we will be using are:</p><ul><li>Label Encoding</li><li>Linear Interpolation</li><li>Data Split</li><li>Normalization</li><li>Segmentation</li><li>One-Hot Encoding</li></ul><h4>Label Encoding</h4><p>Since the model can not take in non-numerical labels as input we will add encoded labels of the ‘activity’ column in another column and name it ‘activityEncode’. The Labels are converted to numerical labels as shown below.</p><ul><li>Downstairs [0]</li><li>Jogging [1]</li><li>Sitting [2]</li><li>Standing [3]</li><li>Upstairs [4]</li><li>Walking [5]</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26eef0034e881f578b628788e9d2d60c/href">https://medium.com/media/26eef0034e881f578b628788e9d2d60c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*Q0s_bB_JS_MfZ7ctuLRQ8Q.png" /></figure><h4>Linear Interpolation</h4><p>Using linear interpolation we can overcome the problem of data that is lost during the collection process which is indicated by NaN. It will fill the missing values. Although in this dataset there is only one NaN value still I have implemented it for your convenience.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6222dc012ac6f8899a9cc5ef3940c7e/href">https://medium.com/media/b6222dc012ac6f8899a9cc5ef3940c7e/href</a></iframe><h4>Data Split</h4><p>The data is split according to the user IDs to avoid the wrong data split. We are taking users with IDs less than or equal to 27 in our training set and the rest in our test set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b14a3827ff3c7462fa16461fd0542ba6/href">https://medium.com/media/b14a3827ff3c7462fa16461fd0542ba6/href</a></iframe><h4>Normalization</h4><p>Now we will normalize our training data features to the range of 0 to 1. The method that we are using for normalization is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*OhoUig1CPun6_RBEJVp6bg.png" /></figure><p>where <em>n</em> denotes the number of channels, and <em>Xi max</em> and <em>Xi min</em> are the maximum and minimum values of the <em>i</em>−th channel, respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd91bc5b8804f2961e0a13d4dd7fc67b/href">https://medium.com/media/bd91bc5b8804f2961e0a13d4dd7fc67b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*1nYp1MIFU1ylT4S8-KTWzA.png" /></figure><h4>Segmentation</h4><p>Reshaping of dataframe is needed for it to be fed into our model. For this, we will create a function called segments that will take in the dataframe, the label names, and the length of each record which is set to 80 steps. This function will also perform separation of features (X-acceleration, Y-acceleration, Z-acceleration) and labels in x_train and y_train respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e56b519aa894a4ee63a2df5e8a3b7ca8/href">https://medium.com/media/e56b519aa894a4ee63a2df5e8a3b7ca8/href</a></iframe><p>x_train and y_train shapes are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3357608cae2c4265f4ab7c91d850a2d5/href">https://medium.com/media/3357608cae2c4265f4ab7c91d850a2d5/href</a></iframe><pre>x_train shape: (20334, 80, 3)<br>Training samples: 20334<br>y_train shape: (20334,)</pre><p>We will store a few values in variables that would be used later. These values are the number of the time periods (time_period), the number of sensors (sensors), and the number of classes (num_classes).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa3ec4bb5e6fe6b00ff0d54338d4afec/href">https://medium.com/media/aa3ec4bb5e6fe6b00ff0d54338d4afec/href</a></iframe><pre>[&#39;Downstairs&#39;, &#39;Jogging&#39;, &#39;Sitting&#39;, &#39;Standing&#39;, &#39;Upstairs&#39;, &#39;Walking&#39;]</pre><p>Since our data is 2-dimensional it will not be processed by our model as multi-dimensional input cannot be processed by Keras so we need to convert it to a list using reshape.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ababee6c04a2dec59460b71f7a84ba64/href">https://medium.com/media/ababee6c04a2dec59460b71f7a84ba64/href</a></iframe><pre>Input Shape:  240<br>Input Data Shape:  (20334, 240)</pre><p>We also need to convert all the feature and label data into float32 so that it is accepted by our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a786d329034b1da9a7bf85d1fadc2b0e/href">https://medium.com/media/a786d329034b1da9a7bf85d1fadc2b0e/href</a></iframe><h4>One-Hot Encoding</h4><p>This is the last step of data preprocessing that we will be performing by one-hot encoding our labels and storing them into y_train_hot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03b05601e6f256a27e5bf9abebd6c74c/href">https://medium.com/media/03b05601e6f256a27e5bf9abebd6c74c/href</a></iframe><pre>y_train shape:  (20334, 6)</pre><h3><strong>Model</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*xFjXP7DfSrMccGG-I_d8bw.png" /><figcaption><strong>Model Architecture</strong></figcaption></figure><p>The model that we are using is a sequential model which consists of 8 layers. The first layer of the model is fed with the preprocessed data. The first two layers consist of LSTMs with 32 neurons each and the activation function used is ReLU. After this comes the convolutional layers which are used to extract spatial features. But first, we need to reshape our LSTM output as it has 3 Dimensions <strong>(samples, time steps, input dimension)</strong> while a CNN layer takes in a 4-dimensional input so we can reshape it to <strong>(samples, 1, time steps, input dimension)</strong>. The first CNN layer has 64 neurons and the other one has 128 neurons. Between the first and second CNN layers, we have a Max-Pooling layer that performs the downsampling operation. Following comes the Global Average Pooling (GAP)layer which converts multi-D feature maps into 1-D feature vectors since there are no parameters to optimize in this layer we end up reducing global model parameters. Now comes the Batch Normalization (BN) layer which helps in the convergence of the model. To improve the training speed and accuracy, it normalizes and reconstructs the input data on each batch of training samples thus ensuring the stability of the output of the previous layer. Finally, we have reached the last layer the Output layer of our model which is just a fully connected Dense layer of 6 neurons with a softmax classifier layer which represents the probability of classes to which the current sample belongs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53e626b0f248100d4bc49de6dd53fd3b/href">https://medium.com/media/53e626b0f248100d4bc49de6dd53fd3b/href</a></iframe><pre>_________________________________________________________________<br> Layer (type)                Output Shape              Param #   <br>=================================================================<br> lstm (LSTM)                 (None, 240, 32)           4352      <br>                                                                 <br> lstm_1 (LSTM)               (None, 240, 32)           8320      <br>                                                                 <br> reshape (Reshape)           (None, 1, 240, 32)        0         <br>                                                                 <br> conv1d (Conv1D)             (None, 1, 120, 64)        4160      <br>                                                                 <br> reshape_1 (Reshape)         (None, 120, 64)           0         <br>                                                                 <br> max_pooling1d (MaxPooling1D  (None, 30, 64)           0         <br> )                                                               <br>                                                                 <br> conv1d_1 (Conv1D)           (None, 29, 192)           24768     <br>                                                                 <br> reshape_2 (Reshape)         (None, 29, 192)           0         <br>                                                                 <br> global_average_pooling1d (G  (None, 192)              0         <br> lobalAveragePooling1D)                                          <br>                                                                 <br> batch_normalization (BatchN  (None, 192)              768       <br> ormalization)                                                   <br>                                                                 <br> dense (Dense)               (None, 6)                 1158      <br>                                                                 <br> activation (Activation)     (None, 6)                 0         <br>                                                                 <br>=================================================================<br>Total params: 43,526<br>Trainable params: 43,142<br>Non-trainable params: 384<br>_________________________________________________________________<br>None</pre><h3><strong>Result</strong></h3><p>After Training our model gives an accuracy of 98.02% and a loss of 0.58%. The F1 score of training comes out to be 0.96.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d89cd88df3bff0f0062d1a998628161a/href">https://medium.com/media/d89cd88df3bff0f0062d1a998628161a/href</a></iframe><pre>Epoch 100/100<br>106/106 [==============================] - 77s 731ms/step - loss: 0.0584 - accuracy: 0.9802</pre><p>Let&#39;s plot the accuracy and loss graph for training along with the classification report.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8c802fbc430ea840f103edd87470b0a/href">https://medium.com/media/b8c802fbc430ea840f103edd87470b0a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*aGiu4DD7s4nvU2yAh7lvEA.png" /></figure><pre>              precision    recall  f1-score   support<br><br>         0.0       0.76      0.98      0.86      1788<br>         1.0       1.00      0.99      0.99      6570<br>         2.0       1.00      0.93      0.96      1049<br>         3.0       0.93      0.99      0.96       801<br>         4.0       0.95      0.91      0.93      2268<br>         5.0       1.00      0.95      0.98      7858<br><br>    accuracy                           0.96     20334<br>   macro avg       0.94      0.96      0.95     20334<br>weighted avg       0.97      0.96      0.96     20334</pre><p>Now we will test it on our test dataset but before passing the test set we need to perform normalization and segmentation of the test set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a172eb66b11279e451e4a8186896cdf1/href">https://medium.com/media/a172eb66b11279e451e4a8186896cdf1/href</a></iframe><p>Now after evaluation of our test data set we get an accuracy of 89.14% and a loss of 46.47%. The F1 score of testing comes out to be 0.89.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af7119d5c50e70349079d46f64ad141b/href">https://medium.com/media/af7119d5c50e70349079d46f64ad141b/href</a></iframe><pre>223/223 [==============================] - 18s 79ms/step - loss: 0.4648 - accuracy: 0.8914<br>Accuracy: 0.8914020657539368<br>Loss: 0.4647580087184906</pre><p>Let&#39;s plot the Confusion matrix to better understand our predictions on the test data set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec9b50c1484b492111207dd7717160ce/href">https://medium.com/media/ec9b50c1484b492111207dd7717160ce/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*4ovODX4lUBJqSQgrhZhjGg.png" /></figure><p>We will also print the Classification report of the model evaluated on the test data set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/916d65713f286ffbc847030f009f4211/href">https://medium.com/media/916d65713f286ffbc847030f009f4211/href</a></iframe><pre>              precision    recall  f1-score   support<br><br>           0       0.61      0.92      0.73       723<br>           1       0.99      0.89      0.93      1989<br>           2       0.89      0.99      0.94       453<br>           3       0.98      0.86      0.92       403<br>           4       0.78      0.78      0.78       799<br>           5       0.96      0.91      0.94      2751<br><br>    accuracy                           0.89      7118<br>   macro avg       0.87      0.89      0.87      7118<br>weighted avg       0.91      0.89      0.90      7118</pre><h3><strong>Conclusion</strong></h3><p>The LSTM-CNN model performs a lot better than any other machine learning model or basic neural network model. If you want to explore Human Activity Recognition using a basic Neural network you can refer to the article <a href="https://towardsdatascience.com/human-activity-recognition-har-tutorial-with-keras-and-core-ml-part-1-8c05e365dfa0">here</a>.</p><p>The Jupyter notebook for this article is available on my <a href="https://github.com/Tanny1810/Human-Activity-Recognition-LSTM-CNN">GitHub</a>.</p><p>You can try implementing it yourself to improve the F1 score by optimizing the model.</p><h3><strong>References</strong></h3><p>The model that I am implementing is from the paper <a href="https://ieeexplore.ieee.org/abstract/document/9043535"><em>LSTM-CNN Architecture for Human Activity Recognition</em></a> written by <a href="https://ieeexplore.ieee.org/author/37086023838"><em>Kun Xia</em></a>, <a href="https://ieeexplore.ieee.org/author/37088355316"><em>Jianguang</em> <em>Huang</em></a>, and <a href="https://ieeexplore.ieee.org/author/37089083604"><em>Hanyu Wang</em></a><em> </em>which is published in<em> IEEE </em>journal<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ccb1a42cb81" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>