<?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 Ashutosh Singh on Medium]]></title>
        <description><![CDATA[Stories by Ashutosh Singh on Medium]]></description>
        <link>https://medium.com/@ashutosh.singh.de?source=rss-b09e63fbaf3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hRVkbqs6BoDR4AVXvMU73A.jpeg</url>
            <title>Stories by Ashutosh Singh on Medium</title>
            <link>https://medium.com/@ashutosh.singh.de?source=rss-b09e63fbaf3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:20:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashutosh.singh.de/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[Iterative Closest Point algorithm. Nearest Neighbours and Point-to-Plane.]]></title>
            <link>https://medium.com/@ashutosh.singh.de/point-cloud-registration-iterative-closest-point-algorithm-25c11d1a20f7?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/25c11d1a20f7</guid>
            <category><![CDATA[linear-models]]></category>
            <category><![CDATA[iterative-closest-point]]></category>
            <category><![CDATA[3d-point-cloud]]></category>
            <category><![CDATA[point-cloud]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 22:10:41 GMT</pubDate>
            <atom:updated>2026-04-19T22:36:34.476Z</atom:updated>
            <content:encoded><![CDATA[<h3>ICP: Introduction</h3><p>Code: <a href="https://colab.research.google.com/drive/1H1Kg-a9G-doOjueXrAYoAUh0ivnywEjw?usp=sharing">https://colab.research.google.com/drive/1H1Kg-a9G-doOjueXrAYoAUh0ivnywEjw?usp=sharing</a></p><p>ICP(Iterative Closest Point) algorithm is one of the most famous algorithms to minimize or understand the differences between two point clouds. It’s often used for point cloud registration to merge multiple scans and also to estimate rigid transforms between them for building maps for robotic applications, due to is simplicity and effectiveness.</p><p>There are many variants of the ICP algorithm, but all of them can be decomposed into similar components, a target point cloud(acts as a reference), a source point cloud(which is to be transformed) and method to measure correspondences between source and target. There is also usually a step to filter outliers using RANSAC(or other methods).</p><p>We are going to start with one of the simplest implementations. In this implementation nearest neighbor of each point in the target(reference) point cloud in source point cloud will be used as correspondences.</p><p>ICP is an iterative algorithm where in each <strong><em>step</em></strong>, the point cloud alignment is performed and error is computed, if <strong><em>error</em></strong> is less than a predefined <strong><em>threshold</em></strong> the iteration is terminated otherwise the source point cloud is transformed and the iteration continues.</p><h3>Computing the error</h3><p>The <strong><em>error</em></strong> measure is used to terminate the ICP, for our implementation the <strong><em>error</em></strong> is measured as the mean of norm of distances between the target points and corresponding transformed source points, the equation can be seen in Figure-1.</p><h3>Estimating the relative transform</h3><p>The goal of ICP is to estimate the relative transform (rigid) between target and source point clouds. This transform is calculated by first establishing correspondences between the two sets of points. These correspondences are then used to estimate the relative transform.</p><p>The Rotation Matrix and translation vector are can be estimated using equations 1–4. The proof of this closed form solution is out of the scope for this blog and can be found in [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHoZZqoQrlu_2EbnMFWaNA.jpeg" /><figcaption>Figure-1: Equations for vanilla ICP. Error computation, and closed form transform estimation (1–4).</figcaption></figure><h3>Initializing the parameters</h3><p>The parameters to be estimated i.e. <strong>R</strong> and <strong>t </strong>have to be initialized for the first iteration of ICP. There are many possible ways to initialize these parameters and the choice usually depends on the knowledge of the use case at hand. However, a good starting point if initializing <strong>R</strong> as an identity matrix and <strong>t</strong> has the difference between coordinates of center of mass for target and source clouds.</p><pre>import numpy as np<br>import open3d import o3d<br><br># Read demo point clouds<br>demo_icp_pcds = o3d.data.DemoICPPointClouds()<br>source = o3d.io.read_point_cloud(demo_icp_pcds.paths[0])<br>target = o3d.io.read_point_cloud(demo_icp_pcds.paths[1])<br><br># Initialize R and identity and t as diff in mean coordinates<br>R = np.eye(3)<br>t = np.mean(np.asarray(target.points), axis=0) - np.mean(np.asarray(source.points), axis=0)</pre><h3>Writing the step function</h3><p>Let’s now write the step function which would return the error and estimated transform after each iteration of the algorithm. The error is computed at each step using a matching function. The step-function described next uses nearest neighbors to estimate the transform and corresponding error.</p><pre>def nearest_neighbour_matcher(source: PointCloud, target: PointCloud, **kwargs) -&gt; Tuple[float, NDArray]:<br>    source_correspondences, _ = find_nearest_neighbors(source_pc=source,<br>                                                        target_pc=target,<br>                                                        nearest_neigh_num=1)<br>    source_centroids = np.mean(source_correspondences, axis=0)<br>    centre_adjusted_source = source_correspondences - source_centroids<br><br>    # SVD to obtain closed form solution<br>    target_centroids = np.mean(np.asarray(target.points), axis=0)<br>    centre_adjusted_target = np.asarray(target.points) - target_centroids<br>    covariace_matrix = centre_adjusted_target.T @ centre_adjusted_source<br>    # My intuitive understanding is extracting the rotation <br>    # components of the covariance matrix, if the initial differences <br>    # are not very large the covariance matrix already reveals how related<br>    # the source and targets are. Now treating this matrix as an affine <br>    # transformation the rotation components from the SVD should be rotating <br>    # any input into a coordinate space where both source and target agree &quot;kind-of&quot;.<br>    # I may be wrong.<br>    U, X, V_T = np.linalg.svd(covariace_matrix)<br>    R = U @ V_T<br>    t = target_centroids - (R @ source_centroids)<br><br>    # No need for t in this error as target and soource are centre adjusted<br>    error = np.mean(np.linalg.norm(centre_adjusted_target - (R @ centre_adjusted_source.T).T, axis=0))<br><br>    transform = np.hstack((R, t.reshape((3, 1))))<br>    transform = np.vstack((transform, np.array([[0, 0, 0, 1]])))<br>    return error, transform</pre><p>The <em>find_nearest_neighbors </em>function is implemented as shown here.</p><pre>import open3d as o3d<br>from open3d.geometry import PointCloud<br><br>def find_nearest_neighbors(source_pc: PointCloud, target_pc: PointCloud, nearest_neigh_num: int):<br>    # Find the closest neighbor for each anchor point through KDTree<br>    point_cloud_tree = o3d.geometry.KDTreeFlann(source_pc)<br>    # Find nearest target_point neighbor index<br>    points_arr = []<br>    indices = []<br>    for point in target_pc.points:<br>        [_, idx, _] = point_cloud_tree.search_knn_vector_3d(point, nearest_neigh_num)<br>        points_arr.append(source_pc.points[idx[0]])<br>        indices.append(idx[0])<br>    return np.asarray(points_arr), np.array(indices)</pre><h3>Putting it all together</h3><p>The overall flow of the algorithm is described in the flowchart in Figure-2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtZ-rr1_I9VVWxU3fOufxQ.jpeg" /><figcaption>Figure-2: Overall flow for ICP algorithms.</figcaption></figure><p>The nearest neighbor method of finding correspondences gives us quite accurate results, however it’s prone to noise and uses too little information by doing one to one matching. Also the convergence is quite noisy and it may take a while to converge.</p><p>The natural next choice is to try to Point-to-Plane method which is more accurate and converges quicker than nearest neighbors(but each iteration is slower as compared to nearest neighbors).</p><h3>Point to plane ICP</h3><p>Point to plane ICP is another variant of ICP where instead of using nearest neighbors (point-to-point error) method the correspondences are established using a virtual plane at each source point and computing its distance from target (destination) point.</p><p>The point to plane ICP tries to minimize the error in Equation-4. As can be seen the matrix <strong><em>M </em></strong>has non-linearities and the equation is minimized using non-linear least-squares methods like the Levenberg–Marquardt method.</p><p>However if we know that the relative orientation is small enough the problem can be approximated to a linear least-squares optimization problem[2].</p><p>The step-function is now changed to the function detailed below.</p><pre>def linear_point_to_plane_matcher(source: PointCloud, target: PointCloud, **kwargs):<br>    # The algorithm used here and the linearity assumption is described here:<br>    # https://www.comp.nus.edu.sg/~lowkl/publications/lowk_point-to-plane_icp_techrep.pdf<br>    def linear_model(params, A, b):<br>        rx = params[&#39;rx&#39;]<br>        ry = params[&#39;ry&#39;]<br>        rz = params[&#39;rz&#39;]<br>        tx = params[&#39;tx&#39;]<br>        ty = params[&#39;ty&#39;]<br>        tz = params[&#39;tz&#39;]<br>        x = np.array([rx, ry, rz, tx, ty, tz])<br>        b_hat = np.dot(A, x)<br>        return b_hat - b<br><br>    def get_transform_matrix_from_params(fitted_params):<br>        # Rotations/translations along<br>        # x, y, z axes respectively.<br>        rx = fitted_params[&#39;rx&#39;].value<br>        ry = fitted_params[&#39;ry&#39;].value<br>        rz = fitted_params[&#39;rz&#39;].value<br>        tx = fitted_params[&#39;tx&#39;].value<br>        ty = fitted_params[&#39;ty&#39;].value<br>        tz = fitted_params[&#39;tz&#39;].value<br>        # For a small enough theta. sine(theta) approximated as theta<br>        # and cos(theta) as 1.<br>        T = [<br>                [  1  ,  rx*ry - rz  , rx*rz + ry  , tx  ],<br>                [  rz , rx*ry*rz + 1 , ry*rz - rx  , ty  ],<br>                [ -ry ,      rx      ,      1      , tz  ],<br>                [  0  ,       0      ,      0      ,  1  ]<br>            ]<br>        return T<br>    <br>    source.estimate_normals()<br>    source_points, indices = find_nearest_neighbors(source, target, nearest_neigh_num=1)<br>    normals = np.asarray(source.normals)[indices]<br><br>    # The intuition here is quite simple. Estimate a plane at target points<br>    # minimize the distance of this plane from corresponding source point.<br><br>    A = np.concatenate(<br>                        (<br>                            np.cross(source_points, normals),<br>                            normals<br>                        ),<br>                        axis=1<br>                      )<br>    b = np.sum((np.asarray(target.points) - source_points) * normals, axis=1)<br><br>    params = kwargs[&quot;params&quot;]<br>    min_result = lmfit.minimize(linear_model, params, args=(A, b,), method=&#39;least_squares&#39;)<br>    params = min_result.params<br>    params_arr = np.array([params[&quot;rx&quot;].value, params[&quot;ry&quot;].value, params[&quot;rz&quot;].value, params[&quot;tx&quot;].value, params[&quot;ty&quot;].value, params[&quot;tz&quot;].value])<br>    error = np.mean(np.square(np.dot(A, params_arr) - b))<br>    transform = get_transform_matrix_from_params(params)<br><br>    return error,  transform</pre><p>In Figure-3 the error from both variants of ICP are illustrated. The Point-to-Plane converged faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kk9Zo3crh9quTdlOeiwa4w.png" /><figcaption>Figure-3: Error from both nearest-neighbour and point-to-plane ICP against the number of iterations before loop exit.</figcaption></figure><p>All the methods and code described in the blog can be found <a href="https://colab.research.google.com/drive/1H1Kg-a9G-doOjueXrAYoAUh0ivnywEjw?usp=sharing">here</a>.</p><p>[1]: K. S. Arun, T. S. Huang and S. D. Blostein, “Least-Squares Fitting of Two 3-D Point Sets,” in <em>IEEE Transactions on Pattern Analysis and Machine Intelligence</em>, vol. PAMI-9, no. 5, pp. 698–700, Sept. 1987, doi: 10.1109/TPAMI.1987.4767965.</p><p>[2]: <a href="https://www.comp.nus.edu.sg/~lowkl/publications/lowk_point-to-plane_icp_techrep.pdf">https://www.comp.nus.edu.sg/~lowkl/publications/lowk_point-to-plane_icp_techrep.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25c11d1a20f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding KITTI dataset Part 2: 3D labels for objects.]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@ashutosh.singh.de/understanding-kitti-dataset-part-2-3d-labels-for-objects-e8c82de3bc2e?source=rss-b09e63fbaf3d------2"><img src="https://cdn-images-1.medium.com/max/1736/1*ttpt-U4eVAdx-yPS_oAU7A.png" width="1736"></a></p><p class="medium-feed-snippet">In Part-1 we introduced KITTI dataset briefly and went into details on projection matrices with a hands-on example of transforming point&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@ashutosh.singh.de/understanding-kitti-dataset-part-2-3d-labels-for-objects-e8c82de3bc2e?source=rss-b09e63fbaf3d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@ashutosh.singh.de/understanding-kitti-dataset-part-2-3d-labels-for-objects-e8c82de3bc2e?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8c82de3bc2e</guid>
            <category><![CDATA[3d-object-detection]]></category>
            <category><![CDATA[kitti-dataset]]></category>
            <category><![CDATA[3d-projections]]></category>
            <category><![CDATA[3d-computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sat, 29 Jun 2024 16:41:50 GMT</pubDate>
            <atom:updated>2024-06-29T16:41:50.005Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[RAG with AWS Sagemaker: Step-by-step guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@ashutosh.singh.de/rag-with-aws-sagemaker-step-by-step-guide-1ad970cc43f6?source=rss-b09e63fbaf3d------2"><img src="https://cdn-images-1.medium.com/max/1920/1*gyaM7GQEKQQW8YFHKkx1NQ.jpeg" width="1920"></a></p><p class="medium-feed-snippet">Step-by-step guide</p><p class="medium-feed-link"><a href="https://medium.com/@ashutosh.singh.de/rag-with-aws-sagemaker-step-by-step-guide-1ad970cc43f6?source=rss-b09e63fbaf3d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@ashutosh.singh.de/rag-with-aws-sagemaker-step-by-step-guide-1ad970cc43f6?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad970cc43f6</guid>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-generation]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 11:21:52 GMT</pubDate>
            <atom:updated>2024-03-24T11:44:33.584Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Understanding KITTI Dataset Part-1: Hands-on Projection Matrices]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@ashutosh.singh.de/understanding-kitti-dataset-part-1-hands-on-projection-matrices-4df2d84680a4?source=rss-b09e63fbaf3d------2"><img src="https://cdn-images-1.medium.com/max/1242/1*7aMT-pfm3PX1Yke75uoN5g.png" width="1242"></a></p><p class="medium-feed-snippet">Table of contents</p><p class="medium-feed-link"><a href="https://medium.com/@ashutosh.singh.de/understanding-kitti-dataset-part-1-hands-on-projection-matrices-4df2d84680a4?source=rss-b09e63fbaf3d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@ashutosh.singh.de/understanding-kitti-dataset-part-1-hands-on-projection-matrices-4df2d84680a4?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4df2d84680a4</guid>
            <category><![CDATA[data-fusion]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[kitti-dataset]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[autonomous-driving]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 11:32:22 GMT</pubDate>
            <atom:updated>2024-03-25T04:38:20.959Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Build your own video encoder with AWS Batch, EC2, Docker and ffmpeg: Part-2]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@ashutosh.singh.de/build-your-own-video-encoder-with-aws-batch-ec2-docker-and-ffmpeg-part-2-bc0102d022c5?source=rss-b09e63fbaf3d------2"><img src="https://cdn-images-1.medium.com/max/782/1*lBfGMuX9DK7ZjF_JCQgH6w.png" width="782"></a></p><p class="medium-feed-snippet">In Part-1 we setup the application structure we will be using for our encoder along with building and pushing the docker image to ECR.</p><p class="medium-feed-link"><a href="https://medium.com/@ashutosh.singh.de/build-your-own-video-encoder-with-aws-batch-ec2-docker-and-ffmpeg-part-2-bc0102d022c5?source=rss-b09e63fbaf3d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@ashutosh.singh.de/build-your-own-video-encoder-with-aws-batch-ec2-docker-and-ffmpeg-part-2-bc0102d022c5?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc0102d022c5</guid>
            <category><![CDATA[video-encoding]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 12:35:08 GMT</pubDate>
            <atom:updated>2024-03-18T12:35:08.966Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Build your own video encoder with AWS Batch, EC2, Docker and ffmpeg: Part-1]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@ashutosh.singh.de/build-your-own-video-encoder-with-aws-batch-ec2-docker-and-ffmpeg-part-1-54dc7f48cf05?source=rss-b09e63fbaf3d------2"><img src="https://cdn-images-1.medium.com/max/782/1*lBfGMuX9DK7ZjF_JCQgH6w.png" width="782"></a></p><p class="medium-feed-snippet">Part-1: Code and pre-requisites</p><p class="medium-feed-link"><a href="https://medium.com/@ashutosh.singh.de/build-your-own-video-encoder-with-aws-batch-ec2-docker-and-ffmpeg-part-1-54dc7f48cf05?source=rss-b09e63fbaf3d------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@ashutosh.singh.de/build-your-own-video-encoder-with-aws-batch-ec2-docker-and-ffmpeg-part-1-54dc7f48cf05?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/54dc7f48cf05</guid>
            <category><![CDATA[video-encoding]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 11:39:17 GMT</pubDate>
            <atom:updated>2024-03-18T12:35:46.193Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to? Quantize FPN backbones in torchvision]]></title>
            <link>https://medium.com/@ashutosh.singh.de/how-to-quantize-fpn-backbones-in-torchvision-6455b22dac04?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6455b22dac04</guid>
            <category><![CDATA[feature-pyramid-network]]></category>
            <category><![CDATA[faster-r-cnn]]></category>
            <category><![CDATA[resnet50]]></category>
            <category><![CDATA[model-quantization]]></category>
            <category><![CDATA[torchvision]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 21:06:14 GMT</pubDate>
            <atom:updated>2023-09-04T21:06:14.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*OedxRukEgjahTI3kYgktTg.gif" /><figcaption>Figure-1: Quantization illustration. Courtesy of <a href="https://www.qualcomm.com/news/onq/2019/03/heres-why-quantization-matters-ai">Qualcomm</a></figcaption></figure><p>Pytorch has great support for quantization, but sometimes some custom models have to be modified to support quantization. This can include replacing some ops or insertion of quant and dequant stubs at specific places in the model.</p><p>I was working on an object detection project and had already trained a Faster-RCNN model from torchvision with Resnet50 backbone.</p><p>I wanted to quantize this model but we soon figured out that the backbone with Feature Pyramid Network cannot be quantized with changes to the code. So I ended up changing up the code by identifying the places where the updates were needed and decided to write this blog.</p><p>Backbones with FPN in torchvision have two major components, the backbone and FPN, you can choose a quantizable backbone is torchvision if it is supported but once you create a BackboneWithFPN you need modifications and updates to make it work.</p><p>Let’s start with the steps that are required for successful quantization</p><ol><li>Model Preparation: This involves fusing modules, inserting Quantization/De-quantization stubs at places.</li><li>Model Calibration: Quantization requires some parameters like expected range and zero point information to be accurate. During calibration representative data(of real data) is passed through the model to activation and weight changes to compute these parameters.</li><li>Quantization: Final quantization to replace weights and kernels to quantized versions. <em>QuantStub</em> and <em>DeQuantStub</em> will be converted to <em>Quantize</em> and <em>DeQuantize</em> instances respectively.</li></ol><p>For more details about this refer to this great <a href="https://pytorch.org/blog/quantization-in-practice/">blog-post[1]</a> from pytorch.</p><p>The <em>BackboneWithFPN</em> in pytorch is composed of two modules the <em>FeaturePyramidNetwork</em> and <em>IntermediateLayerGetter</em> module. Check this code <a href="https://github.com/pytorch/vision/blob/1f94320d8db8d102214a7dc02c22fa65ee9ac58a/torchvision/models/detection/backbone_utils.py#L13-L60">here</a>.</p><p>We need to modify the <em>FeaturePyramidNetwork </em>mclass and change some stateless ops to stateful ops by using <em>torch.ao.nn.quantized.FloatFunctional().</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c243104ae128804e80ae5759a3c0f33/href">https://medium.com/media/0c243104ae128804e80ae5759a3c0f33/href</a></iframe><p>Here I replaced the stateless add operation with stateful add operation. Since this operation is stateful it has to be unique and hence one for each feature map.</p><p>To be able to use this implementation we need to modify <em>BackBoneWithFPN </em>as well a little bit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5791649b45a0475a3d7f7d5c5e49969b/href">https://medium.com/media/5791649b45a0475a3d7f7d5c5e49969b/href</a></iframe><p>Now that we have modified and created the respective modules we can go ahead with preparation of the FasterRCNN model for quantization.</p><p>I actually started with swapping backbones since my model was already trained. By swapping the backbones I was able to use quantizable modules if you already have trained using backbones created with these modules you can skip these steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4ee0eb2417c0001cd2cfe6e16f20f3d/href">https://medium.com/media/e4ee0eb2417c0001cd2cfe6e16f20f3d/href</a></iframe><p>Now all the ops in the backbone are quantizable and we can start with preparing model for quantization by inserting stubs and calibrating the fpn backbone.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/729b1e71c700d359c70a40a3fe47df65/href">https://medium.com/media/729b1e71c700d359c70a40a3fe47df65/href</a></iframe><p>Putting it all together in one method</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b9d5f323ce83e4030c58bdd6255bf9c/href">https://medium.com/media/8b9d5f323ce83e4030c58bdd6255bf9c/href</a></iframe><p>Pytorch also provides a numerical suite for measuring statistics for original(float) and quantized model. <a href="https://pytorch.org/tutorials/prototype/numeric_suite_tutorial.html">Here</a>[2] you can find a very nice tutorial by pytorch.</p><p>I measured the SNR values of weights for the original model and quantized model using the numerical suite and the results were quite good.</p><pre>1.body.conv1.weight tensor(40.8152)<br>1.body.layer1.0.conv1.weight tensor(39.4636)<br>1.body.layer1.0.conv2.weight tensor(38.1880)<br>1.body.layer1.0.conv3.weight tensor(41.0514)<br>1.body.layer1.0.downsample.0.weight tensor(40.5418)<br>1.body.layer1.1.conv1.weight tensor(41.1677)<br>1.body.layer1.1.conv2.weight tensor(39.0955)<br>1.body.layer1.1.conv3.weight tensor(42.1380)<br>1.body.layer1.2.conv1.weight tensor(41.4388)<br>1.body.layer1.2.conv2.weight tensor(39.7841)<br>1.body.layer1.2.conv3.weight tensor(43.6933)<br>1.body.layer2.0.conv1.weight tensor(40.3923)<br>1.body.layer2.0.conv2.weight tensor(41.2354)<br>1.body.layer2.0.conv3.weight tensor(41.3604)<br>1.body.layer2.0.downsample.0.weight tensor(39.0140)<br>1.body.layer2.1.conv1.weight tensor(38.6397)<br>1.body.layer2.1.conv2.weight tensor(38.6079)<br>1.body.layer2.1.conv3.weight tensor(41.2269)<br>1.body.layer2.2.conv1.weight tensor(39.6961)<br>1.body.layer2.2.conv2.weight tensor(39.7890)<br>1.body.layer2.2.conv3.weight tensor(41.9291)<br>1.body.layer2.3.conv1.weight tensor(41.0505)<br>1.body.layer2.3.conv2.weight tensor(41.2248)<br>1.body.layer2.3.conv3.weight tensor(42.6117)<br>1.body.layer3.0.conv1.weight tensor(40.2314)<br>1.body.layer3.0.conv2.weight tensor(40.8213)<br>1.body.layer3.0.conv3.weight tensor(41.8512)<br>1.body.layer3.0.downsample.0.weight tensor(41.1487)<br>1.body.layer3.1.conv1.weight tensor(39.6918)<br>1.body.layer3.1.conv2.weight tensor(40.2603)<br>1.body.layer3.1.conv3.weight tensor(41.4721)<br>1.body.layer3.2.conv1.weight tensor(40.2102)<br>1.body.layer3.2.conv2.weight tensor(40.9107)<br>1.body.layer3.2.conv3.weight tensor(42.3015)<br>1.body.layer3.3.conv1.weight tensor(40.6934)<br>1.body.layer3.3.conv2.weight tensor(41.1808)<br>1.body.layer3.3.conv3.weight tensor(42.1478)<br>1.body.layer3.4.conv1.weight tensor(41.0754)<br>1.body.layer3.4.conv2.weight tensor(41.0854)<br>1.body.layer3.4.conv3.weight tensor(42.4351)<br>1.body.layer3.5.conv1.weight tensor(41.3490)<br>1.body.layer3.5.conv2.weight tensor(41.0968)<br>1.body.layer3.5.conv3.weight tensor(42.5521)<br>1.body.layer4.0.conv1.weight tensor(41.2761)<br>1.body.layer4.0.conv2.weight tensor(40.9379)<br>1.body.layer4.0.conv3.weight tensor(41.9411)<br>1.body.layer4.0.downsample.0.weight tensor(41.3350)<br>1.body.layer4.1.conv1.weight tensor(39.9500)<br>1.body.layer4.1.conv2.weight tensor(40.0488)<br>1.body.layer4.1.conv3.weight tensor(42.0374)<br>1.body.layer4.2.conv1.weight tensor(40.0415)<br>1.body.layer4.2.conv2.weight tensor(38.4257)<br>1.body.layer4.2.conv3.weight tensor(41.1589)<br>1.fpn.inner_blocks.0.0.weight tensor(44.5333)<br>1.fpn.inner_blocks.1.0.weight tensor(42.9688)<br>1.fpn.inner_blocks.2.0.weight tensor(42.2766)<br>1.fpn.inner_blocks.3.0.weight tensor(41.1366)<br>1.fpn.layer_blocks.0.0.weight tensor(41.7108)<br>1.fpn.layer_blocks.1.0.weight tensor(41.5649)<br>1.fpn.layer_blocks.2.0.weight tensor(41.6138)<br>1.fpn.layer_blocks.3.0.weight tensor(41.6933)</pre><p>All of this was possible due to the beautiful developers of pytorch and torchvision. Even after training with normal resnet models I was able to replace it with a quantizable version.</p><p>The complete code and test cases can be found <a href="https://github.com/ashutoshsingh0223/quantizable_fpn">here</a>.</p><p><a href="https://github.com/ashutoshsingh0223/quantizable_fpn">GitHub - ashutoshsingh0223/quantizable_fpn: Modules for quantizable backbones with FPN</a></p><p>[1]: <a href="https://pytorch.org/blog/quantization-in-practice/">https://pytorch.org/blog/quantization-in-practice/</a></p><p>[2]: <a href="https://pytorch.org/tutorials/prototype/numeric_suite_tutorial.html">https://pytorch.org/tutorials/prototype/numeric_suite_tutorial.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6455b22dac04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Affective Computing using Deep Learning-Part 3: Latent Subgroups Analysis for MAHNOB-HCI]]></title>
            <link>https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-3-latent-subgroups-analysis-for-mahnob-hci-97271aaa79be?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/97271aaa79be</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[wasserstein]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[affective-computing]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 21:09:41 GMT</pubDate>
            <atom:updated>2024-01-02T22:10:05.827Z</atom:updated>
            <content:encoded><![CDATA[<p>Please make sure you read <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-1-mahnob-hci-dataset-analysis-b2161c306868">Part-</a>1 for exploratory analysis and intuitions from affective computing datasets and if you want to explore works around data-fusion in for affective computing using deep learning please read <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-2-data-fusion-introduction-and-literature-review-636266ad9bef">Part-2</a>.</p><p>The results of LOSO(Leave One Subject Out) evaluation did not look good during valence/arousal classification experiments; for both unimodal and fusion methods. The predictions had very high uncertainty[5]. We decided to explore the MAHNOB dataset for emotion classification a little more — first using simple handcrafted statistical features, and then with more advanced methods to study the characteristics of the dataset from high/low valence(arousal) and subject level behaviour perspective.</p><h3>Handcrafted statistical Features</h3><p>We use simple statistical features as described in [1] namely; max, min, mean, median, variance, difference between max and min values for original signal along with 1st and 2nd order difference of the signal as described in the Figure-1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TIUEdpW1wLdFuwSEx1Pvw.png" /><figcaption>Figure-1: Flow chat for this analysis. We use t-sne fit with `n_components=2`. Source Master Thesis presentation by Ashutosh Singh @ FAU Erlangen and Fraunhofer IIS,Erlangen.</figcaption></figure><p>The idea behind this analysis was to see if there is some difference between behaviour of these signals for baseline and stimilus periods(see <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-1-mahnob-hci-dataset-analysis-b2161c306868">Part-1</a>) and also the if different different stimuli(different videos) lead to some differences or not. These values can be used to see how these signals differ when presented with different type of stimuli(anger, disgust etc from preliminary emotion tags — see <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-1-mahnob-hci-dataset-analysis-b2161c306868">Part-1</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1VxgpG3K3kLEzVldH6BQw.png" /><figcaption>Figure-2: t-SNE visualisation of simple statistical features for Resp signal. ‘x’ marks are for baseline periods and ‘o’ if stimulus duration.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zn3HIgkYliOYwU9iKLvdw.png" /><figcaption>Figure-3: t-SNE visualisation of simple statistical features for GSR signal. ‘x’ marks are for baseline periods and ‘o’ if stimulus duration.</figcaption></figure><p>There aren’t any clusters visible between either baseline and stimulus period features or different emotion tags, see how ‘joy’ and ‘anger/sadness’ are spread out almost identically. These results show that these simple statistical features are not good enough for emotion classification, at-least for MAHNOB-HCI dataset.</p><h3>Latent Features from Unsupervised Learning</h3><p>To overcome the shortcomings of the handcrafted features, we decided to use Unsupervised Learning to model the data. The idea was we could then compare the distributions of signals from different stimuli to have some estimate of any significant difference between high/low valence samples for example.</p><p>Unsupervised learning(in this case) makes a lot of sense as MAHNOB-HCI dataset has emotions labels associated to a small fraction of trials as compared to the total number of trials.(See <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-1-mahnob-hci-dataset-analysis-b2161c306868">Part-1</a> for this breakdown), so we can possibly learn rich representations.</p><p>Self-Supervised learning may be better a approach if these representations are to be used for down-stream tasks, but we stick to unsupervised learning with VAE given our task of comparing distributions.</p><p>The generated latent representations <strong>z </strong>follow the distribution illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*9Ldalz1qdKahN9AW2yCtew.png" /></figure><p>Since the distribution is diagonal; meaning no covariance amongst dimensions in latent space, each dimension may be treated independently.</p><p>After generating latent representations from VAE we primarily use them for analysing subgroups in the dataset from the multiple perspectives. We wish to confirm the presence of any such subgroups from the perspective of stimuli, subjects and the self-rating for valence and arousal. Any dominant sub-groups(for example subject-level) which are conditionally independent of the class labels might explain co-variate shifts in classifier training data leading to unstable training and high uncertainty in predictions.The presence of such groups is identified using a distance metric between distributions of these groups. We use <em>Wasserstein Metric</em>[[2], [3]] to measure this distance.</p><blockquote>In short subgroups based on self-rating for valence and arousal should have larger distances(ideally) than any other groups in the dataset.</blockquote><p>We calculate this distance for each dimension in latent space(owing to diagonal distribution) to get a vector <strong>d</strong>. The final distance d is calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*SFKh26rUdTicnqXBIvFgOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgJTddMX2iJw1tNZCmRq6g.png" /><figcaption>Figure-4: Illustration of process used to calculate the distance between the groups.</figcaption></figure><p>In order to check of how inter-class distances for standard datasets look like , we also report wasserstein distance metric for MNIST Dataset[4] where <em>separate classes are treated as groups</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lbeUO4FNdb3UVktFR-oPA.png" /><figcaption>Figure-5: Wasserstein distances calculated for distributions of 10 classes of MNIST dataset with the method illustrated in Figure-4</figcaption></figure><p>The first observation to make here is how distribution of <em>class-0 </em>distribution is farthest from that of <em>class-1 </em>which is the digit that appears most unlike 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*4TRqq2hf99tiZ9h9HxWTqg.png" /><figcaption>Figure-6: Wasserstein distances between HV, LV, HA and LA subgroups. Groups were created based on nature of stimulus based on preliminary emotion tags where amusement, joy videos are treated as high valence and sadness fear and disgust videos as low valence stimuli.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*mnBlvokSFxJttRc8MwQAWQ.png" /><figcaption>Figure-7: Wasserstein distances between HV, LV, HA and LA subgroups. Groups were created based self-rating by the participants</figcaption></figure><p>The distances for MNIST dataset amongst different subgroups for MNIST is quite high as compared to that for MAHNOB-HCI dataset. However, MNIST is much simpler than MAHNOB, so the next question we had was — “Are the distances between High/Low Valence(or Arousal) are large enough?”</p><p>In context of MAHNOB-HCI we had an obvious of answering this question to certain extent — by using inter-subject variance.</p><blockquote>Again at this point I think it would interesting to try an approach where the feature representations are generated such that the loss especially tries to decrease these inter-subject distances while increasing the rating differences.</blockquote><p>We can repeat the same exercise of creating subgroups, but this time one group for each subject or participant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkY-VDbrQzmffemM4lT_hQ.png" /><figcaption>Figure-8: Distances between groups for each subject.</figcaption></figure><p>The mean value of inter-subject distances comes out to be <strong>0.0313 ± 0.009</strong> which is much larger than highest distances between both rating and stimuli nature based groups which are <strong>0.0069 and 0.0032</strong> respectively.</p><h3>Conclusion</h3><p>We hypothesise that <strong>high inter-subject differences as compared to rating based differences in the dataset might be causing the high uncertainty</strong> that we see in the classifier predictions during out experiments, fusion helps the performance a little but still the uncertainty is quite high to be able to evaluate the performance using LOSO.</p><p><strong>We also see this common trend of high accuracy results from publications that are not using LOSO.</strong></p><p>Unsupervised and Self-Supervised Learning can help a lot since MAHBOB-HCI dataset has a lot of samples with emotion labels. <strong>We can also skip LOSO and deal with this high inter-subject variance if we decide to look at the emotion recognition system as a personalised for each subject; fine-tuned for one specific person which maybe deployed on their smart-watch.</strong></p><p>[1]: Wei Wei, Qingxuan Jia, Yongli Feng, and Gang Chen. Emotion recognition based on weighted fusion strategy of multichannel physiological signals. <em>Comput Intell Neurosci</em>, 2018:5296523, July 2018.</p><p>[2]: L. N. Vaserstein. Markov Processes over Denumerable Products of Spaces, Describing Large Systems of Automata. <em>Probl. Peredachi Inf.</em>, 5:3, 1969.</p><p>[3]: Kantorovich LV. Mathematical methods of organizing and planning production. <em>Management Science. 6</em>, 6, 1939.</p><p>[4]: Li Deng. The mnist database of handwritten digit images for machine learning research. <em>IEEE Signal Processing Magazine</em>, 29(6):141–142, 2012.</p><p>[5]: <a href="https://ashutoshsingh0223.github.io/files/master-thesis-low-res.pdf">Master thesis — Ashutosh Singh @ Fraunhofer-IIS and University of Erlangen-Nuremberg</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97271aaa79be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Affective Computing Using Deep Learning-Part 2: Data Fusion, Introduction and Literature Review]]></title>
            <link>https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-2-data-fusion-introduction-and-literature-review-636266ad9bef?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/636266ad9bef</guid>
            <category><![CDATA[data-fusion]]></category>
            <category><![CDATA[emotion-recognition]]></category>
            <category><![CDATA[deep-leaning]]></category>
            <category><![CDATA[literature-review]]></category>
            <category><![CDATA[affective-computing]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 16:45:47 GMT</pubDate>
            <atom:updated>2024-01-02T22:07:09.123Z</atom:updated>
            <content:encoded><![CDATA[<p>Data fusion is the process combining data from multiple modalities with the goal of getting complimentary information from each modality to get more accurate representations, which are better than those provided by individual modalities for machine learning tasks like classification or regression. Fusion strategies are mainly grouped into three categories namely <em>Early Fusion</em>, <em>Intermediate Fusion</em> and <em>Late Fusion</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3Z6aW2peKgu_ZuW338vuA.png" /><figcaption>Figure: Illustrations for different fusion strategies. (a) Late Fusion, (b) Early Fusion,<br>(c) Intermediate Fusion. Functions represent parameterised models, red arrow<br>represents backpropagation during training. Source [1]</figcaption></figure><h3>Late Fusion</h3><p>Late fusion also known as decision fusion, is the process of combining decision made by the machine/deep learning model. For example in case of classification the probabilities of different classes may be averaged and normalised over all modalities, or some boosting techniques.</p><h3>Intermediate Fusion</h3><p>It is the process of combining intermediate representations from different modalities. These intermediate representations are learnt separately for every modality before the fusion step. A simple example is having different encoder for each modality and then fusing the representations from these encoders via some interaction. In this work we focus on intermediate fusion.</p><h3>Early Fusion</h3><p>Early fusion refers to the process of joining/combining multiple modalities together before feeding them to the machine/deep learning model. The modalities maybe combined in multiple ways for example, channel-wise concatenation of PSD based images.</p><h3>Deep Learning based Fusion for Affective Computing — Literature Review</h3><p>There have been a lot of works on data fusion for Affective Computing and Emotion Recognition . I am only listing down a few of them which I researched during the course of my thesis and found most interesting for my work. The common attribute is the use of deep learning and automatic feature extraction, instead of handcrafted features(many works in this direction as well.)</p><p><strong>DeepVANet: A Deep End-to-End Network for Multi-modal Emotion Recognition [2]</strong></p><ul><li>Fuse video and bio-signals at feature level.</li><li>Bio-Signals fused in an early fusion style as channels of 1D-Spatial signals.</li><li>1D-Convolutions and LSTM as modelling units.</li><li>Mention of per-subject evaluation — Similar to LOSO; Data leakage found on trial level.</li></ul><p><strong>Utilizing Deep Learning Towards Multi-modal Bio-sensing and Vision-based [3]</strong></p><ul><li>Results for individual modalities along with fusion results.</li><li>Use of pre-trained VGG-16 network to extract features from PSD images from EEG signals.</li><li>For ECG/PPG signals; the signals are converted in spectrograms and again a pre-trained VGG-16 is used to extract features.</li><li>Validation with 10-Fold Cross Validation with 80/20 split; LOSO not employed.</li></ul><p><strong>Deep Learning Method for Selecting Effective Models and Feature Groups in Emotion Recognition Using an Asian Multimodal Database[4]</strong></p><ul><li>Uses Genetic Algorithm for selecting models given the dataset.</li><li>LSTM model used for each EEG channel and simple concatenation of final LSTM outputs are fed to FCN.</li><li>LOSO not employed.</li><li>The authors got continuous emotional state tagging results from MAHNOB-HCI authors(This could be a good idea and might solve the problem of localisation of emotion that even I faced during my thesis)</li></ul><p><strong>Multimodal Emotion Recognition Using a Hierarchical Fusion Convolutional Neural Network [5]</strong></p><ul><li>Handcrafted features extracted from EEG and PPS(PPG, GSR, Resp Temp) individually.</li><li>The preprocessed EEG and PPS signals formed in a unified vector and then used as input for CNN to extract features.</li><li>Handcrafted features and convolutional features fused together with weighted fusion.</li><li>Random Forest as final classifier. LOSO not employed.</li></ul><p><strong>Automatic Emotion Recognition Using Temporal Multimodal Deep Learning [6]</strong></p><ul><li>EEG and BVP signals used.</li><li>Signals have individual CNN encoders followed by concatenation of CNN output at each time-step t. Author’s call this their Early Fusion</li><li>They also present an alternative where the modalities have individual CNN-LSTM encoders and the final output is concatenated for classification and this is represented as the late fusion in the paper.</li><li>Segments of length 10s proved to the best. LOSO employed but dataset other than MAHNOB-HCI.</li></ul><p><strong>CNN and LSTM-Based Emotion Charting Using Physiological Signals [7]</strong></p><ul><li>EEG preprocessed as 2D images and ECG and GSR used as 1D time series signals.</li><li>ECG and GSR processed using a 1D CNN-LSTM.</li><li>The final fusion is done as a Majority Vote Mechanism across ECG, EEG and GSR outputs.</li></ul><p>Make sure you read <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-1-mahnob-hci-dataset-analysis-b2161c306868">Part-1</a> for exploratory analysis and intuitions from affective computing datasets and <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-3-latent-subgroups-analysis-for-mahnob-hci-97271aaa79be">Part-3</a> for deeper latent analysis using Variational Encoders.</p><p>[1]: <a href="https://ashutoshsingh0223.github.io/files/master-thesis-low-res.pdf">Master thesis — Ashutosh Singh @ Fraunhofer-IIS and University of Erlangen-Nuremberg</a></p><p>[2]: Yuhao Zhang, Md Zakir Hossain, and Shafin Rahman. Deepvanet: A deep end-to- end network for multi-modal emotion recognition. In Carmelo Ardito, Rosa Lanzilotti, Alessio Malizia, Helen Petrie, Antonio Piccinno, Giuseppe Desolda, and Kori Inkpen, editors, <em>Human-Computer Interaction – INTERACT 2021</em>, Seiten 227–237, Cham, 2021. Springer International Publishing.</p><p>[3]: Siddharth, Tzyy-Ping Jung, and Terrence J. Sejnowski. Utilizing deep learning towards multi-modal bio-sensing and vision-based affective computing. <em>CoRR</em>, abs/1905.07039, 2019.</p><p>[4]: Jun-Ho Maeng, Dong-Hyun Kang, and Deok-Hwan Kim. Deep learning method for selecting effective models and feature groups in emotion recognition using an asian multimodal database. <em>Electronics</em>, 9(12), 2020.</p><p>[5]: Yong Zhang, Cheng Cheng, and Yidie Zhang. Multimodal emotion recognition using a hierarchical fusion convolutional neural network. <em>IEEE Access</em>, 9:7943–7951, 2021.</p><p>[6]: Bahareh Nakisa, Mohammad Naim Rastgoo, Andry Rakotonirainy, Frederic Maire, and Vinod Chandran. Automatic emotion recognition using temporal multimodal deep learning. <em>IEEE Access</em>, 8:225463–225474, 2020.</p><p>[7]: Muhammad Najam Dar, Muhammad Usman Akram, Sajid Gul Khawaja, and Amit N. Pujari. Cnn and lstm-based emotion charting using physiological signals. <em>Sensors</em>, 20(16), 2020.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=636266ad9bef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Affective Computing using Deep Learning-Part 1: MAHNOB-HCI dataset analysis]]></title>
            <link>https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-1-mahnob-hci-dataset-analysis-b2161c306868?source=rss-b09e63fbaf3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2161c306868</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[data-fusion]]></category>
            <category><![CDATA[emotion-recognition]]></category>
            <category><![CDATA[mahnob-hci]]></category>
            <dc:creator><![CDATA[Ashutosh Singh]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 16:42:23 GMT</pubDate>
            <atom:updated>2024-01-02T22:05:10.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of contents</h3><ol><li><a href="#132b">Introduction</a></li><li><a href="#430d">MAHNOB-HCI dataset</a></li><li><a href="#ae40">Stimuli</a></li><li><a href="#70e3">Emotion Recognition problem</a></li><li><a href="#ffb5">Visualising raw signals</a></li><li><a href="#5067">Final Remarks</a></li></ol><h3>1. Introduction</h3><p>Affective computing is a multidisciplinary field that involves the research and advancement of systems and devices capable of identifying, understanding, analyzing, and replicating human emotions. This field combines elements from computer science, psychology, and cognitive science.<br>Emotion detection research is becoming very popular due to wide range of applications. Human emotions are very complex and are reflected completely/partially in multiple types of signals like facial expressions, heart rate, body temperature, brain function etc. Current datasets available for emotion detection generally contain these signals in form of multiple modalities like Facial Video/Audio, ECG, Galvanic Skin Response(GSR), Respiration Amplitude, Eye Gaze Tracking data and Electroencephalogram(EEG). While each of these modalities plays an important role in human emotion detection some of the signals are more difficult and expensive to record than others.<br>There are multiple ways to formulate the problem of emotion classification such as classifying between discrete emotions like joy, anger, sadness, disgust etc. or using a dimensional model for emotions and associating each emotion to a point in this space. There are multiple dimensional models for emotions, most of these models use <em>Valence</em> and <em>Arousal</em> dimensions and all emotions can be represented in this 2-Dimensional Space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*hVw2yD1ymJ2qjNiTNPxmpQ.png" /><figcaption>Figure 1: Valence(negative/positive) and Arousal(low/high) as the two dimensions of emotions[1]</figcaption></figure><p>Valence and Arousal values for MAHNOB-HCI dataset are lie in {1, 9}.</p><h3>2. MAHNOB-HCI Dataset</h3><p>MAHNOB-HCI dataset[2], where HCI stands for Human Computer Interaction, is a very commonly used dataset for emotion or valence/arousal classification. The dataset itself is a combination of 2 experiments where some test subjects(humans) are given some form of stimuli(videos and images) and then they are asked to rate their emotional state on a discrete scale of 1–9 for valence and arousal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2ew2YP45ItKooyJaqP6Dw.png" /><figcaption>Figure 2: Summary of MAHNOB-HCI dataset experiments[2].</figcaption></figure><p>The two types of experiments are illustrated in the figures below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hmnDhbEJ6QC5HLduJYsKJw.png" /><figcaption>Figure 3: Setup for experiment type 1. Subject’s baseline is recorded and then provided with stimuli to elicit emotion and then asked to rate his valence/arousal on a scale of 1–9[3]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*LjZY4tTzawJjiFC_TGDa_A.png" /><figcaption>Figure 4: Setup for experiment type 2. Subject’s baseline is recorded and then provided with an image with a textual prompt on the image. Then subject is asked whether they agree or disagree with the tag given the image. This is just an example and not from real dataset[3]</figcaption></figure><p>Multiple bio-signals are collected in the MAHNOB-HCI dataset. Below is a list of signals that will be used for valence-arousal detection in this study. We will refer to these signals by the acronyms of their names as specified in the first column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*JPkzzPA_-9KTDfy1c4TCNQ.png" /><figcaption>Table 2: List of physiological signals recorded in MAHNOB-HCI dataset</figcaption></figure><h3>3. Stimuli</h3><p>Now let’s dive a little deeper into the dataset, starting with the stimuli. MAHNOB-HCI dataset employs videos(and images) as stimuli to elicit emotional response from the participants.The emotion elicitation experiment contains 20 video clips which were selected from multiple commercially produced movies. The authors did a preliminary online study to get emotion tags corresponding to each video clip where each clip received at least 10 annotations from over 50 participants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r08EULAJ7JyeS0rxuAOD_A.png" /><figcaption>Figure : Video Stimuli and corresponding emotion(as surveyed from preliminary study)[3]</figcaption></figure><p>Now let’s see how the subjects rated the stimuli video clips and what the median rating was for each one of them, for valence and arousal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOdf3KXF87sv-1NGpqXlJg.png" /><figcaption>Figure : Valence(left) and Arousal(right) ratings for each stimulus.The size of the dots is proportional to number votes for given rating i.e if more subjects rate 5 it’s represented by a bigger dot. Source [3]</figcaption></figure><p>The visualisations presented below confirm that in most cases majority<br>of participants agree on a given rating for both Arousal and Valence; however there are quite significant differences as well. For example in case of valence we see much more significant spread of for some clips like <em>earworm_f.avi</em>. Arousal ratings are much more spread out than<br>valence, even for high arousal stimuli like <strong>joy</strong>(<em>79.avi, 80.avi</em> and <em>90.avi</em>).</p><h3>4. Emotion Recognition problem</h3><p>Since the rating scale of Valance/Arousal is discrete it’s quite counterintuitive to model the problem of emotion recognition as a regression problem, when using MAHNOB-HCI. So we can consider this problem as a classification problem.</p><p>Next problem is since we have very small number of trials available, classifying between 9 classes might be too difficult(also considering the imbalance in dataset) but we can formulate the problem as a coarse problem of binary classification for valence and arousal by transforming rating scale to 0–1 from 1–9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*E03lraZOw1UYV_ZzQi2gGw.png" /><figcaption>Figure : Coarser discretisation of 9 point rating scale to 0–1 or Low/High scale[3]</figcaption></figure><p>The problem is not exactly solved yet, there is some trade-off involved in the decision of whether to chose 5 has high or low as it is the most frequent rating in dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*Q3ysLnh_xIWzzLny8cxQ6Q.png" /><figcaption>Figure : Variation of Valence with Arousal. Large number of samples have a rating of 5 which leads to large bias if 5 is treated as LA/LV[3]</figcaption></figure><p>The figure below shows the class balance in data coming from media with preliminary emotion tags of <strong>Sadness</strong>, <strong>Joy</strong> and <strong>Neutral</strong>. We present these distributions for both thresholds of 4.5 and 5.5. We can see the trade-off in class distribution based on value of threshold, for example for preliminary tag <strong>sadness</strong> the number of high valence samples decreases as we go from threshold of 4.5 to 5.5, which is expected. However for <strong>joy </strong>, number of samples in high valence class samples also decreases which is undesired, a solution to this problem could be <em>different thresholds for different stimuli.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rKfQf1POZ1Ze8wQN3zQFQw.png" /><figcaption>Figure: Distribution of High/Low Valence samples for preliminary tags of sadness(Low Valence), Joy(High Valence) and Neutral for (a) threshold = 4.5 and (b) threshold = 5.5. Source [3]</figcaption></figure><p>In my experiments I chose the threshold of 4.5 for all experiments.</p><h3>5. Visualising raw signals</h3><p>Finally we can visualise some raw signals from different modalities like Skin Temperature and GSR etc. for different subjects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oK9bi3GHDcoeBu7v1Eudrw.png" /><figcaption>Figure :Skin temperatures for different kinds of stimuli provided and the corresponding rating received for subject 11. The vertical blue line separates the baseline period from actual stimulus period. Source [3]</figcaption></figure><p>It’s clearly visible from the figure above that the skin temperature is not in normal range for subject-11 which might be due to the temperature sensor placement. Looking at the same results for subject-10 we see the baseline temperatures are higher than those in stimulus period, which becomes a problem when baseline period is ignored when detecting the emotional state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*diiv3w42CxVxSH4uxM5jgA.png" /><figcaption>Skin temperatures for different kinds of stimuli provided and the corresponding rating received for subject 10. Source [3].</figcaption></figure><p>I will also show GSR and Respiration results just for completion but it is not possible(we can speculate though:)) to derive any such insights directly from those signals since unlike temperature their rate of variation is a little faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*W3fqAmeo-1Ex4YPpZpCSOw.png" /><figcaption>Figure : GSR signals for multiple stimulus from different baseline emotions for subjects 9 and 10. The vertical line marks end of baseline. The legends have stimulus name along with preliminary emotion associated and the arousal/valence ratings given. Source [3]</figcaption></figure><p>If you see the response to <em>111.avi </em>for subject-17, we see almost no response. This is quite common in MAHNOB-HCI dataset, the subject-level variations which require a more deeper analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECMF8luFXjZDynEaES9qYQ.png" /><figcaption>Figure : Resp signal — Frequency Spectrum, Signals with trend removed and raw signals(left to right) for subject-17</figcaption></figure><p>The signals seem quite similar except for large variations here and there which might be an artefact of gasping or laughing(which can be verified by looking at the recorded participant video).</p><h3>6. Final Remarks</h3><p>MAHNOB-HCI dataset is not an easy dataset to run analysis and derive insights from, there is a strong variance of reactions to a stimuli among different subjects. Even if there seems to be a consensus between valence and arousal ratings, the perceived scale of these ratings varies a lot for different subjects which is evident from their physiological signals. For example: I might be very joyful and give a valence rating of only 5 given what I perceive as the most joyful I have ever been.</p><p>The dataset is also quite noisy, I found number of trials where the ECG signals have a lot of sensor noise. So before doing any analysis a lot of cleaning up might be required.</p><p>Temperature does not seem to be representative of the stimulus, which we see in the raw temperature signals.</p><p>Proceed to <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-2-data-fusion-introduction-and-literature-review-636266ad9bef">part-2</a> for a literature review of Data Fusion in Affective Computing in context of deep-learning. <a href="https://medium.com/@ashutosh.singh.de/affective-computing-using-deep-learning-part-3-latent-subgroups-analysis-for-mahnob-hci-97271aaa79be">Part-3</a> for a deeper analysis on MAHNOB.</p><p>[1]: Enrique Munoz-De-Escalona and Jos´e Canas. Online measuring of available resources.</p><p>[2]: Mohammad Soleymani, Jeroen Lichtenauer, Thierry Pun, and Maja Pantic. A multimodal database for affect recognition and implicit tagging. IEEE Trans. Affect. Comput., 3(1):42–55, jan 2012.</p><p>[3]: <a href="https://ashutoshsingh0223.github.io/files/master-thesis-low-res.pdf">Master thesis - Ashutosh Singh @ Fraunhofer-IIS and University of Erlangen-Nuremberg</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2161c306868" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>