<?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 Hajar Zoubir on Medium]]></title>
        <description><![CDATA[Stories by Hajar Zoubir on Medium]]></description>
        <link>https://medium.com/@zoubirhajar?source=rss-80f1ec05fb9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l14Me_6ACS9z9d_zUUGLhQ.jpeg</url>
            <title>Stories by Hajar Zoubir on Medium</title>
            <link>https://medium.com/@zoubirhajar?source=rss-80f1ec05fb9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:12:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zoubirhajar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A step-by-step guide to write a research paper in Civil Engineering and AI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@zoubirhajar/a-step-by-step-guide-to-write-a-research-paper-in-civil-engineering-and-ai-fde9cb29049e?source=rss-80f1ec05fb9b------2"><img src="https://cdn-images-1.medium.com/max/600/1*NPGyaw2FNWXc3emK5G7luA.png" width="600"></a></p><p class="medium-feed-snippet">Writing a research paper in civil engineering and artificial intelligence requires expertise in both fields and a careful balance in&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@zoubirhajar/a-step-by-step-guide-to-write-a-research-paper-in-civil-engineering-and-ai-fde9cb29049e?source=rss-80f1ec05fb9b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@zoubirhajar/a-step-by-step-guide-to-write-a-research-paper-in-civil-engineering-and-ai-fde9cb29049e?source=rss-80f1ec05fb9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde9cb29049e</guid>
            <category><![CDATA[phd]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[academia]]></category>
            <category><![CDATA[research-paper-writing]]></category>
            <category><![CDATA[civil-engineering]]></category>
            <dc:creator><![CDATA[Hajar Zoubir]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 13:25:19 GMT</pubDate>
            <atom:updated>2024-12-24T13:34:28.297Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Find your datasets for your research in Civil Engineering and AI — Numerical data]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@zoubirhajar/find-your-datasets-for-your-research-in-civil-engineering-and-ai-numerical-data-0525e80ee1f4?source=rss-80f1ec05fb9b------2"><img src="https://cdn-images-1.medium.com/max/2600/1*UPN90siedSjZa6Qf1QCfCQ.jpeg" width="6240"></a></p><p class="medium-feed-snippet">Whether you are applying AI models to analyze structural behaviour, build predictive models or simulating traffic flow, numerical datasets&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@zoubirhajar/find-your-datasets-for-your-research-in-civil-engineering-and-ai-numerical-data-0525e80ee1f4?source=rss-80f1ec05fb9b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@zoubirhajar/find-your-datasets-for-your-research-in-civil-engineering-and-ai-numerical-data-0525e80ee1f4?source=rss-80f1ec05fb9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0525e80ee1f4</guid>
            <category><![CDATA[civil-engineering]]></category>
            <category><![CDATA[research-paper]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[academia]]></category>
            <category><![CDATA[datasets-for-ml]]></category>
            <dc:creator><![CDATA[Hajar Zoubir]]></dc:creator>
            <pubDate>Thu, 28 Nov 2024 11:37:53 GMT</pubDate>
            <atom:updated>2024-11-28T11:49:46.171Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Find your dataset for your research in Civil Engineering and AI — Visual data]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@zoubirhajar/find-your-dataset-for-your-research-in-civil-engineering-and-ai-visual-data-99e48926b171?source=rss-80f1ec05fb9b------2"><img src="https://cdn-images-1.medium.com/max/749/1*P7cuNxyCDedMMxco6su0Tw.png" width="749"></a></p><p class="medium-feed-snippet">Images and videos are the lifeblood of computer vision models (e.g. Convolutional Neural Networks). Related applications in civil&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@zoubirhajar/find-your-dataset-for-your-research-in-civil-engineering-and-ai-visual-data-99e48926b171?source=rss-80f1ec05fb9b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@zoubirhajar/find-your-dataset-for-your-research-in-civil-engineering-and-ai-visual-data-99e48926b171?source=rss-80f1ec05fb9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/99e48926b171</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[visual-data]]></category>
            <category><![CDATA[civil-engineering]]></category>
            <category><![CDATA[datasets-for-ml]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hajar Zoubir]]></dc:creator>
            <pubDate>Tue, 05 Nov 2024 11:25:09 GMT</pubDate>
            <atom:updated>2024-12-27T08:30:34.140Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Write a solid literature review for your research paper in Civil Engineering and AI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@zoubirhajar/write-a-solid-literature-review-for-your-research-paper-in-civil-engineering-and-ai-b1fbf3edb0f3?source=rss-80f1ec05fb9b------2"><img src="https://cdn-images-1.medium.com/max/2600/1*VtsYYQenkvrV-r4bH0O2Hg.jpeg" width="5329"></a></p><p class="medium-feed-snippet">Are you working on a research paper combining Civil Engineering and AI&#xA0;? Your literature review plays a critical role in uniting these&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@zoubirhajar/write-a-solid-literature-review-for-your-research-paper-in-civil-engineering-and-ai-b1fbf3edb0f3?source=rss-80f1ec05fb9b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@zoubirhajar/write-a-solid-literature-review-for-your-research-paper-in-civil-engineering-and-ai-b1fbf3edb0f3?source=rss-80f1ec05fb9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1fbf3edb0f3</guid>
            <category><![CDATA[phd]]></category>
            <category><![CDATA[literature-review]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[civil-engineering]]></category>
            <category><![CDATA[paper]]></category>
            <dc:creator><![CDATA[Hajar Zoubir]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 10:15:37 GMT</pubDate>
            <atom:updated>2024-10-18T08:57:51.864Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Launch your Research in Civil Engineering and AI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@zoubirhajar/launch-your-research-in-civil-engineering-and-ai-198289b4eda1?source=rss-80f1ec05fb9b------2"><img src="https://cdn-images-1.medium.com/max/2600/1*G800SK0IkkLX_Qn1kJDdFg.jpeg" width="3468"></a></p><p class="medium-feed-snippet">Akashi-Kaikyou Bridge in Japan (Photo by author)</p><p class="medium-feed-link"><a href="https://medium.com/@zoubirhajar/launch-your-research-in-civil-engineering-and-ai-198289b4eda1?source=rss-80f1ec05fb9b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@zoubirhajar/launch-your-research-in-civil-engineering-and-ai-198289b4eda1?source=rss-80f1ec05fb9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/198289b4eda1</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[civil-engineering]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificalintelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hajar Zoubir]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 10:51:22 GMT</pubDate>
            <atom:updated>2024-10-25T11:05:03.806Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Road infrastructure, ML and DL…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@zoubirhajar/road-infrastructure-ml-and-dl-ea849cda774d?source=rss-80f1ec05fb9b------2"><img src="https://cdn-images-1.medium.com/max/2600/1*-_p5z5lewMvVU2xqbn61Cg.jpeg" width="3992"></a></p><p class="medium-feed-snippet">Image uploaded from Unsplash (link)</p><p class="medium-feed-link"><a href="https://medium.com/@zoubirhajar/road-infrastructure-ml-and-dl-ea849cda774d?source=rss-80f1ec05fb9b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@zoubirhajar/road-infrastructure-ml-and-dl-ea849cda774d?source=rss-80f1ec05fb9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea849cda774d</guid>
            <category><![CDATA[civil-engineering]]></category>
            <category><![CDATA[articial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Hajar Zoubir]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 16:37:18 GMT</pubDate>
            <atom:updated>2024-10-25T11:07:01.547Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Identifying cracks in concrete bridge images using edge detection techniques]]></title>
            <link>https://medium.com/@zoubirhajar/identifying-cracks-in-concrete-bridge-images-using-edge-detection-techniques-219020defaef?source=rss-80f1ec05fb9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/219020defaef</guid>
            <category><![CDATA[concrete]]></category>
            <category><![CDATA[crack]]></category>
            <category><![CDATA[inspection]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[bridge]]></category>
            <dc:creator><![CDATA[Hajar Zoubir]]></dc:creator>
            <pubDate>Thu, 05 May 2022 23:51:47 GMT</pubDate>
            <atom:updated>2022-05-17T13:47:34.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*u51OOntDk_8XCm5vGjbkog.jpeg" /><figcaption>Sobel masks applied to an RGB image (original RGB image taken by author)</figcaption></figure><p>In <a href="https://medium.com/@zoubirhajar/cnn-based-classification-applied-to-concrete-bridge-crack-images-6ae4731b638a">my previous post</a>, I used the pre-trained VGG16 model and Transfer Learning to classify concrete crack images I extracted from <a href="https://www.matec-conferences.org/articles/matecconf/abs/2021/18/matecconf_iceaf2021_03014/matecconf_iceaf2021_03014.html">this dataset</a>.</p><p>Although my current work is more focused on Convolutional Neural Networks (CNNs), I thought it would practical to discuss some Image Processing Techniques that have been widely explored in the computer vision literature to detect cracks in images. In this post, I will apply two edge detection techniques to identify cracks in concrete bridge images.</p><p><strong>What is an image?</strong></p><p>Images are mathematically represented by pixel matrices arranged in rows and columns: one matrix for grayscale images and three matrices for RGB (Red, Green, and Blue) images.</p><p>Each pixel has an intensity ranging from 0 to 255.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*nxJJC6xlp39kLohIOu9PtA.png" /><figcaption>Pixel intensity values of a Grayscale image (<a href="https://mozanunal.com/2019/11/img2sh/">Source</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*mWYZB6TJ_NaqHKE7DuswYA.jpeg" /><figcaption>RGB image and its split channels: Red channel(left), Green channel(middle), and Blue channel (right)</figcaption></figure><p><strong>Edge detectors</strong></p><p>Edges in an image correspond to discontinuities and sharp changes in pixel intensity. They represent important features to analyze objects in an image.</p><p>They can be detected by applying filters in the spatial domain (e.g. Sobel, Canny, Prewitt) or frequency domain (e.g. Fast Haar Transform).</p><p>Since cracks in a digital image are classified as edges, I will apply in this post two popular edge detectors (i.e. Sobel and Canny) to concrete crack images.</p><p>Before that, how do these edge detectors work?</p><p>Well, both techniques use image gradient for edge detection. The gradient vector is computed at each pixel of the 2D image, its magnitude (G) measures the strength of the edge and its direction (Ɵ) points to the maximum increase of intensity.</p><p>To approximate image gradient, images are convolved with horizontal and vertical filters to compute the derivatives in the x and y directions (Gx and Gy, respectively).</p><pre>G= sqrt(G²x+G²y)<br>Ɵ = arctan(Gy/Gx)</pre><p>The Sobel edge detector is known for its simplicity. It uses two 3x3 convolution masks to compute Gx and Gy :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FC64LFR-eCgjgxS0xw_guw.png" /><figcaption>Sobel masks (image taken from <a href="https://www.projectrhea.org/rhea/index.php/An_Implementation_of_Sobel_Edge_Detection">here</a>)</figcaption></figure><p>After applying these masks to the image, the two filter results are added together to provide an accurate representation of all the edges in the image (in X and Y directions).</p><p>The Canny edge detector uses a multi-stage algorithm to identify edges. It also applies convolution filters (e.g. Sobel, Prewitt) to the image, but it first smoothes it using a Gaussian filter to reduce noise. Then, the algorithm attempts to find edges based on the gradient magnitude and its direction at each pixel in the smoothed image. A double threshold is applied to determine the pixels belonging to an edge.</p><p>More explanations and details about the Canny edge detector and its implementation can be found <a href="https://medium.com/towards-data-science/canny-edge-detection-step-by-step-in-python-computer-vision-b49c3a2d8123">here.</a></p><p><strong>Concrete crack detection</strong></p><p>I am using the OpenCV library to apply the Canny and Sobel edge detectors on sample crack images from the dataset I built in <a href="https://medium.com/@zoubirhajar/cnn-based-classification-applied-to-concrete-bridge-crack-images-6ae4731b638a">my previous post</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*fR_hvyzCDz09WrvhMD0zdQ.jpeg" /></figure><p>It is clear that both edge detectors are susceptible to image noise, particularly Sobel, but they are still capable of highlighting cracks in the images and Canny provided a better representation of the existing cracks.</p><p>However, the examples above don’t entirely cover the real-world bridge inspection conditions (strong light, shadow, complex concrete texture, presence of stains, markings…) that are likely to make the crack detection task more challenging.</p><p>Now, let’s see how these edge detectors perform in more complex situations :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*K4cLfZ9_Cc7IQNUewV9lyg.jpeg" /></figure><p>The image on the left represents scaling concrete with a complex texture and both edge detectors failed to detect the crack in the image. In the two remaining images, the boundary between shadow and light (middle) and markings (right) were highlighted as edges. This means that, in the bridge inspection real-world, edges are not necessarily sufficient to represent features that accurately describe cracks in an image.</p><p><strong>What is next?</strong></p><p>In this post, I only used two gradient-based edge detectors to identify cracks in concrete images. There are more interesting and powerful techniques that I will discuss in my next post. I will also explain (based on performance metrics) why CNNs can be more effective at automatically extracting relevant features from a concrete crack image dataset avoiding the need for feature engineering.</p><p>Cheers :)</p><p><strong>References</strong></p><ol><li>S. Dorafshan, R. J. Thomas, and M. Maguire, “Comparison of deep convolutional neural networks and edge detectors for image-based crack detection in concrete,” <em>Construction and Building Materials</em>, vol. 186, pp. 1031–1045, Oct. 2018.</li><li>I. Abdel-Qader, P. Abudayyeh, M.E. Kelly, Analysis of edge-detection techniques for crack identification in bridges, J. Comput. Civil Eng. 17 (4)(2003) 255–263.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=219020defaef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CNN-based classification applied to concrete bridge crack images]]></title>
            <link>https://medium.com/@zoubirhajar/cnn-based-classification-applied-to-concrete-bridge-crack-images-6ae4731b638a?source=rss-80f1ec05fb9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ae4731b638a</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[concrete-crack]]></category>
            <category><![CDATA[bridge-inspections]]></category>
            <category><![CDATA[concrete-bridge]]></category>
            <dc:creator><![CDATA[Hajar Zoubir]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 23:56:56 GMT</pubDate>
            <atom:updated>2022-04-24T23:56:56.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFYD9kj7nxPZF1G5p4z-EQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@afritz55?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Amanda Forrest</a> on <a href="https://unsplash.com/s/photos/concrete-crack?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4><strong>Cracks in bridges</strong></h4><p>Cracks in reinforced concrete bridges occur due to several deterioration mechanisms related to mechanical (e.g. loading conditions), physical (e.g. drying shrinkage), chemical (e.g. alkali-aggregate reactions), and thermal (e.g. temperature gradients) factors. Their presence is hazardous to the bridge&#39;s durability and sometimes can be a sign of structural deficiency.</p><p>Identifying, localizing, and quantifying this type of damage is paramount to assess the condition of structural elements (e.g. girders and piers) and understand the possible effects of cracks on the bridge&#39;s structural reliability. To this end, bridge elements are regularly examined by trained inspectors who record the extent and severity of existing defects based on established standards and guidelines.</p><p>Bridge inspection is sometimes conducted using Unmanned Aerial Vehicles (UAVs) to access hard-to-reach areas of the bridge. However, this practice requires the automation of processing and analyzing a considerable amount of image data generated by mounted sensors (e.g. optical and thermal cameras) to efficiently detect cracks and other defects and evaluate the condition of the inspected bridge.</p><h4><strong>Crack detection automation</strong></h4><p>Several techniques have been applied to automate crack detection in concrete images ranging from traditional Image Processing Techniques (e.g. <a href="https://medium.com/jun94-devpblog/cv-5-canny-edge-detector-with-image-gradients-a42f07dc69c">edge detectors</a>) to Deep Learning models (e.g. <a href="https://medium.com/analytics-vidhya/introduction-to-convolutional-neural-networks-cnns-28bbf0f47172">Convolutional Neural Networks</a>, a.k.a CNNs). I will write more about these techniques and compare their performance in the crack detection task in future posts.</p><p>As features (i.e. representative properties that describe an object in an image) are automatically learned from a set of training data in a CNN-based learning framework, these deep networks have become the solution of choice among researchers for crack detection in concrete images.</p><p>Generally, <a href="https://medium.com/technologymadeeasy/the-best-explanation-of-convolutional-neural-networks-on-the-internet-fbb8b1ad5df8">the architecture of a CNN</a> consists of Convolutional layers where features are extracted from a set of labeled data (e.g. cracked and uncracked images), pooling layers that reduce the number of learnable parameters (i.e. weights), fully connected layers that map the flattened features to the Softmax layer where target class probabilities are computed. <a href="https://medium.com/geekculture/different-activation-functions-for-deep-neural-networks-you-should-know-ea5e86f51e84">Activation functions</a> (e.g. Rectified Linear Unit) are used to increase the non-linearity of the models. The learning scheme of these networks is based on <a href="https://medium.com/datadriveninvestor/overview-of-different-optimizers-for-neural-networks-e0ed119440c3">optimizing</a>, through <a href="https://medium.com/datathings/neural-networks-and-backpropagation-explained-in-a-simple-way-f540a3611f5e">backpropagation</a>, a <a href="https://medium.com/@shiva-verma/understanding-different-loss-functions-for-neural-networks-dd1ed0274718">loss function</a> (e.g. Binary Cross-Entropy loss) that measures the error between the predicted outputs and ground truth targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZZsPLh-dX6_gapnKkqRzA.png" /><figcaption>Example of the <a href="https://arxiv.org/abs/1409.1556">VGG16</a> model architecture</figcaption></figure><h4><strong>Crack image classification using a CNN</strong></h4><p>The rest of this post focuses on the application of a CNN for crack image classification.</p><p>So let’s dive into some code!</p><p>First of all, the images I am using are extracted from t<a href="https://www.matec-conferences.org/articles/matecconf/abs/2021/18/matecconf_iceaf2021_03014/matecconf_iceaf2021_03014.html">his dataset</a> where we shared more than 6900 cracked and uncracked images of concrete bridges following our participation in the <a href="https://iceaf.eu/2021/home">6th International Conference of Engineering Against Failure.</a></p><p>I am building a dataset of 1304 and 1806 cracked and uncracked images respectively, and it is randomly split into training (70%), validation (10%), and testing (20%) sets.</p><p>For model implementation, I am using Google Colaboratory with the 12GB NVIDIA Tesla K80 GPU provided by the platform, Pytorch, and the necessary libraries for data preprocessing, model training, and result visualization.</p><pre>from torchvision import datasets, models, transforms</pre><pre>import torch</pre><pre>import torch.nn as nn</pre><pre>import torch.optim as optim</pre><pre>import numpy as np</pre><pre>import matplotlib.pyplot as plt</pre><pre>import time</pre><pre>import os</pre><pre>device = &#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;</pre><p>Since my dataset is small, I am using a pre-trained <a href="https://arxiv.org/abs/1409.1556">VGG16 </a>model with <a href="https://ieeexplore.ieee.org/document/5206848">imageNet</a> weights and I am adjusting the number of classes of the last layer to two (since we have two target classes). This is one of the most common <a href="https://medium.com/towards-data-science/cnn-transfer-learning-fine-tuning-9f3e7c5806b2">Transfer Learning</a> techniques applied to transfer the knowledge of a source domain (large datasets like ImageNet) to a specific domain (low-scale datasets like our concrete crack dataset).</p><pre>model = models.vgg16(pretrained=True)</pre><pre>num_ftrs = model.classifier[6].in_features</pre><pre>model.classifier[6] = nn.Linear(num_ftrs,2)</pre><pre>input_size = 224</pre><p>I am also applying some data augmentation techniques to avoid <a href="https://medium.com/towards-data-science/overfitting-vs-underfitting-a-complete-example-d05dd7e19765">overfitting</a>.</p><pre>data_transforms = {</pre><pre>&#39;train&#39;: transforms.Compose([</pre><pre>transforms.RandomVerticalFlip(),</pre><pre>transforms.RandomHorizontalFlip(),</pre><pre>transforms.RandomRotation(45),</pre><pre>transforms.ToTensor(),</pre><pre>transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])</pre><pre>]),</pre><pre>&#39;val&#39;: transforms.Compose([</pre><pre>transforms.Resize(input_size),</pre><pre>transforms.ToTensor(),</pre><pre>transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])</pre><pre>]),</pre><pre>}</pre><pre>image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in [&#39;train&#39;, &#39;val&#39;]}</pre><pre>dataloaders_dict = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True, num_workers=4) for x in [&#39;train&#39;, &#39;val&#39;]}</pre><pre>device = torch.device(&quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;)</pre><pre>data_transforms_test = {</pre><pre>&#39;test&#39;: transforms.Compose([</pre><pre>transforms.ToTensor(),</pre><pre>transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])</pre><pre>])</pre><pre>}</pre><pre>dataset_test = {&#39;test&#39; : datasets.ImageFolder(os.path.join(data_dir, &#39;test&#39;), data_transforms_test[&#39;test&#39;])}</pre><pre>dataloader_test = {&#39;test&#39;: torch.utils.data.DataLoader(dataset_test[&#39;test&#39;], batch_size = 1, shuffle=False, num_workers=4)}</pre><p>I am keeping all the learning parameters frozen and only retraining the last convolutional and fully connected layers that are more sensitive to the target dataset.</p><pre>for param in model.parameters():</pre><pre>param.requires_grad = False</pre><pre>for param in model.classifier[3].parameters():</pre><pre>param.requires_grad = True</pre><pre>for param in model.classifier[0].parameters():</pre><pre>param.requires_grad = True</pre><pre>for param in model.features[28].parameters():</pre><pre>param.requires_grad = True</pre><p>Defining the loss function and optimizer (I am using the Stochastic Gradient Descent optimizer)</p><pre>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.SGD(params_to_update, lr=0.001, momentum=0.9)</pre><p>Defining training and testing functions</p><pre>#Training function : </pre><pre>def train_model(model, dataloaders, criterion, optimizer, num_epochs):</pre><pre>since = time.time()</pre><pre>val_acc_history = []</pre><pre>train_acc_history = []</pre><pre>val_loss_history = []</pre><pre>train_loss_history = []</pre><pre>best_model_wts = copy.deepcopy(model.state_dict())</pre><pre>best_acc = 0.0</pre><pre>for epoch in range(num_epochs):</pre><pre>print(&#39;Epoch {}/{}&#39;.format(epoch, num_epochs - 1))</pre><pre>print(&#39;-&#39; * 10)</pre><pre>for phase in [&#39;train&#39;, &#39;val&#39;]:</pre><pre>if phase == &#39;train&#39;:</pre><pre>model.train()  </pre><pre>else:</pre><pre>model.eval()   </pre><pre>running_loss = 0.0</pre><pre>running_corrects = 0</pre><pre>for inputs, labels in dataloaders[phase]:</pre><pre>inputs = inputs.to(device)</pre><pre>labels = labels.to(device)</pre><pre>optimizer.zero_grad()</pre><pre>with torch.set_grad_enabled(phase == &#39;train&#39;):</pre><pre>outputs = model(inputs)</pre><pre>loss = criterion(outputs, labels)</pre><pre>_, preds = torch.max(outputs, 1)</pre><pre>if phase == &#39;train&#39;:</pre><pre>loss.backward()</pre><pre>optimizer.step()</pre><pre>running_loss += loss.item() * inputs.size(0)</pre><pre>running_corrects += torch.sum(preds == labels.data)</pre><pre>epoch_loss = running_loss / len(dataloaders[phase].dataset)</pre><pre>epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)</pre><pre>print(&#39;{} Loss: {:.4f} Acc: {:.4f}&#39;.format(phase, epoch_loss, epoch_acc))</pre><pre>if phase == &#39;val&#39; and epoch_acc &gt; best_acc:</pre><pre>best_acc = epoch_acc</pre><pre>best_model_wts = copy.deepcopy(model.state_dict())</pre><pre>if phase == &#39;val&#39;:</pre><pre>val_acc_history.append(epoch_acc)</pre><pre>val_loss_history.append(epoch_loss)</pre><pre>if phase == &#39;train&#39;:</pre><pre>train_acc_history.append(epoch_acc)</pre><pre>train_loss_history.append(epoch_loss)</pre><pre>print()</pre><pre>time_elapsed = time.time() - since</pre><pre>print(&#39;Training complete in {:.0f}m {:.0f}s&#39;.format(time_elapsed // 60, time_elapsed % 60))</pre><pre>print(&#39;Best val Acc: {:4f}&#39;.format(best_acc))</pre><pre>model.load_state_dict(best_model_wts)</pre><pre>return model,(train_acc_history,val_acc_history,train_loss_history,val_loss_history)</pre><pre>#Testing function </pre><pre>def check_accuracy(loader, model):</pre><pre>num_correct = 0</pre><pre>num_samples = 0</pre><pre>model.eval()</pre><pre>with torch.no_grad():</pre><pre>for x, y in loader:</pre><pre>x = x.to(device=device)</pre><pre>y = y.to(device=device)</pre><pre>scores = model(x)</pre><pre>_, predictions = scores.max(1)</pre><pre>num_correct += (predictions == y).sum()</pre><pre>num_samples += predictions.size(0)</pre><pre>print(f&#39;Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}&#39;)</pre><pre>model.train()</pre><p>Training the model for 20 epochs</p><pre>model, hist = train_model(model, dataloaders_dict, criterion, optimizer, num_epochs=20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5s7p68pbL4YMEBnvXQESQ.png" /></figure><p>And testing the model</p><pre><br>check_accuracy(dataloader_test[&#39;test&#39;], model)</pre><p>After testing the trained model on the test set, I got a <strong>96.15%</strong> classification accuracy.</p><p>I then visualized the prediction results of sample crack images :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*gs35yUFZviFW8WXGfloOlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*r7FcKB0XFkFFfJ-ea9znaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*t_J36nI6kcwpI7UGax330A.png" /></figure><p>Finally, to check if the model has learned the right features for classification, I used the <a href="https://medium.com/towards-data-science/demystifying-convolutional-neural-networks-using-gradcam-554a85dd4e48">GradCAM interpretation technique</a> to visualize the regions of images that contributed to the classification result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*B3wKsZPQ0xCh73D-BH7iYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*8XU51B2DIkKMSsDdfLJkjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*7k6a0j6LhxljqJeewX4abg.png" /></figure><p>Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ae4731b638a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>