<?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 R.A.M on Medium]]></title>
        <description><![CDATA[Stories by R.A.M on Medium]]></description>
        <link>https://medium.com/@Sriram-P?source=rss-5883b9816e2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3i2rcK7ZxMxGB0VVynr0gQ.jpeg</url>
            <title>Stories by R.A.M on Medium</title>
            <link>https://medium.com/@Sriram-P?source=rss-5883b9816e2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:51:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Sriram-P/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[Stereo depth estimation on DrivingStereo Dataset : Part-2]]></title>
            <link>https://medium.com/@Sriram-P/stereo-depth-estimation-on-drivingstereo-dataset-part-2-18fd423446e3?source=rss-5883b9816e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/18fd423446e3</guid>
            <dc:creator><![CDATA[R.A.M]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 16:39:42 GMT</pubDate>
            <atom:updated>2023-03-06T16:39:42.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stereo depth estimation on DrivingStereo Dataset : Part-2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*uWx0mePWsZLPD-Ku" /><figcaption>Photo by <a href="https://unsplash.com/@samuele_piccarini">samuele_piccarini</a> on <a href="https://unsplash.com/photos/MyjVReZ5GLQ">unsplash</a></figcaption></figure><p>This two part series explores various existing deep learning architectures and custom models in calculating depth from stereo images. The two parts in this series are separated as follows:</p><ul><li><a href="https://medium.com/@Sriram-P/stereo-depth-estimation-on-drivingstereo-dataset-part-1-884388156c93">Part-1 : Introduction, Literature survey and Metrics</a></li><li>Part-2 : Modeling, Training and results</li></ul><h3>Table of Contents</h3><ul><li>Training and experiments</li><li>Final Results</li><li>Future Scope</li><li>References</li></ul><h3><strong>Training and experiments</strong></h3><h4>Data processing</h4><p>The stereo depth prediction — model training involves using left and right images as inputs and depth maps as output. In order to use input images as model inputs, they need stereo calibration and for ground truth output depth maps, they need to be dense depth maps.</p><ol><li>Stereo image calibration and data preparation : Calibration of stereo image pairs involves removal of distortions and match the stereo image pairs. Detailed info is present in the blog <a href="https://dibyendu-biswas.medium.com/stereo-camera-calibration-and-depth-estimation-from-stereo-images-29d87bc702f3">here</a>. However, the authors of the DrivingStereo dataset had calibrated images and provided intrinsic parameters for each captured scenario. This involves minimal preprocessing on the input pipeline. The input images have a resolution of 881x400 which are downscaled to 440x200 or 220x100 resolution for faster training and to keep training within google colab’s GPU vram limits. The image data available is huge but it is in parts which is convenient to train in steps. In this case study, only 2 parts of training images are used for training and other parts are used for testing and validation.</li><li>Dense depth maps : The depth maps present in the dataset are cumulatively processed lidar point clouds with each point representing the depth at a given area. The point cloud data is sparse in nature and is not suitable to train as lot of the spatial information is empty. Hence dense depth maps are required to train the DL models for depth prediction.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/726714afafce5d5d1017c4562e8fc637/href">https://medium.com/media/726714afafce5d5d1017c4562e8fc637/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*OjUU3fEnbsDGwPjC" /><figcaption>Sparse depth map visualization</figcaption></figure><p>The process of generating dense depth maps from sparse depth data is called depth inpainting or depth completion. This process involves various techniques to fill the empty spaces with data from nearest depth measurements. In this case study, depth completion from the repo <a href="https://github.com/kujason/ip_basic">Image Processing for Basic Depth Completion (IP-Basic)</a> is modified to fit the requirements of driving stereo dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06225882529614e3dff3aec7569a584e/href">https://medium.com/media/06225882529614e3dff3aec7569a584e/href</a></iframe><p>The complete_depth function requires the sparse depth map image, resolution of the output image and fill_type (fast or multiscale) using which the completed depth image is generated. In order to visualise and validate the dense depth maps for artefacts, visualize_depth_map function is prepared which can display stereo image pair and corresponding dense depth map.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/730a94c50bc4d58e4101a820b80fb606/href">https://medium.com/media/730a94c50bc4d58e4101a820b80fb606/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*lTgy_yZXLlu3RRXfEmdaBg.png" /><figcaption>Visualization of left — right — depth images</figcaption></figure><p>In order to generate the dense depth map for training the model, there are two ways to do it. First is to generate and store all the dense depth maps to the disk, which can be directly used during the training process. This method takes up significant disk space but will not impact training time. Second way is to generate during the training process included in the training pipeline. This method takes no more disk space but slows down the training process. Second method is used here for generation of dense depth maps as the first step involves generation of dense depth maps each time the colab instance is started.</p><h4>Datagenerator pipeline</h4><p>The data generator pipeline is a modified data generator from keras <a href="https://keras.io/examples/vision/depth_estimation/">depth_estimation</a> example. Main modification involves generating dense depth maps during the process of training. Other minor changes include using tf.io and tf.image to load and resize the stereo image pairs.</p><p>The data used for training is a small subset of the DrivingStereo dataset. This creates a requirement of using image augmentation techniques to inflate the data seen by the model. In the case of Stereo image depth estimation, Stereo image pairs are expected to be calibrated and match spatially in the image. This implies that any augmentation technique involving modification of geometric shapes of objects in the image are to be avoided. Hence in this project, only random brightness change to the stereo image pair is used here.</p><h4>Modelling</h4><p><strong><em>Baseline model : FlowNet</em></strong></p><p>In the first stage of modelling, a baseline model is trained based on the <a href="https://arxiv.org/pdf/1504.06852.pdf">FlowNet</a> implementation. This model stacks both input images together and feeds them through a rather generic network, and lets the network learn decoding depth through backpropagation. This architecture loosely follows encoder (contraction part) and decoder (Refinement part) based architecture with skip connection to refinement layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*1N0Oj3kx0-rv3RBe" /><figcaption>Flownet architecture</figcaption></figure><p>One-to-One implementation of FlowNet resulted in huge parameters. A modified and scaled down version of flownet is used to train and prepare baseline depth maps. The loss function used here is Smooth L1 Loss. Optimizer used in Nadam with a step of 0.0008 and batch size of 8.</p><pre>Smooth_L1 = tf.keras.losses.Huber()<br>optimizer = tf.keras.optimizers.Nadam(learning_rate=0.0008)<br>model_1.compile(optimizer=optimizer,loss=Smooth_L1)</pre><p>Call backs are used for saving model weights frequently and tensorboard is used to monitor the performance. The callbacks become more consolidated but form same pattern throughout the modeling.</p><p><a href="https://gist.github.com/sriram-pasupuleti/54b13559e079d524e9fb71366c11d636">https://gist.github.com/sriram-pasupuleti/54b13559e079d524e9fb71366c11d636</a></p><p>The result of the training for 72 epochs is as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*Vmi300VrsTp5bkBwyKVbKg.png" /><figcaption>Left: Left image, Middle: Ground Truth, Right: Prediction</figcaption></figure><p><em>Observations</em>:</p><ul><li>In the predicted depth maps, there are a lot of structural artefacts.</li><li>Overall structure of the depth is also not perceived correctly by the model</li><li>Lot of fringing within the depth prediction of same depth objects</li><li>Smaller objects are lost in details in prediction depth maps</li><li>lots of chequered artefacts in objects at the corner of the images</li></ul><p><em>Modifying loss function</em> : Instead of only Smooth L1 loss, SSIM and Image gradients are added. The addition slightly improved the overall structure of predicted depth maps</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96a95c140bca860aa6e2866ed078592e/href">https://medium.com/media/96a95c140bca860aa6e2866ed078592e/href</a></iframe><p>The result of the training for 120 epochs is as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*WFPb4wruc_YYaCcbKLpNjw.png" /></figure><p><em>Observations</em> :</p><ul><li>Still, there are a lot of chequered artefacts in the prediction, this could be because of usage of continuous conv2D transpose layers.</li><li>Lot of objects got ignored in the prediction</li><li>Overall structure of the objects are lost, border detections are weak</li></ul><h4>Custom models</h4><p><strong><em>Unet — Locally connected 2D</em></strong></p><p>This model implements standard downsample and skip connections along with locally connected 2D layer in the last level of encoder. Locally connected 2D layer creates filters at each pixel which means it creates a lot of parameters which are not possible to fit in colab’s Vram. Explanations can be found <a href="https://prateekvjoshi.com/2016/04/12/understanding-locally-connected-layers-in-convolutional-neural-networks/">here</a> and <a href="https://medium.com/machine-learning-for-li/different-convolutional-layers-43dc146f4d0e">here</a>.</p><pre>shared_LC_layer = tf.keras.layers.LocallyConnected2D(filters=1, kernel_size=2, strides=2, activation=tf.keras.layers.LeakyReLU(0.2), name=&#39;Locally_connected&#39;)</pre><p>Another part of the encoder is using shared weights for the stereo image pair instead of concatenating and sending them together. At the end of the decoder stage, there are two tensors for the left and right image, These two have to be fused together to generate a depth map. The fusion is done by local multiplication of the two tensors and a Conv2D layer followed by a softmax. This creates a similarity tensor between left and right images over which decoding starts using Conv2DTranspose.</p><p><em>Results and Observations:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*NccF-XVOKPLNeJ867XlOHA.png" /></figure><ul><li>The physical structures of the depth maps are not corresponding to objects in the image.</li><li>There are a lot of weird artefacts of even basic objects like nearby cars or a normal pole.</li><li>Lots of chequered artefacts for objects slightly far.</li><li>RMSE on the test data is 9.927887</li></ul><p>The verification here is done only with images at different timestamps. Better way to observe the performance of the model is by generating depth maps for a part of the stereo video. Hence function gen_video is used which generates side by side frames of left frame and predicted depth map. The video stream can be found in the notebooks in the github.</p><pre>gen_video(model=model_Unet, resolution=(200,440), <br>          video_name=&#39;/content/dense_depths_model_UNET.mp4&#39;, <br>          frame_list=list(range(200,400)), fps = 6)<br><br>show_video(&#39;/content/dense_depths_model_UNET.mp4&#39;, 1000)</pre><p><strong><em>CBAM — Convolutional block attention module</em></strong></p><p>This is an implementation of <a href="https://arxiv.org/pdf/1807.06521.pdf">CBAM: Convolutional Block Attention Module</a>. CBAM includes spatial and channel attention into the network. Attention modules can be implemented so that spatial and channel attention can be helpful in order to maintain attention on physical objects. Shared CBAM layers are used for both left and right images before skip connections.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a9cd4bfe98bf73623b7040a74b0100d/href">https://medium.com/media/4a9cd4bfe98bf73623b7040a74b0100d/href</a></iframe><p><em>Results and Observations:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*PMDes_JNyypzXMbBo2NZQA.png" /></figure><ul><li>There is little to no improvement in the predicted depth maps. There is an improvement in overall structure of the scene</li><li>There is a reduction in chequered artefacts for depth objects</li><li>The artefacts and inconsistencies still exists in the predicted depth maps</li><li>Trying to improve the predicted depth maps using Spatial pyramid pooling and Up-projection</li><li>Spatial pyramid pooling is helpful in extracting multiscale features and up projection is to avoid chequered artefacts in predicted depth maps and consistent depth map creations.</li><li>RMSE on test data is 10.064903</li></ul><p><strong><em>Up-Projection and SpatialPyramidPool(SPP)</em></strong></p><p>Up-Projection:</p><ul><li>Up-projection is a way of upsampling which is described in the <a href="https://arxiv.org/abs/1606.00373">paper</a></li><li>Multiple branches of convolutions for same input are convolved and integrated together forming better structured upsampled feature map</li><li>In this implementation, for every level of upsampling except doubling, upsampling is used, else conv2dTranspose is used. Slight modifications are also done such as using separable convolutions, so as to reduce the memory footprint</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7dc64f0025d0434d693c773dc8322e4/href">https://medium.com/media/c7dc64f0025d0434d693c773dc8322e4/href</a></iframe><p>SPP Implementation:</p><ul><li>SPP is used to extract multi scale features from a given image by convolving at different kernel sizes and merging them together</li><li>This is an implementation of SPP module with slight modifications</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da702d7809ac8a5bed6adf0288e0780f/href">https://medium.com/media/da702d7809ac8a5bed6adf0288e0780f/href</a></iframe><p>Up projection replaced every Conv2D transpose in the decoder, in an attempt to reduce the chequered artefacts in the generated depth maps. Coupled with the addition of CBAM and SPP, there are significant improvements in the generated depth maps.</p><p><em>Results and Observations:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*jq126B-0LOc93NS2p51XaQ.png" /></figure><ul><li>There is a little improvement in the edge separation of objects in depth maps</li><li>There is a significant reduction in the chequered patterns.</li><li>Predicted depth maps are much smoother when compared to older methods.</li><li>Close objects are resolved better than previous methods.</li><li>However, there are still inconsistencies in the depth maps of a single object. The depth maps are not smooth when considered for a single object.</li><li>RMSE score of this method is 10.020688</li></ul><p><strong><em>Transfer learning</em></strong></p><ul><li>There are a lot of inconsistencies in the predictions in the above model which needs to be smoothed out.</li><li>The above models are learning representations of objects from the scratch and also decoding depth data simultaneously.</li><li>There is a possibility that the encoder is not learning enough to extract good feature encodings.</li><li>Hence Transfer learning is used to understand the impact of pre-trained encoder and constructing UNET architecture around it.</li><li>The encoder used here is MobileNetV2. Several other encoders (Densenet, efficient net, resnet, etc.) have been tested and mobilenet v2 performed better among them. MobileNetV2 is faster and also lighter in size.</li><li>Training is done in two ways, first with the encoder weights freezed and second is with unfreezed encoder.</li><li>UNet based structure is used with skip connections between encoder and decoder, The choice of the layers for skip connection is based on layers where there is downsampling.</li><li>Another part that is considered is upsampling and downsampling layers. Padding with zeros is used to overcome where there are difficulties in tensor shapes in concatenating skip connections to decoder layers.</li></ul><pre>core_filter = 16<br>left_input = tf.keras.layers.Input(shape=(img_width, img_height, 3,), name=&#39;Left&#39;)<br>right_input = tf.keras.layers.Input(shape=(img_width, img_height, 3,), name=&#39;Right&#39;)<br><br>out_layers = [Base_encoder.layers[i].output for i in [11, 29, 56, 119, -1]]<br>Encoder = Model(inputs = Base_encoder.input , outputs = out_layers)<br><br>left_pass_1,left_pass_2,left_pass_3,left_pass_4,left_out = Encoder(left_input)<br>right_pass_1,right_pass_2,right_pass_3,right_pass_4,right_out = Encoder(right_input)</pre><ul><li>Since the encoder is freezed, the time to train each step/epoch is reduced significantly.</li></ul><pre># Freezing the layer weights<br>for i in range(len(Base_encoder.layers)):<br>  Base_encoder.layers[i].trainable=False</pre><p><em>Results and Observations:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*c0Z-GIqGt6gDXj1nXK3fvA.png" /></figure><ul><li>The spatial structure is preserved a lot better when compared with previous methods. The passengers are also restructured much better.</li><li>The far objects also have good recognition capacity.</li><li>The depth fringing and chequered artefacts have also reduced significantly</li><li>Despite improvement in depth maps, the RMSE is 11.611034 which is slightly higher.</li></ul><p>Tuning encoder with unfreezed weights, along with decoder resulted in low RMSE scores so far.</p><p><em>Results and Observations:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*Mh2-Sa3L3G5fsL6iHLNK7g.png" /></figure><ul><li>The generated depth maps are significantly smoother when compared to previous methods indicating poor encoding performance.</li><li>The RMSE calculated is 9.628401 which is the lowest so far</li></ul><p><strong><em>Changing approach : Fusion to create depth map</em></strong></p><ul><li>This is an implementation of <a href="https://arxiv.org/abs/2109.11393">Cross attention guided dense network for fusion</a></li><li>Instead of using shared weights and then merging them at the low levels, this method consistently fuses the stereo pair and processes to get depth maps.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*KPhnx2mqob30D_2p" /><figcaption>Fusion architecture</figcaption></figure><ul><li>Two images are fused to get the final desired output by training at the same resolution and using attention to match the features between the images.</li><li>Resolution of images is reduced to 220x100 due to large vram consumption.</li></ul><p><em>Results and Observations:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*t6QIE-P66MLlj3TdUE9rAg.png" /></figure><ul><li>This method has also produced interesting results. The encoder is trained from random weights and still generated depth maps closer to the Transfer learning method.</li><li>Object boundaries are consistent across multiple runs and depth maps.</li><li>The RMSE score is 10.477098</li></ul><h3>Final Results:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*GnfXCQ1bfeLP8rx-" /></figure><p>From the above results, the best performance is provided by the Encoder unfreezed transfer learning method closely followed by flownet based custom model. The parameter size is also provided to provide a glimpse of model size.</p><h3>Future scope:</h3><ul><li>Depth map predictions for longer distances are influencing the metric. Metric for every 10m distance can give a glimpse of error distribution.</li><li>Decoder architecture can have better left-right fusion capacity.</li><li>The metric is not indicating the reconstruction structure of objects in images.</li><li>Attention module from fusion model can be included instead of CBAM and can be verified</li><li>Joint training of depth along with object detection could give better depth reconstruction capacity</li><li>Using depth map from previous frame for current frame depth prediction can help boost depth prediction</li></ul><h3>References:</h3><ul><li><a href="https://dibyendu-biswas.medium.com/stereo-camera-calibration-and-depth-estimation-from-stereo-images-29d87bc702f3">Stereo Camera Calibration and Depth Estimation from Stereo Images</a></li><li><a href="https://github.com/kujason/ip_basic">IP Basic</a></li><li><a href="https://keras.io/examples/vision/depth_estimation/">Keras : Monocular depth estimation</a></li><li><a href="https://arxiv.org/pdf/1504.06852.pdf">FlowNet</a></li><li><a href="https://prateekvjoshi.com/2016/04/12/understanding-locally-connected-layers-in-convolutional-neural-networks/">Understanding Locally Connected Layers In Convolutional Neural Networks</a></li><li><a href="https://medium.com/machine-learning-for-li/different-convolutional-layers-43dc146f4d0e">A Summary of Neural Network Layers</a></li><li><a href="https://arxiv.org/pdf/1807.06521.pdf">CBAM: Convolutional Block Attention Module</a></li><li><a href="https://arxiv.org/abs/1606.00373">Up-Projection</a></li><li><a href="https://www.tensorflow.org/api_docs/python/tf/keras/applications/mobilenet_v2/MobileNetV2">MobileNetV2</a></li><li><a href="https://arxiv.org/abs/2109.11393">Cross attention guided dense network for fusion</a></li><li><a href="https://github.com/shenzw21/CADNIF/blob/master/utils.py">Cross attention : Github</a></li></ul><p><em>For any doubts, or queries, the readers may comment in the blog post itself, or connect with me on </em><a href="https://www.linkedin.com/in/sriram-pasupuleti/"><em>LinkedIn</em></a><em>.</em></p><p>You can find the code in <a href="https://github.com/sriram-pasupuleti/Stereo_Depth_Estimation">github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18fd423446e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stereo depth estimation on DrivingStereo Dataset : Part-1]]></title>
            <link>https://medium.com/@Sriram-P/stereo-depth-estimation-on-drivingstereo-dataset-part-1-884388156c93?source=rss-5883b9816e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/884388156c93</guid>
            <dc:creator><![CDATA[R.A.M]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 16:38:49 GMT</pubDate>
            <atom:updated>2023-03-06T16:40:13.645Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Stereo depth estimation on DrivingStereo Dataset : Part-1</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*uWx0mePWsZLPD-Ku" /><figcaption>Photo by <a href="https://unsplash.com/@samuele_piccarini">samuele_piccarini</a> on <a href="https://unsplash.com/photos/MyjVReZ5GLQ">unsplash</a></figcaption></figure><p>The recent rise of autonomous driving vehicles is due to the development of faster computing as well as extensive improvements in deep learning techniques. The role of deep learning is to facilitate the perception of the surroundings to the vehicle. One of the main problems in perceiving the surroundings and observing targets is to extract depth information. The depth information is used to understand, localise the vehicles surrounding the subject vehicle and plan appropriate and accurate manoeuvres.</p><p>This two part series explores various existing deep learning architectures and custom models in calculating depth from stereo images. The two parts in this series are separated as follows:</p><ul><li>Part-1 : Introduction, Literature survey and Metrics</li><li><a href="https://medium.com/@Sriram-P/stereo-depth-estimation-on-drivingstereo-dataset-part-2-18fd423446e3">Part-2 : Modeling, Training and results</a></li></ul><h3>Table of Contents</h3><ul><li>Business Problem</li><li>Dataset : DrivingStereo</li><li>Loss function</li><li>Evaluation Metrics</li><li>Literature survey</li></ul><h3><strong>Business Problem</strong></h3><p>Existing methods of depth estimation involve using either LIDAR/RADAR or camera sensors. Depth data from LIDAR is very accurate but it generates huge data per second which needs stronger throughput devices and LIDAR is also expensive. Camera on the other hand generates less data in comparison and is inexpensive. Hence camera based depth estimation is gaining momentum in the self driving industry. Measuring depth from a stereo(pair) camera is generally more advantageous than monocular camera due to the <a href="https://en.wikipedia.org/wiki/Stereopsis">stereopsis</a> phenomenon.</p><p>Traditional stereo vision solutions involve solving a problem called correspondence problem i.e obtaining matching points/pixels in the two images which requires calibration of cameras and rectification of images which are inconsistent at best. Here, deep learning techniques take the role of obtaining depth from the stereo images end-to-end using various deep architectures.</p><h3><strong>Dataset : DrivingStereo</strong></h3><p>The dataset taken for this study is from DrivingStereo (<a href="https://drivingstereo-dataset.github.io/">Link</a>). The dataset is a large-scale stereo dataset containing over 180k images covering a diverse set of driving scenarios. There are two advantages (from the perspective of training) in using this dataset:</p><ol><li>Data is split into smaller sized zip files</li><li>Each split of data is available via google drive</li></ol><p>The existing available datasets are usually huge in size and are difficult to import into the colab environment. The DrivingStereo dataset can be directly downloaded to google colab with a shared google drive link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/0*81wjn86BCpeqGKGx" /><figcaption>zip files segregated in the google drive</figcaption></figure><p>The dataset for any stereo depth estimation problem contains at least three components of frames/images.</p><ol><li>Left stereo camera images/frames</li><li>Right stereo camera image/frames</li><li>Disparity/Depth maps for corresponding images/frames</li></ol><p>Left and right images are frames of the same scene but are from the perspective of distance separated cameras. Depth/Disparity maps are usually processed depth data captured from Lidar or other similar methods. More information can be found in <a href="https://medium.com/analytics-vidhya/distance-estimation-cf2f2fd709d8#:~:text=Stereo%20vision%20is%20a%20technique,of%20rays%20from%20multiple%20viewpoints.">this</a> in depth article.</p><p>The dataset contains sequential images of resolution 881x400 in jpg format. The images are downscaled further for training in colab. The disparity maps and depth maps are in uint16 .png images. The disparity value and depth value for each pixel can be computed by converting the uint16 value to float and dividing it by 256. The zero values indicate the invalid pixels. The depth map can be understood better by looking at the heatmaps with colour indicating depth.</p><h3><strong>Loss function</strong></h3><p>Various forms of loss functions are proposed in the literature for training networks over depthestimation. Few major losses used are as follows.</p><ul><li>Scale invariant loss discussed in <a href="https://medium.com/@omarbarakat1995/depth-estimation-with-deep-neural-networks-part-1-5fa6d2237d0d">blog</a> and <a href="https://arxiv.org/pdf/1411.4734.pdf">here</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*iHb_rCgf_UoA4cEp" /><figcaption>Scale invariant loss formulation</figcaption></figure><ul><li>Combinations of existing and new losses as discussed <a href="https://arxiv.org/pdf/2009.09934.pdf">here (section 3.5)</a> which is a sum of L1 loss, Structural similarity index measure and multinomial logistic loss.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*IHC7IkextntilNUV" /><figcaption>Loss illustration</figcaption></figure><ul><li>Smooth L1 loss is used in papers <a href="https://arxiv.org/pdf/1803.08669.pdf">1</a> and <a href="https://cse.sc.edu/~songwang/document/iccv19a.pdf">2</a></li></ul><p>Smooth L1 loss is used initially but a combination of the three losses as in the second point yielded better results and hence it is used for training models in later models.</p><h3><strong>Evaluation metrics</strong></h3><p>There are various evaluation metrics proposed in the literature. Popular metric used to evaluate is Root mean squared error and absolute relative error. In some situations, Log RMSE error is also used as an evaluation metric. In this case study, RMSE is used as the primary evaluation metric.</p><h3><strong>Literature survey</strong></h3><h4>1. <a href="https://arxiv.org/pdf/2009.09934.pdf">Monocular Depth Estimation Using Multi Scale Neural Network And Feature Fusion</a></h4><ul><li>This paper uses monocular images instead of stereo images. The network in this paper uses pretrained Resnet as a feature extractor.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*72uDYkmegdqiU6KLH94h9w.png" /><figcaption>Network architecture used in this work</figcaption></figure><ul><li>The features from Resnet are convolved with multiscale weights which are concatenated together which are followed by parallel dilated convolutions. This is similar to the spatial pyramid pooling used in PSMNet.</li><li>This paper also uses image augmentation techniques from which some of them can be used in this case study. Since this case study is on stereo images, some of the aug techniques are not applicable as they break the geometric relationships between stereo images. So it is important to select the techniques carefully.</li></ul><h4>2. <a href="https://arxiv.org/pdf/1703.04309.pdf">End-to-End Learning of Geometry and Context for Deep Stereo Regression (GCNet)</a></h4><ul><li>GCNet is one of the first to implement cost volume technique followed by 3D convolutions in the architecture for stereo vision systems.</li><li>One of the consistent techniques in the following papers is to use shared weights to obtain features for left and right images which is an equivalent of siamese network. The features extracted at this point are called unary features.</li><li>The features obtained for left and right images are concatenated such that a 3D volume is created which is a combination of each feature vector from left and right. In this paper, concatenation is used whereas in others, cosine or feature summation is used.</li><li>The cost volume is followed by multi scale 3D convolutions to extract features from local and global perspectives. This is followed by a Soft differentiable argmax to obtain a final disparity map.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*hPoMKYLFS_r-0IIL" /><figcaption>Network arcihtecture of GCNet</figcaption></figure><ul><li>This paper implemented L1 loss for training the network and also evaluated that the formulation of the problem as regression is much better than a multiclass classification problem. This is one of the reasons for the case study to be formulated as a regression problem.</li><li>The shared weight based training i.e siamese training can be used in this case study followed by cost volume technique.</li></ul><h4>3. <a href="https://arxiv.org/pdf/1807.08865.pdf">StereoNet</a></h4><ul><li>Stereonet utilizes the similar siamese network type of training for unary feature extraction and cost volume creation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*Rmx2YL-X_4X7wPUF" /><figcaption>Network architecture of stereonet</figcaption></figure><ul><li>Stereo network fairly suffers from textureless surfaces, mirrors and lambertian surfaces. For identifying such surfaces, context surrounding the surface will be helpful so that their effect is reduced.</li><li>In order to tackle this problem, features are extracted with larger receptive fields. The input images are aggressively downsampled using K 5×5 convolutions with a stride of 2. These are followed by residual blocks and batch normalization. The output is a 32-dimensional feature vector at each pixel in the downsampled image.</li><li>Similar to the GCNet, cost volume is constructed with the low dimensional features. The difference is that the features are reduced in size when compared to GCNet providing compute boost.</li><li>Interesting part in the paper is the hierarchical refinement. The refinement network takes as input the disparity bilinearly upsampled to the output size as well as the color resized to the same dimensions. The concatenated color and disparity first pass through a 3 × 3 convolutional layer (Dilated convolutions are used for bigger receptive fields).</li><li>The output of this network is a 1-dimensional disparity residual that is then added to the input prediction to scale borders or the objects.</li><li>This paper uses a form of smoothed L1 loss. The final refinement can be used in this case study to process final depth prediction of the stereo images.</li></ul><h4>4. <a href="https://arxiv.org/pdf/1803.08669.pdf">Pyramid Stereo Matching Network (PSMNet)</a></h4><ul><li>This paper is one of the first to introduce spatial pyramid pooling, which is multiscale convolutions and upsampling+concatenation.</li><li>Similar to GCNet and StereoNet discussed above, this network uses siamese training which also includes the spatial pyramid pooling, till the cost volume extraction.</li><li>On the cost volume, stacked hourglass methods are used, which are repeated encoder-decoders where encoder distills the input through a series of contracting layers to a bottleneck that captures the details most relevant to the task in training, and the decoder reconstructs the output from the representation captured in the bottleneck layer through a series of expanding layers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*EsBVMBTAm8F-jeBG" /><figcaption>Network architecture of PSMNet</figcaption></figure><ul><li>The encoders and decoders have interconnected residual connections across encoder-decoders. The depth regression is done in various levels which can be extracted based on refinement level required.</li><li>This paper also used smooth L1 loss for training the network. The spatial pyramid pooling module can be implemented to extract multi scale features in the case study.</li></ul><h4>5. <a href="https://arxiv.org/pdf/1810.11408v2.pdf">Anytime Stereo Image Depth Estimation on Mobile Devices (AnyNet)</a></h4><ul><li>This paper mainly focuses on the tradeoff between speed of estimation and accuracy of the estimation. The networks discussed above i.e GCNet, PSMNet suffers from requiring heavy compute resources. AnyNet on the other hand targeted mobile devices.</li><li>The target device is the Nvidia Jetson TX2 GPU module, which is reaching about 30FPS on AnyNet whereas PSMNet is averaging about 0.3FPS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*dVofxgpAmO95UIHSDlpyWw.png" /><figcaption>Network architecture of AnyNet</figcaption></figure><ul><li>AnyNet uses UNET as the primary multi scale feature extractor for both left and right images. The input is a pair of images left and right and the disparity is directly estimated in various stages.</li><li>With the lowest features, The disparity network is used to extract a raw disparity map. This is stage 1 and the disparity is vague and not accurate. However, this disparity is repeatedly improvised step by step by extracting a residual map which is added to the disparity predicted in stage-1.</li><li>This process is followed recursively as shown in the above top view image. Finally, SPNet (spatial propagation network) is used to sharpen the prediction to more accurate levels. The disparity at various stages can be extracted as required.</li></ul><h4>6. <a href="https://arxiv.org/pdf/1804.03999.pdf">Attention U-Net</a></h4><ul><li>Attention U-Net is an extension of unet with an added attention module</li><li>The attention module is placed in the skip connection between residual connection from encoder to decoder.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*b4NO9ZCB6e1i_xYu" /><figcaption>Network architecture of Attention U-Net</figcaption></figure><ul><li>The attention layer (attention gate) focuses on controlling the focus on the necessary parts of the image.</li></ul><h3><strong>First Cut Approach</strong></h3><ol><li>Similar to the AnyNet described in the above papers, Unet is used as the primary feature extractor for the study. However, for each level in the UNET, the cost volume is constructed from lowest encoder feature representation. The lowest extracted features can generate a rough estimate of the disparity map. The rest of the above layers can be used for fine tuning the generated map.</li><li>For the above layers, instead of directly concatenating the features, attention gates discussed in the attention UNET to be used.</li><li>The output of the Unet is used to estimate disparity maps instead of generating cost volume. The hierarchical refinement introduced in the stereo can be used to generate a refined disparity map.</li><li>The Encoder part of the Unet is shared between the left and right image. The left and right image should be combined/concatenated and then an attention gate is applied before sending it to the decoder for estimation.</li><li>Loss functions are not standard as in classification. Initially Smooth L1 is used as a primary loss but losses like scale invariant loss, structural similarity index measure can be implemented and analysed.</li><li>Similar to AnyNet, The idea is to make it extract multi level stereo depths at different levels. Another extension for this network is to extend the network to monocular depth estimation by using consecutive frames.</li></ol><h3>References</h3><ol><li><a href="https://en.wikipedia.org/wiki/Stereopsis">Stereopsis Phenomenon</a></li><li><a href="https://towardsdatascience.com/depth-estimation-1-basics-and-intuition-86f2c9538cd1">Depth estimation intuition by Daryl Tan</a></li><li><a href="https://www.intechopen.com/chapters/67181">Efficient Depth Estimation Using Sparse Stereo-Vision with Other Perception Techniques</a></li><li><a href="https://drivingstereo-dataset.github.io/">DrivingStereo</a></li><li><a href="https://medium.com/@omarbarakat1995/depth-estimation-with-deep-neural-networks-part-1-5fa6d2237d0d">Depth estimation with deep Neural networks</a></li><li><a href="https://arxiv.org/pdf/1411.4734.pdf">Predicting Depth, Surface Normals and Semantic Labels with a Common Multi-Scale Convolutional Architecture</a></li><li><a href="https://cse.sc.edu/~songwang/document/iccv19a.pdf">Semantic Stereo Matching with Pyramid Cost Volumes</a></li><li><a href="https://arxiv.org/pdf/2009.09934.pdf">Monocular Depth Estimation Using Multi Scale<br>Neural Network And Feature Fusion</a></li><li><a href="https://arxiv.org/pdf/1703.04309.pdf">End-to-End Learning of Geometry and Context for Deep Stereo Regression (GCNet)</a></li><li><a href="https://arxiv.org/pdf/1807.08865.pdf">StereoNet</a></li><li><a href="https://arxiv.org/pdf/1803.08669.pdf">Pyramid Stereo Matching Network (PSMNet)</a></li><li><a href="https://arxiv.org/pdf/1810.11408v2.pdf">Anytime Stereo Image Depth Estimation on Mobile Devices (AnyNet)</a></li><li><a href="https://arxiv.org/pdf/1804.03999.pdf">Attention U-Net</a></li></ol><p><em>For any doubts, or queries, the readers may comment in the blog post itself, or connect with me on </em><a href="https://www.linkedin.com/in/sriram-pasupuleti/"><em>LinkedIn</em></a><em>.</em></p><p>You can find the code in <a href="https://github.com/sriram-pasupuleti/Stereo_Depth_Estimation">github</a>. Part-2 can be found <a href="https://medium.com/@Sriram-P/stereo-depth-estimation-on-drivingstereo-dataset-part-2-18fd423446e3">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=884388156c93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Battery capacity estimation using Machine Learning : Part-2]]></title>
            <link>https://medium.com/@Sriram-P/battery-capacity-estimation-using-machine-learning-part-2-a51944953d86?source=rss-5883b9816e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a51944953d86</guid>
            <dc:creator><![CDATA[R.A.M]]></dc:creator>
            <pubDate>Mon, 31 Jan 2022 17:07:50 GMT</pubDate>
            <atom:updated>2022-02-02T19:00:00.290Z</atom:updated>
            <content:encoded><![CDATA[<h3>Battery capacity estimation using Machine Learning : Part-2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ADi9z1fg9bxMACCn" /><figcaption>Photo by <a href="https://unsplash.com/@daniloalvesd?utm_source=medium&amp;utm_medium=referral">Danilo Alvesd</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is a two part blog series on understanding and predicting battery capacity using machine learning. In the <a href="https://medium.com/@Sriram-P/battery-capacity-estimation-using-machine-learning-part-1-1347f3047324">part-1</a> of battery capacity estimation with machine learning, EDA and data preprocessing is discussed. In this part, feature engineering, modeling and results are discussed.</p><h3>Table of Contents</h3><ul><li>Feature Extraction</li><li>Modeling</li><li>Results</li><li>Future work</li><li>References</li></ul><h3>5. Feature engineering</h3><h4>5.1 Charge cycle:</h4><p>For charge cycles, the following features are analyzed and extracted.</p><ul><li>Duration in Constant current mode</li><li>Decay of current</li><li>Peak temperature over mean</li></ul><p><strong>CC mode duration</strong></p><p>This indicates the duration of charging in which the cell stayed in constant current while charging. Since charging was carried out in a constant current mode at 1.5A, Time column for indices corresponding to 1.5 are obtained and converted into minutes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8c1e9e5f043bd5ce42945f47340b595/href">https://medium.com/media/e8c1e9e5f043bd5ce42945f47340b595/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*gEfRRwk1r9HgFHdy" /></figure><p><strong>Decay of current</strong></p><p>In charging mode, once mode shifts to CV mode, current steadily decays and eventually enters trickle mode. During this process, the current decay can be observed if it has any relation with capacity by fitting a polynomial curve and observing coefficients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/749e03f517a7bc386025963b0cde2603/href">https://medium.com/media/749e03f517a7bc386025963b0cde2603/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*GnjCrm6X5_qkjBaeI0osVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*lCaeA5qLxkJuad7-eulNsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*eHw6ZmR92QH_GatJgCZ26w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*gdSGZzymyZBdGw_Mq_KUXA.png" /></figure><p>The above plots are coefficients of a curve fitted to the decaying current which can be interpreted as a curve. The order of the curve (np.polyfit) is obtained by manually plotting and chosing the best order in which the curve is not fitting overly to the cycle data. These are the variation of coefficients of fitted curves on charge cycle over increasing order of cycles. These coefficients capture decay rate duration shifts that happen when the cell/battery loses capacity. The coefficients are very low in magnitude</p><p><strong>Peak temperature over median</strong></p><p>Difference between median temperature and peak temperature is calculated</p><pre>peak_temp_med = [max(d[&#39;data&#39;][&#39;Temperature_measured&#39;]) - np.median(d[&#39;data&#39;][&#39;Temperature_measured&#39;]) for d in charge_data]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*c6Q2nKr9RbXGWCmr" /></figure><p>The difference is increasing with a significant trend to it, but it is irregular in nature as well. This curve can be processed through SG-filter to obtain smoothed values which can be used as a feature</p><h4><strong>5.2 Discharge Cycle:</strong></h4><p>For discharge cycles, the following features are analyzed and extracted</p><ul><li>CC mode duration</li><li>Recovery voltage magnitude</li><li>Decay rate of voltage</li><li>growth parameters of temperature in CC mode</li></ul><p><strong>CC mode duration</strong></p><p>Duration of cycle which stayed in constant current mode while discharging.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f12012488eb10c0ac2008670f65ba996/href">https://medium.com/media/f12012488eb10c0ac2008670f65ba996/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*mw93fyXVnezd8ab-" /></figure><p>The above plot is Change of CC mode duration in discharge mode over multiple cycles. The decrease in trend is similar to the decrease in trend of the target variable.</p><p><strong>Recovery voltage magnitude</strong></p><p>The voltage that the battery gains, once the discharge is completed is the voltage recovered. The magnitude of the recovery voltage is different as the cycle reaches EOL.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/043b3c8182d6490d4c8a1f9b36ddc611/href">https://medium.com/media/043b3c8182d6490d4c8a1f9b36ddc611/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*VjOq3zGpOIgfOrd-" /></figure><p>The recovery voltage seems to increase over time clearly with some irregularity in the initial measurements</p><p><strong>Decay rate of voltage</strong></p><p>In the discharge cycle, the voltage decreases over time. A polynomial curve is fitted and coefficients are extracted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fd521e92dd47dc4dca4f54ac90e3aa0/href">https://medium.com/media/1fd521e92dd47dc4dca4f54ac90e3aa0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*psGuN2weIJmQew2A" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*GIz8tLkbvNcvqizp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*vo0Jgw7eOKTf302-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*eQC9pfLkdr-fJFL4" /></figure><p>Coefficients of fitted curves for voltage decay are reducing consistently on how there is a decrease in voltage duration as cycles increase.</p><p><strong>Rate of temperature in CC mode:</strong></p><p>During discharge, as long as the current stays constant, the temperature steadily rises. The variation of rise of temperature can be observed by fitting a polynomial curve and plotting coefficients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8e1b80811456a470a59d7ee4a2185ce/href">https://medium.com/media/e8e1b80811456a470a59d7ee4a2185ce/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*THJwK4-TQ3RFGvBg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*rtOigh6hEVlMIWmL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*9ormYaFU4zI9GbKz" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*fvJeJhv5mAI42_97" /></figure><p>Three of the four coefficients are almost linearly increasing/decreasing. 4th coefficient, which is the main component, is not consistent in any direction.</p><h4><strong>5.3 Sequential Spectrum Analysis</strong></h4><p>In previous methods, feature information is extracted by looking at only one cycle information. As the battery capacity degrades, there are noticeable differences in charge — discharge profiles. This difference between cycles is not noticeable when looked at two consecutive cycles, but are observable when looked a few cycles away from the current cycle. These cycles also contain a lot of noise while logging which makes point to point comparison difficult. The consecutive method uses SSA to remove periodic noise, fluctuations etc from the main cycle data which are then compared with previous cycles. For each current cycle, past 10 cycles data can be used to obtain relative change in profiles which captures/correlates to reduction in capacity over time.First two components are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*89hKrlFkOyCE70wn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z640vNoLCJ0Yr_gK" /></figure><p><strong>Similarity based analysis</strong></p><p>A window of 10 previous cycles is averaged and then compared with current cycle data to obtain an estimate of similarity. Dot product used to obtain similarity between the cycles. To compute the dot product, the two inputs should be of the same size, So from each cycle, percentiles are extracted. The similarity based variation is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NMWAQ5Zfd_kel3CP" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3862fe5132eb2b011dd61bf8bdfeff8d/href">https://medium.com/media/3862fe5132eb2b011dd61bf8bdfeff8d/href</a></iframe><p>The similarity with SSA is processed for charge voltage, discharge voltage, charge current and discharge current.</p><h4>5.4 Fourier transform</h4><p>Similar to SSA, Fourier transform is applied on the ten cycles, frequencies are extracted. The components of the frequencies are separated and categorized based on cycles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eea4d118f0281b851d82772374d1dcb/href">https://medium.com/media/6eea4d118f0281b851d82772374d1dcb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Os046bxBliaCoOKJeZTIrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3cVyP8_2luklxxSUIALmg.png" /></figure><h3>6. Models</h3><p>The dataset after feature engineering contains a very low number of points. Train data contains 68 rows and test data contains relatively higher 99 rows. The training can be done with 68 datapoints but there is a possibility of overfitting. Hence the train data is upsampled using linear interpolation between cycles. This means that fake cycles data is created based on actual cycle data. However, there is a need to know if the data interpolation made any difference in performance of the models. So initially, the models are fitted on the sparsely available data to obtain a ‘baseline’ like metrics.</p><h4>No interpolation</h4><p><strong>SGD regressor</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/320146e93caeb75875a967212bc55678/href">https://medium.com/media/320146e93caeb75875a967212bc55678/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6MYpf0T6zKsCqJebQRm6Q.png" /><figcaption>SGD (no interpolation): MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdKBz46TuRm6K6hoDxMX-Q.png" /><figcaption>SGD (no interpolation) : MAPE</figcaption></figure><p><strong>SVM regressor</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d987669a4bb838445542d3f737f10d2/href">https://medium.com/media/2d987669a4bb838445542d3f737f10d2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QR6yolAmgklQXFtQXYXZNQ.png" /><figcaption>SVR(no interpolation) : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJkMYGvt_FiM0mzDwPAUoA.png" /><figcaption>SVR(no interpolation) : MAPE</figcaption></figure><p><strong>RANSAC regressor</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d6181810bdb7b55018585040d6428ba/href">https://medium.com/media/8d6181810bdb7b55018585040d6428ba/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opMAdQHSPP2AjuBRHEtgyQ.png" /><figcaption>RANSAC (no interpolation) : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2wYnAXuWP3cza_rXRidJg.png" /><figcaption>RANSAC (no interpolation) : MAPE</figcaption></figure><p><strong>Decision Tree</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3e1fa589442dede717500e7cc5dcd4d/href">https://medium.com/media/c3e1fa589442dede717500e7cc5dcd4d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wc4NK1fw6FJfj1POJ-tyTg.png" /><figcaption>Decision trees (no interpolation) : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQzp56RXsuPhvQqQZTEBqw.png" /><figcaption>Decision trees (no interpolation) : MAPE</figcaption></figure><p><strong>Adaboost</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cf077e0856a87f5d420625bc7f600df/href">https://medium.com/media/8cf077e0856a87f5d420625bc7f600df/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-RBJhKkR6CvvmVM_ey1Ig.png" /><figcaption>ADABOOST (no interpolation) : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5Am6ZimC0eXwn_S_mxrfw.png" /><figcaption>ADABOOST ((no interpolation) : MAPE</figcaption></figure><p><strong>Random forest</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/219493e12d4a5897d218634667deee3b/href">https://medium.com/media/219493e12d4a5897d218634667deee3b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuFu6cNoAKXmx3vuoOEXng.png" /><figcaption>Random Forest (no interpolation) : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XQnjPcfgP62SM6YAETzLw.png" /><figcaption>Random Forest (no interpolation) : MAPE</figcaption></figure><p><strong>GBDT</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36ba652add438ebd083aaf1515db074b/href">https://medium.com/media/36ba652add438ebd083aaf1515db074b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zj5iwdjxJj1cmbWTcdnc0A.png" /><figcaption>GBDT (no interpolation) : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KavaN5vV8RNLYtMh11z7fw.png" /><figcaption>GBDT (no interpolation) : MAPE</figcaption></figure><p><strong>Models with best parameters</strong></p><p>Models with best hyperparameters used above are all gathered to understand relative performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KH7CcoFj93UMM4OIktG5Jw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1XkgW746rMlKeZQ8yIZxXQ.png" /><figcaption>Best model comparison : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcuT6N9_H2ALaj6yhK69ig.png" /><figcaption>Best model comparison : MAPE</figcaption></figure><ul><li>It can be seen that Random forest seems to be doing well when compared to all other models</li><li>Decision tree seems to be doing better than RF but it is overfitting which resulted in higher difference in train and test metrics when compared to RF model</li></ul><h4>Interpolation</h4><p>Method of interpolation:</p><ul><li>Sort the training data based on cycle column</li><li>expand_len : number of observations to which the existing dataset is to be interpolated</li><li>dummy_row_len = expand_len/existing_dataset_rows, gives how many new points are needed to be generated between two rows of existing dataframe rows</li><li>Create new dataframe with rows equal to expand_len and columns equal to existing dataframe and value of np.nan</li><li>for every dummy_row_len, add a row from existing dataframe into new df</li><li>for each column, use pandas.interpolate function to obtain nan values</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/497a89150ee578b158e9a4a814ed93c6/href">https://medium.com/media/497a89150ee578b158e9a4a814ed93c6/href</a></iframe><pre>DF_upsamp = interpolate_data(DF_train, 1020)</pre><p>After interpolation, the train data size is increased to 1020 datapoints</p><p><strong>SGD regressor</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/320146e93caeb75875a967212bc55678/href">https://medium.com/media/320146e93caeb75875a967212bc55678/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYDPGCVQJv5irFGoYfBeBg.png" /><figcaption>SGD : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otQ1IDiJHfui9r5OZTcVrw.png" /><figcaption>SGD : MAPE</figcaption></figure><p><strong>SVM regressor</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d987669a4bb838445542d3f737f10d2/href">https://medium.com/media/2d987669a4bb838445542d3f737f10d2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inHSdktPS7-RRuoNE6C3_g.png" /><figcaption>SVM : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6I9Lq8UvVTQxJd_HIB58w.png" /><figcaption>SVM : MAPE</figcaption></figure><p><strong>RANSAC regressor</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d6181810bdb7b55018585040d6428ba/href">https://medium.com/media/8d6181810bdb7b55018585040d6428ba/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1q5gVD95gsaQhhq5RoKTA.png" /><figcaption>RANSAC : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QPHz4IID3YrOg5lqPIInw.png" /><figcaption>RANSAC : MAPE</figcaption></figure><p><strong>Decision tree regressor</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3e1fa589442dede717500e7cc5dcd4d/href">https://medium.com/media/c3e1fa589442dede717500e7cc5dcd4d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9sLKiEoRxxmDunEktocAA.png" /><figcaption>Decision trees : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dJ2Lpx_JsaABomZl13IoQ.png" /><figcaption>Decision trees : MAPE</figcaption></figure><p><strong>Adaboost regression</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cf077e0856a87f5d420625bc7f600df/href">https://medium.com/media/8cf077e0856a87f5d420625bc7f600df/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTzGks9wDanm6gUdp8wjfA.png" /><figcaption>Adaboost : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VytkV-YGqwZDrFc4EU-TOg.png" /><figcaption>Adaboost : MAPE</figcaption></figure><p><strong>Random forest regressor</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/219493e12d4a5897d218634667deee3b/href">https://medium.com/media/219493e12d4a5897d218634667deee3b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_cJ7yZVB2JE7DH3zA01Og.png" /><figcaption>Random Forest : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXwa482DQ25JCiQnExJjuw.png" /><figcaption>Random Forest : MAPE</figcaption></figure><p><strong>GBDT</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36ba652add438ebd083aaf1515db074b/href">https://medium.com/media/36ba652add438ebd083aaf1515db074b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beGVQPEnZNRRGqcUX-9Ovg.png" /><figcaption>GBDT : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mg7APrZ_AJMQVJkTqiRIlQ.png" /><figcaption>GBDT : MAPE</figcaption></figure><p><strong>LGBM</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1acedd45527ec8a0437f6547f1b4d13/href">https://medium.com/media/a1acedd45527ec8a0437f6547f1b4d13/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOzQmQnW-lGHS84hSXn07g.png" /><figcaption>LGBM : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BM_fg4OU0kLdB4bb_nOqLw.png" /><figcaption>LGBM : MAPE</figcaption></figure><p>Relative comparison of models with best hyperparameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUqIAToakTJSG6iSLWkm7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WF0vzMoOgvyfZFT0LXUqKw.png" /><figcaption>Best models (interpolation) : MAE</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WuMQT6YRqNCTPIqbAiu1iQ.png" /><figcaption>Best models (interpolation) : MAPE</figcaption></figure><p>Random forest and LGBM are close best performers with LGBM slightly in lead. Linear models are not great performers in this case and GBDT performs worse than linear regression. LGBM is added to data to verify the performance of standard boosted models other than sklearn GBDT.</p><p><strong>Custom stacking model</strong></p><p>A custom stacking model is implemented which is a bootstrapped ensemble of multiple models and a meta model. The process of the custom model is described below.</p><ul><li>The entire dataset is separated into train and test set (80–20)</li><li>The train set(80%) is splitted into two sets D1 and D2 (50–50)</li><li>On the dataset D1, Sampling with replacement is done to create sub-datasets d1, d2, d3..dk(k samples)</li><li>With the k samples, k models are trained with each sample set in k. This creates k base models which are trained on slightly different k datasets.</li><li>Using the K models, predict K predictions on the dataset D2. The K predictions for each point in D2 is used to train a meta model.</li><li>The test set (20%) which is left out in the beginning is used as an evaluation set to understand the performance of the custom model.</li></ul><p>In order to implement this process, a custom class is implemented which includes k datasets creation, base model training and meta model training. The custom model is implemented in three different ways.</p><ol><li>Fixed base model hyperparameters : The base models are with hyperparameters which performed best in previous training.</li><li>Randomized hyperparameters: The base models are top 3 or 4 performing models in previous training and are picked randomly.</li><li>Flexible base model: The base models can be explicitly mentioned during the custom model initiation. If no models are mentioned, it falls back to fixed base model type custom model. Below is the code for the flexible base model. This is chosen as the final custom model as it performed better than the above two types of custom models after tuning with various combinations of base models.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/277484d8c275ec37f75651aa13434d99/href">https://medium.com/media/277484d8c275ec37f75651aa13434d99/href</a></iframe><p><strong>Arguments for custom model :</strong></p><ul><li>sample_k- No of base models</li><li>sample_size- No of data samples per base model</li><li>base_models- List of base models to choose. In np.nan, models are chosen randomly which adds more randomness to the custom model</li></ul><p>The custom model is trained and the performance metrics MAE and MAPE are tracked.</p><pre>mae = []<br>mape = []<br>for _ in tqdm(range(500)):<br>  model = Custom_model(16, 256, base_models = [&#39;RF&#39;,&#39;LGBM&#39;])<br>  model.fit(X_train_1, X_train_2, y_train_1, y_train_2)<br>  y_test_pred = model.predict(X_test)<br>  mae.append(mean_absolute_error(y_test,y_test_pred))<br>  mape.append(mean_absolute_percentage_error(y_test,y_test_pred))</pre><p>The custom model has MAE of 0.00608 and MAPE of 0.35%. This data when included along with the previous models gives a better context of the performance.</p><h3>7. Results</h3><p>The best set of models from each category i.e no-interpolation, interpolation and interpolation + custom models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*29R8x9miHADpodSFDTBbpA.png" /></figure><p>From no interpolation to interpolation of data, there is a significant improvement in performance. The custom model also performed better than Random forest with no interpolation but was slightly behind the performance of LGBM.</p><h3>8. Deployment</h3><p>The model is deployed locally using streamlit which takes cycle number as input and generates capacity as output.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_YmbuKlwpfs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_YmbuKlwpfs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_YmbuKlwpfs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eee555caa85281f15b310c9df302b81/href">https://medium.com/media/4eee555caa85281f15b310c9df302b81/href</a></iframe><h3>9. Future work</h3><ul><li>A dataset with features having varying load would be more useful as applications tends to have varying load.</li><li>Dependency on previous cycles can be removed.</li><li>Application specific data will be more insightful in understanding load variation and capacity variation.</li></ul><h3>10. References</h3><ol><li><a href="https://www.researchgate.net/publication/333643175_Machine_Learning-Based_Lithium-Ion_Battery_Capacity_Estimation_Exploiting_Multi-Channel_Charging_Profiles">(PDF) Machine Learning-Based Lithium-Ion Battery Capacity Estimation Exploiting Multi-Channel Charging Profiles (researchgate.net)</a></li><li><a href="http://ssa.cf.ac.uk/ssa2010/a_brief_introduction_to_ssa.pdf">A Brief Introduction to Singular Spectrum Analysis</a></li><li><a href="https://ataspinar.com/2018/04/04/machine-learning-with-signal-processing-techniques/">Machine learning and signal processing techniques</a></li><li><a href="https://appliedaicourse.com/">Applied Ai course</a></li></ol><p><em>For any doubts, or queries, the readers may comment in the blog post itself, or connect with me on </em><a href="https://www.linkedin.com/in/sriram-pasupuleti/"><em>LinkedIn</em></a><em>.</em></p><p>You can find the code in <a href="https://github.com/sriram-pasupuleti/Battery_capacity_estimation">github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a51944953d86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Battery capacity estimation using Machine Learning : Part-1]]></title>
            <link>https://medium.com/@Sriram-P/battery-capacity-estimation-using-machine-learning-part-1-1347f3047324?source=rss-5883b9816e2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1347f3047324</guid>
            <dc:creator><![CDATA[R.A.M]]></dc:creator>
            <pubDate>Mon, 31 Jan 2022 17:05:58 GMT</pubDate>
            <atom:updated>2022-02-02T18:50:27.555Z</atom:updated>
            <content:encoded><![CDATA[<h3>Battery capacity estimation using Machine Learning : Part-1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6eJwmyAYn9Z4fhAP" /><figcaption>Photo by <a href="https://unsplash.com/@daniloalvesd?utm_source=medium&amp;utm_medium=referral">Danilo Alvesd</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Lithium ion cells are one of the most common compact energy storage solutions. Their applications range from smartphones and laptops to electric vehicles. It is natural for the Li-ion cells to lose their capacity to hold charge over time. Hence it is important to learn when the cell will meet its failure point so that it can be replaced at appropriate time and prevent device failures. Here, Machine learning techniques can be used to predict the cell capacity over its lifetime using various parameters during charging and discharging.</p><p>In this series of blogs, we will build a Machine Learning Case Study for predicting the capacity based on the charge-discharge cycle data. The series consists of 2 parts:</p><ul><li>Part-1 : Introduction ,Exploratory Data Analysis and Preprocessing</li><li>Part-2 : <a href="https://medium.com/@Sriram-P/battery-capacity-estimation-using-machine-learning-part-2-a51944953d86">Feature engineering, modeling and comparison</a></li></ul><p>This is the first part of the series in which we will cover the Overview of the problem, Exploratory Data Analysis and Preprocessing.</p><h3>Table of Contents</h3><ul><li>Business Problem</li><li>Dataset Overview</li><li>Performance Metrics</li><li>Exploratory Data Analysis</li><li>References</li></ul><h3>1. Business Problem</h3><p>Lithium ion batteries are prone to losing their capacity and lose charge overtime, which are dependent on many factors. There are traditional models that try to capture the nature of loss of capacity by using electrical and chemical properties. These methods are functional till some point but are not accurate due to complex chemical dynamics.Testing and verifying cells physically will involve manufacturing costs, equipment costs, testing costs and also chemical waste. This step can be almost completely avoided by using machine learning tools.</p><p>The properties of the cell changes as the cell loses its charge capacity. Some of the observable properties that change are the voltage, current, temperature and impedance during charging and discharging. These parameters can be recorded using easily accessible equipments and can be used to engineer features that can model the decay of capacity over time. The cell capacity can be predicted and also an estimate of the number of remaining cycles so that cells can be replaced in advance, preventing device failures.</p><h3>2. Dataset Overview</h3><p>The dataset taken for this study is from Nasa prognostics data repository(<a href="https://ti.arc.nasa.gov/tech/dash/groups/pcoe/prognostic-data-repository/#battery">Link</a>). The dataset contains information of four batteries under observation logged in the form of .mat files (MATLAB format). For this study, B0005 cell data is used. Top level of the cell contains a ‘Cycle’ structure. The cycle structure is a top level structure array containing the charge, discharge and impedance operations. The following information is taken from Readme.txt from the dataset which explains the data columns.</p><h4>Top level</h4><p><em>cycle</em>: top level structure array containing the charge, discharge and impedance operations</p><p><em>type</em>: operation type, can be charge, discharge or impedance</p><p><em>ambient_temperature</em>: ambient temperature (degree C)</p><p><em>time</em>: the date and time of the start of the cycle, in MATLAB date vector format</p><p><em>data</em>: data structure containing the measurements</p><h4>Fields in charge cycle:</h4><p><em>Voltage_measured</em>: Battery terminal voltage (Volts)</p><p><em>Current_measured</em>: Battery output current (Amps)</p><p><em>Temperature_measured</em>: Battery temperature (degree C)</p><p><em>Current_charge</em>: Current measured at charger (Amps)</p><p><em>Voltage_charge</em>: Voltage measured at charger (Volts)</p><p><em>Time</em>: Time vector for the cycle (secs)</p><h4>Fields in discharge cycles:</h4><p><em>Voltage_measured</em>: Battery terminal voltage (Volts)</p><p><em>Current_measured</em>: Battery output current (Amps)</p><p><em>Temperature_measured</em>: Battery temperature (degree C)</p><p><em>Current_charge</em>: Current measured at load (Amps)</p><p><em>Voltage_charge</em>: Voltage measured at load (Volts)</p><p><em>Time</em>: Time vector for the cycle (secs)</p><p><em>Capacity</em>: Battery capacity (Ahr) for discharge till 2.7V</p><h4>Fields in impedance cycles:</h4><p><em>Sense_current</em>: Current in sense branch (Amps)</p><p><em>Battery_current</em>: Current in battery branch (Amps)</p><p><em>Current_ratio</em>: Ratio of the above currents</p><p><em>Battery_impedance</em>: Battery impedance (Ohms) computed from raw data</p><p><em>Rectified_impedance</em>: Calibrated and smoothed battery impedance (Ohms)</p><p><em>Re</em>: Estimated electrolyte resistance (Ohms)</p><p><em>Rct</em>: Estimated charge transfer resistance (Ohms)</p><h3>3.Performance metrics</h3><p>In this problem, Models are used to predict the capacity(Ahr) of the battery after an ‘x’ amount of cycles given charge-discharge characteristics data. Hence this is a regression problem and the metrics that can be used for this are following:</p><ul><li><em>RMSE/MSE</em></li><li><em>MAE</em></li><li><em>MAPE</em></li><li><em>R-squared</em></li></ul><p>Among these, MAE gives us the average difference of predictions from actual values. Since the difference is absolute without any transformations as in RMSE, the output prediction, which is cell capacity, is more intuitive to grasp. Another requirement is that irrespective of the scale of the predictor variable, Regression model performance should be understandable when evaluation metrics are analyzed. a MAE value of 0.0034 does not make much sense unless the scale of the predictor variable is a prior knowledge. MAPE helps overcome this problem by providing a percentage error in prediction instead of error directly. The statement “Model predicts with 2% error” is intuitive and comparable to the statement “Model predicts with 0.0034 MAE”. Hence MAE and MAPE are suitable for this problem.</p><h3>4.Exploratory Data Analysis</h3><p>There are three types of cycles in the data, Charge, Discharge and Impedance. EDA should be done individually for each of the cycles as the properties are different for each of the cycle.</p><h4>4.1 Distribution of cycles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*QdXAlBhDFzySSETK" /><figcaption>Frequency of cycles</figcaption></figure><p>It can be observed that the frequency of impedance measurements in the cycle data is significantly higher than charge and discharge measurements. The number of charge cycles are 170 and discharge cycles are 168 which means that there are 2 charge cycles without the presence of consecutive discharge cycles.</p><h4>4.2 Number of observations in each cycle category</h4><p>Data that is logged for each cycle at a certain frequency called Sampling rate. For each type of cycle, different sampling rates are used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b63ee2978bd3688ed6266c5a4c9ee85d/href">https://medium.com/media/b63ee2978bd3688ed6266c5a4c9ee85d/href</a></iframe><p>The distributions are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*D0OOUrQr4byMT4Qf" /></figure><p>In charging cycles, the number of observations is as high as 4000 samples for a cycle. Some observations are very close to 5 observations as well,which is possibly an outlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*0Da9quoyiU5KxDWy" /></figure><p>In Discharge cycles, Majority number of datapoints are distributed near 300 observations which is a fairly good number of observations for extraction of useful observations. Lowest values lie close to 179 data points which is also sufficient for analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*ZIiMBVDqmnGmz6QE" /></figure><p>All of the impedance measurements are recorded with 48 data points. In percentile information for discharge cycle, the 25th percentile value is 300; the rest of the values are less than it, which is sufficient data.</p><h4>4.3 Outlier analysis:</h4><p><strong>Finding Outliers in logs of charge data</strong>: By comparing number of observations per cycle and highest values in ‘Time’ data for each cycle, outliers or improper logs can be identified. For charge cycles, the two states are as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f85825c25364427ee667bb554283ed9e/href">https://medium.com/media/f85825c25364427ee667bb554283ed9e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*3y3fpmx5Yuk5tsOC" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*OoMy4rrj5W8VFpY2" /></figure><p>There are a set of observations with lower sampling rate than others (less than 1000 observations per cycle). There is a strong dip in max values in 2 places which should be removed as they are not properly logged. The Number of observations having low sampling rate are 35 and observations having count less than 600 are 2 at indices 84 and 615 which are to be removed.</p><p><strong>Finding outliers in discharge data</strong>: Similar to charge cycles, the difference in sampling rate is analyzed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a32726b3542c049142ebb43369c5a5db/href">https://medium.com/media/a32726b3542c049142ebb43369c5a5db/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*4PRbv7pg4ZMOermg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*5Ejvg6JuXnzcQkBI" /></figure><p>In the number of samples plot, there is a drop in observations between 25 and 50 cycles. However, the difference in the observations from maximum values is relatively lower than the case in charge cycles. Even though there is a drop in the number of observations, the highest values for the corresponding observations are not abnormal. so by interpolation, the observations can be upsampled (or down sampled if needed).</p><h4>4.4 Individual cycle analysis : charge cycles</h4><p>Comparing the initial and final cycle of charging will give us insight into the variation of cell properties.</p><p><em>Single function to obtain the plots of each cycle category</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a33d157aef8f773ed52edb701720d54b/href">https://medium.com/media/a33d157aef8f773ed52edb701720d54b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*EMjKOlfJSnfSz8zP" /><figcaption>Cycle-1 vs Cycle-167</figcaption></figure><p>It can be observed that the cell in 167th cycle is staying in constant current mode for shorter duration and staying in constant current mode for longer duration than the cell at cycle 1.There is a trend of temperature increase as long as the battery stays in CC mode and then slowly decreasing as the mode shifts to CV mode.However, the temperature variation is present due to the addition of initial temperature in the system. This makes the assumption in the above point slightly weak.This initial temperature can be incorporated into the feature set along with max temp difference and also temperature decay rate. There are also some irregularities in the data (eg: voltage at the end of cycle 1). Current_charge and Voltage_charge can be ignored as they are reflections of Voltage_measured and Current_measured. 3D plots can be used to visualize how parameters are varying over time.</p><p><em>Function for 3D plots</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a5b27bada9bb6d39b45b082fb7c2af3/href">https://medium.com/media/1a5b27bada9bb6d39b45b082fb7c2af3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*I5-ODVFezrMGYm0G" /><figcaption>observations vs cycles vs magnitude of voltage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*rUJgOVNFxguFuUyg" /><figcaption>observations vs cycles vs magnitude of current</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*qSidVSfS2dvaYqf-" /><figcaption>observations vs cycles vs magnitude of temperature</figcaption></figure><p>From the above plots, it can be clearly observed that there is a shortage in initial cycle observations when compared to rest of observations. In previous plots, there were some data points which are less in length than other observation lengths, the same missing data is shown here clearly.</p><p>Resolving inconsistent sampling rate: 33 observations are sampled at lower rate than other observations, as a result, their lengths are lower than rest of the set which resulted in 3D plots with quicker change. This data should be upsampled with proper interpolation inorder to match overall observations. Interpolation is done to inflate and adjust the observations with lower sampling rate.</p><p>Interpolation method: It primarily iterates through ‘Time’ data of each cycle. one by one, the difference is calculated between current and previous time stamps, if the difference is more than ‘step’ argument, then interpolation is done, else skipped to consecutive time steps. Step argument is chosen based on length of data obtained after interpolation. This length is approximately compared to the rest of the data length to estimate proper step value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0502b945094ce055571a7f7fcd400c85/href">https://medium.com/media/0502b945094ce055571a7f7fcd400c85/href</a></iframe><p>Post interpolation, the observations are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*wd9Mpejmmp46fruQ" /><figcaption>observations vs cycles vs magnitude of voltage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*zEufCTfZbAZDRqD8" /><figcaption>observations vs cycles vs magnitude of current</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*kaEkFefQxwM569hU" /><figcaption>observations vs cycles vs magnitude of temperature</figcaption></figure><p>Prominent observation is current_measured, CC mode duration in fresh cells is higher than aged cells. A similar trend is present in voltage measured. In temperature measured, the rise in temperature as the battery exits CC mode is higher in aged cells than fresh cells. The cell reaches peak temperature faster in aged cells than fresh cells. Similar conclusions can be drawn from Voltage and current charge observations. The trends that are observed here can be further verified when features are extracted and analyzed with cell capacity for charging cycles.</p><h4>4.5 Individual cycle analysis : discharge cycles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*vKqc72lgEoEWAlXSo-PaQQ.png" /><figcaption>Cycle-1 vs Cycle-167</figcaption></figure><p>From the above figures, it is evident that a fresh cell can deliver more power than an aged cell. In voltage profiles, aged cell voltage falls rapidly than a fresh cell. It can also be observed that the peak temperature while discharging is significantly higher than a fresh cell. This was the case in multiple cycles, which could indicate the age of a cell properly. Current plots are constant as the discharge is done at 1.5A constantly. After load is removed, with remaining charge, voltage is recovered slightly which resulted in the increase of voltage after load current diminished</p><p>The recovered voltage seems to be slightly higher in aged cells than fresh cells. 3D plots can be plotted to understand how parameters are varying with cycles. If there is a problem with the number of observations, the above defined interpolation can be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*ylWOlffCxun10yF5" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*RFMr8wGiBdCgLteS" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*Uz7UzuuZBWzU94_N" /></figure><p>Resolving inconsistent sampling rate: Similar to the interpolation done in the charge cycles, discharge cycles are also interpolated with suitable step size. Post interpolation, the graphs of variation of parameters across time over all cycles recorded is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*thzOGgW6EBEPfgr9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*hSXJUrqd1J43YeR9" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/0*woVMwEujNcacmd8P" /></figure><p>After interpolating values, similar to charge 3D plots, there are also noticeable trends as the number of cycles increases. The prominent feature is Voltage, which is varying significantly as the number of cycles increases. Temperature is also increasing as cell ages in discharges, which is also correlated to voltage variations.</p><h4>4.6 Individual cycle analysis : Impedance</h4><p>The parameters in Impedance cycle logs are represented as sum of real and imaginary parts. Real and imaginary parts are plotted independently.</p><p><em>Since impedance is complex in nature, 3D plot function is modified</em></p><p><a href="https://gist.github.com/sriram-pasupuleti/673a881cf8250cfa889a7636c988a3f0">https://gist.github.com/sriram-pasupuleti/673a881cf8250cfa889a7636c988a3f</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3duOloWfXhZODB77" /><figcaption>Sense_current</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CpdpypvEaNby11uo" /><figcaption>Battery_current</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q3kin3NfoYyCf019" /><figcaption>Current_ratio</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YYtOGipkEPeK540_" /><figcaption>Battery_Impedance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZbbVxEWtff92fnkS" /><figcaption>Rectified_Impedance</figcaption></figure><p>The above plots are for all complex parameters of impedance. In sense_current, the real part is showing a slight tendency to increase as cycles increase. it is not consistent but there is a shift in increased real value. In the imaginary part, there is no such pattern present. Similar to sense_current, the real part of battery current is also decreasing as the cycle increases. There is no consistent pattern in the imaginary part. Current ratio is the ratio of sense current to battery current. In current_ratio, in both real and imaginary parts, there is a tendency to change values as cycles increase. Real part is showing more significant change than the imaginary part. As pointed above, rectified impedance is used directly instead of battery impedance. In battery impedance, there are the same, consistent values present in the first 21 cycles, which are possibly an error in measurement. In rectified impedance, the real portion is also showing a significant increase in magnitude as cycles increase, however, it needs smoothening as there are almost random sharp ridges and groves. In the imaginary part of rectified impedance, there is also a decrease in value as the cycles increase. However it is even more noisy at the end of cycles, making it difficult to utilize in feature extraction.</p><h4>4.7 Target variable — Capacity</h4><p>The target variable is capacity which is present in the discharge cycle data. Capacity is extracted and plotted to understand its characteristics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3089d5b9993b3530840b773a941c63ff/href">https://medium.com/media/3089d5b9993b3530840b773a941c63ff/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2FvQonivhMw5CIetc7_GQ.png" /><figcaption>variation of capacity over cycles</figcaption></figure><p>The capacity data is decreasing as the number of cycles increases i.e. over time, the cell is losing its capacity to hold charge which is as expected. There are some spikes which could be due to delay of charging in the testing stage. Even though the spikes exist, capacity quickly returns to reduced values. Since charge capacity is decreasing in nature, the feature plots are expected to be in correlation (+ve or -ve) with capacity.</p><p><strong>4.7.1 Change of capacity over time</strong></p><p>Since there is a constant decrease of capacity over time, the rate of change of capacity can be obtained to understand the characteristics of the cell. There are also sudden spikes which need to be verified whether they are logging errors or a variation due to external factors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36ca6b8923b6d194a453a42e674dd6cf/href">https://medium.com/media/36ca6b8923b6d194a453a42e674dd6cf/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gnyla-WNbsNCNeXQ7yrJAg.png" /></figure><p>Majority change is within -0.01 and 0.00. There are some values corresponding to sudden changes to the capacity, with highest differences. The indices for the highest differences are extracted using np.argsort().</p><pre>np.argsort(cap_diff)[::-1][:7].tolist()</pre><blockquote>Indices at spikes in capacity: [47, 30, 89, 19, 149, 118, 165]</blockquote><p><strong>4.7.2 Logging error or influence of external factors?</strong></p><p>Below plots are to understand if the capacity is influenced by external parameters or error in reading. In order to observe it, plots of pre and post cycles of anomaly indices are analysed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*K_X46duJ24dPtKEjHzqvig.png" /><figcaption>Cycle 46 vs 47</figcaption></figure><p>There are actual differences in the parameters of the cell which could have contributed to the change of cell capacity. Cycle data is also checked for the next set of cycle data i.e. 30.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*EXdlsBmp4LMQ-bC8ofoWIg.png" /><figcaption>Cycle 29 vs 30</figcaption></figure><p>For cycles 29 and 30, there is a clear difference between the two cycle parameters, mainly in the temperature. So the sudden capacity change is not a logging error but due to external factors.</p><p><strong>4.7.3 Average drop in capacity</strong></p><p>The average of the capacity difference calculated previously can be interpreted as the average rate of drop of capacity.</p><blockquote>Average drop of capacity : -0.0031820843842827653</blockquote><p>The average drop of capacity is around 0.0031 ah per cycle. So from the capacity of the first cycle, if 0.0031 is removed for every cycle, an average linear drop of the cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myjcIU1hhfg1a8zAryJzqw.png" /></figure><p>Till around cycle 65, the actual capacity is over the predicted capacity and from cycle 65, the drop of capacity is faster as cycles increase.</p><h4>4.8 Charge-Discharge cycle sequence analysis:</h4><p>There are 3 types of observations in data, Charge cycle, Discharge cycle and Impedance logs. These three types of cycles are not consistent in the data, some are irregularly present and some are not present for a certain duration. Below is an analysis on how various sequences are present and how they can be resolved into a common sequence. Observe the sequences below.</p><pre>types = [i[&#39;type&#39;] for i in B5]<br>print(&#39;Observe the sequences below&#39;)<br>print(&#39;Initial 10 cycles : &#39;,types[0:10], )<br>print(&#39;100 to 110 cycles : &#39;,types[100:110])</pre><blockquote><strong>Initial 10 cycles</strong> : [‘charge’, ‘discharge’, ‘charge’, ‘discharge’, ‘charge’, ‘discharge’, ‘charge’, ‘discharge’, ‘charge’, ‘discharge’]</blockquote><blockquote><strong>100 to 110 cycles</strong> : [‘discharge’, ‘impedance’, ‘charge’, ‘impedance’, ‘discharge’, ‘impedance’, ‘charge’, ‘impedance’, ‘discharge’, ‘impedance’]</blockquote><p>The Impedance observations are not present in the first 10 observations where as impedance is recorded after every charge as well as discharge cycle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce0f4c2525872cf358f2158a773ce5d3/href">https://medium.com/media/ce0f4c2525872cf358f2158a773ce5d3/href</a></iframe><blockquote>Sequences with charge-discharge: 30</blockquote><blockquote>Sequences with charge-impedance-discharge-impedance: 129</blockquote><blockquote>Length of data : 614</blockquote><p>There are 30 sequences with no data about impedance in those observations. In the remaining 129 sequences, there are impedance observations after charge and discharge cycles.</p><p>Including Impedance data along with charge and discharge across cycles is difficult as Impedance data is very irregularly logged. Here, we can see that 30 * 2 + 129 * 4 equals 576 which is not equal to the length of the ‘types’ list which is 616. This indicates that there are some observations where the sequences are not in the order of C-I-D-I</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/256bee0dde835b3935022c1f22d44451/href">https://medium.com/media/256bee0dde835b3935022c1f22d44451/href</a></iframe><blockquote>Length of Charge and Discharge list : 336</blockquote><blockquote>Anomaly at idx : 23</blockquote><blockquote>Anomaly at idx : 179</blockquote><blockquote>Final Sequence count : 166</blockquote><ul><li>There are 2 idxs where there are problems in sequences of charge and discharge, at 23 and at 179.</li></ul><pre>print(&#39;At id 23 : &#39;, c_d[22], c_d[23], c_d[24])<br>print(&#39;At id 179 : &#39;, c_d[178], c_d[179], c_d[180])</pre><blockquote>At id 23 : charge charge discharge</blockquote><blockquote>At id 179 : discharge discharge charge</blockquote><ul><li>As the above output, there are additional charge and discharge info without consecutive counterpart cycles.</li><li>For Charge, first instance of charge can be dropped and for discharge cycle, second instance of discharge can be dropped</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d32c388d786169f70d2c86ad0d57060/href">https://medium.com/media/8d32c388d786169f70d2c86ad0d57060/href</a></iframe><p>After this process, a data point of charge and consecutive discharge is considered as a single data point. Contents of discharge contain capacity but content of charge does not contain capacity which will make it difficult to analyze the charge data with dependent variables. So data restructure is needed for better analysis. The capacity of the battery in discharge data can be added to corresponding charge data or charge — discharge pairs should be combined to form a single data point. The former is chosen to retain the structure of original data.</p><p>This concludes the EDA of battery capacity estimation with machine learning. In This EDA, distributions are observed, outliers in the logs are removed for each type of cycles, inconsistent sampling rate is resolved, sequence analysis and data restructure is done.</p><h3>5. References</h3><ol><li><a href="https://www.researchgate.net/publication/333643175_Machine_Learning-Based_Lithium-Ion_Battery_Capacity_Estimation_Exploiting_Multi-Channel_Charging_Profiles">(PDF) Machine Learning-Based Lithium-Ion Battery Capacity Estimation Exploiting Multi-Channel Charging Profiles (researchgate.net)</a></li><li><a href="http://ssa.cf.ac.uk/ssa2010/a_brief_introduction_to_ssa.pdf">A Brief Introduction to Singular Spectrum Analysis</a></li><li><a href="https://ataspinar.com/2018/04/04/machine-learning-with-signal-processing-techniques/">Machine learning and signal processing techniques</a></li><li><a href="https://appliedaicourse.com/">Applied Ai course</a></li></ol><p><em>For any doubts, or queries, the readers may comment in the blog post itself, or connect with me on </em><a href="https://www.linkedin.com/in/sriram-pasupuleti/"><em>LinkedIn</em></a><em>.</em></p><p>You can find the code in <a href="https://github.com/sriram-pasupuleti/Battery_capacity_estimation/blob/master/EDA.ipynb">github</a>. Part-2 can be found <a href="https://medium.com/@Sriram-P/battery-capacity-estimation-using-machine-learning-part-2-a51944953d86">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1347f3047324" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>