{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Dhruv Matani",
  "title_listed": "Efficient Image Segmentation Using PyTorch: Part 2",
  "keywords": "",
  "domain": "图像处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/efficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7/",
  "publish_date": "2023-06-27",
  "corpus_stage": "",
  "notes": "",
  "id": "c0bcb16b6731",
  "collected_at": "2026-10-02T10:47:51",
  "title": "Efficient Image Segmentation Using PyTorch: Part 2 | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\n# Efficient Image Segmentation Using PyTorch: Part 2\nA CNN-based model\n[Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\nJune 27, 202312 min read\nThis is the second part of the 4-part series to implement image segmentation step by step from scratch using deep learning techniques in PyTorch. This part will focus on implementing a baseline image segmentation Convolutional Neural Network (CNN) model.\nCo-authored with [Naresh Singh](https://medium.com/@brocolishbroxoli)\n![Figure 1: Result of running image segmentation using a CNN. In order from top to bottom, input images, ground truth segmentation masks, predicted segmentation masks. Source: Author\\(s\\)](../images/000.png)\nFigure 1: Result of running image segmentation using a CNN. In order from top to bottom, input images, ground truth segmentation masks, predicted segmentation masks. Source: Author(s)\n* * *\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## Article outline\nIn this article, we will implement a [Convolutional Neural Network (CNN)](https://en.wikipedia.org/wiki/Convolutional_neural_network) based architecture called [SegNet](https://arxiv.org/abs/1511.00561) which will assign each pixel in an input image to a corresponding pet such as a cat or a dog. The pixels which don't belong to any pet will be classified as background pixels. We will build and train this model on the [Oxford Pets dataset](https://www.robots.ox.ac.uk/~vgg/data/pets/) using [PyTorch](https://pytorch.org/) to develop a sense of what it takes to deliver a successful image segmentation task. The model building process will be hands-on where we will discuss in detail the role of each layer in our model. The article will contain plenty of references to research papers and articles for further learning.\nThroughout this article, we will reference the code and results from this [notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/pets_segmentation/oxford-iiit-pets-segmentation-using-pytorch-segnet-and-depth-wise-separable-convs.ipynb). If you wish to reproduce the results, you'll need a GPU to ensure that the notebook completes running in a reasonable amount of time.\n* * *\n## Articles in this series\nThis series is for readers at all experience levels with deep learning. If you want to learn about the practice of deep learning and vision AI along with some solid theory and hands-on experience, you've come to the right place! This is expected to be a 4-part series with the following articles:\n  1. [Concepts and Ideas](https://medium.com/p/89e8297a0923/)\n  2. **A CNN-based model (this article)**\n  3. [Depthwise separable convolutions](https://medium.com/p/3534cf04fb89/)\n  4. [A Vision Transformer-based model](https://medium.com/p/6c86da083432/)\n\n\nLet's start this discussion with a short introduction to the Convolution layers and a few other layers that are typically used together as a convolution block.\n* * *\n## Conv-BatchNorm-ReLU and Max Pooling/Unpooling\nA convolution, batch-normalization, ReLU block is the holy trinity of vision AI. You'll see it used frequently with CNN-based vision AI models. Each of these terms stands for a distinct layer implemented in PyTorch. The convolution layer is responsible for performing a cross-correlation operation of learned filters on the input tensor. Batch Normalization centers the elements in the batch to zero mean and unit variance, and ReLU is a non-linear activation function that keeps just the positive values in the input.\nA typical CNN progressively reduces the input spatial dimensions as layers are stacked. The motivation behind the reduction of spatial dimensions is discussed in the next section. This reduction is achieved by pooling the neighboring values using a simple function such as max or average. We will discuss this further in the Max-Pooling section. In classification problems, the stack of Conv-BN-ReLU-Pool blocks is followed by a classification head which predicts the probability that input belongs to one of the target classes. Some sets of problems such as Semantic Segmentation require per-pixel prediction. For such cases, a stack of upsampling blocks are appended after the downsampling blocks to project their output to the required spatial dimension. The upsampling blocks are nothing but Conv-BN-ReLU-Unpool blocks which replace the pooling layer with an un-pooling layer. We will talk more about un-pooling in the Max-Pooling section.\nNow, let's further elaborate on the motivation behind convolution layers.\n### Convolution\nConvolutions are the basic building blocks of vision AI models. They are used heavily in computer vision and have historically been used to implement vision transformations such as:\n  1. Edge detection\n  2. Image blurring and sharpening\n  3. Embossing\n  4. Intensification\n\n\nA convolution operation is an elementwise multiplication and aggregation of two matrices. An example convolution operation is shown in Figure 2.\n![Figure 2: An illustration of the convolution operation. Source: Author\\(s\\)](../images/001.png)\nFigure 2: An illustration of the convolution operation. Source: Author(s)\nIn a deep learning context, convolution is carried out between an _n-dimensional_ parameter matrix called a filter or a kernel over a larger-sized input. This is achieved by sliding the filter over the input and applying convolution to the corresponding section. The extent of the slide is configured using a stride parameter. A stride of one means the kernel slides over by one step to operate on the next section. As opposed to the traditional approaches where a fixed filter is used, deep learning learns the filter from the data using backpropagation.\n**So how do convolutions assist in deep learning?**\nIn deep learning, a convolution layer is used to detect visual features. A typical CNN model contains a stack of such layers. The bottom layers in the stack detect simple features such as lines and edges. As we move up in the stack, the layers detect increasingly complex features. Middle layers in the stack detect combinations of lines and edges and the top layers detect complex shapes such as a car, a face or an airplane. Figure 3 shows visually the output of top and bottom layers for a trained model.\n![Figure 3: What convolutional filters learn to identify. Source: Convolutional Deep Belief Networks for Scalable Unsupervised Learning of Hierarchical Representations](../images/002.png)\nFigure 3: What convolutional filters learn to identify. Source: [Convolutional Deep Belief Networks for Scalable Unsupervised Learning of Hierarchical Representations](http://web.eecs.umich.edu/~honglak/icml09-ConvolutionalDeepBeliefNetworks.pdf)\nA convolution layer has a set of learnable filters that act on small regions in the input to produce a representative output value for each region. For example, a 3x3 filter operates over a 3x3 size region and produces a value representative of the region. The repeated application of a filter over input regions produces an output which becomes the input to the next layer in the stack. Intuitively, the layers higher up get to \"see\" a larger region of the input. For example, a 3x3 filter in the second convolution layer operates on the output of the first convolution layer where each cell contains information about the 3x3 sized region in the input. If we assume a convolution operation with stride=1, then the filter in the second layer will \"see'' the 5x5 sized region of the original input. This is called the [receptive field](https://theaisummer.com/receptive-field/) of the convolution. The repeated application of convolutional layers progressively reduces the spatial dimensions of the input image and increases the field of vision of the filters which enables them to \"see\" complex shapes. Figure 4 shows the processing of a 1-D input by a convolution network. An element in the output layer is a representative of a relatively larger input chunk.\n![Figure 4: Receptive field of a 1d convolution with kernel size=3, applied 3 times. Assume stride=1 and no padding. After the 3rd successive application of the convolutional kernel, a single pixel is able to see 7 pixels in the original input image. Source: Author\\(s\\)](../images/003.png)\nFigure 4: Receptive field of a 1d convolution with kernel size=3, applied 3 times. Assume stride=1 and no padding. After the 3rd successive application of the convolutional kernel, a single pixel is able to see 7 pixels in the original input image. Source: Author(s)\nOnce a convolutional layer can detect these objects and is able to generate their representations, we can use these representations for image classification, image segmentation, and object detection and localization. Broadly speaking, CNNs adhere to the following general principles:\n  1. A Convolution layer either keeps the number of output channels © intact or doubles them.\n  2. It keeps the spatial dimensions intact using a stride=1 or reduces them to a half using stride=2.\n  3. It's common to pool the output of a convolution block to change the spatial dimensions of an image.\n\n\nA convolution layer applies the kernel independently to each input. This could cause its output to vary for different inputs. A Batch Normalization layer typically follows a convolution layer to address this problem. Let's understand its role in detail in the next section.\n### Batch Normalization\nBatch Normalization layer normalizes the channel values in the batch input to have a zero mean and a unit variance. This normalization is performed independently for each channel in the batch to ensure that the channel values for the inputs have the same distribution. Batch Normalization has the following benefits:\n  1. It stabilizes the training process by preventing the gradients from becoming too small.\n  2. It achieves faster convergence on our tasks.\n\n\nIf all we had was a stack of convolution layers, it would essentially be equivalent to a single convolution layer network because of the cascading effect of linear transformations. In other words, a sequence of linear transformations can be replaced with a single linear transformation which has the same effect. Intuitively, if we multiply a vector with a constant _k₁_ followed by multiplication with another constant _k₂_ , it is equivalent to a single multiplication by a constant _k₁k₂_. Hence, for the networks to be realistically deep, they must have a non-linearity to prevent their _collapse_. We will discuss ReLU in the next section which is frequently used as a non-linearity.\n### ReLU\nReLU is a simple non-linear activation function which clips the lowest input values to be greater than or equal to 0. It also helps with the vanishing gradients problem limiting the outputs to be greater than or equal to 0. The ReLU layer is typically followed by a pooling layer to shrink the spatial dimensions in the downscaling subnetwork or an un-pooling layer to bump the spatial dimensions in the upscaling subnetwork. The details are provided in the next section.\n### Pooling\nA pooling layer is used to shrink the spatial dimensions of our inputs. Pooling with _stride=2_ will transform an input with spatial dimensions (H, W) to (H/2, W/2). [Max-pooling](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html) is the most commonly used pooling technique in deep CNNs. It projects the maximum value in a grid of (say) 2x2 onto the output. Then, we slide the 2x2 pooling window to the next section based on the stride similar to convolutions. Doing this repeatedly with a _stride=2_ results in an output that is half the height and half the width of the input. Another commonly used pooling layer is the [average-pooling](https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html#torch.nn.AvgPool2d) layer, which computes the average instead of the max.\nThe reverse of a pooling layer is called an un-pooling layer. It takes an (H, W) dimension input and converts it into a (2H, 2W) dimension output for _stride=2_. A necessary ingredient of this transformation is selecting the location in the 2x2 section of the output to project the input value. To do this, we need a [max-unpooling](https://pytorch.org/docs/stable/generated/torch.nn.MaxUnpool2d.html#torch.nn.MaxUnpool2d)-index-map which tells us the target locations in the output section. This unpooling-map is produced by a previous max-pooling operation. Figure 5 shows examples of pooling and un-pooling operations.\n![Figure 5: Max pooling and un-pooling. Source: DeepPainter: Painter Classification Using Deep Convolutional Autoencoders](../images/004.png)\nFigure 5: Max pooling and un-pooling. Source: [DeepPainter: Painter Classification Using Deep Convolutional Autoencoders](https://www.researchgate.net/publication/306081538_DeepPainter_Painter_Classification_Using_Deep_Convolutional_Autoencoders)\nWe can consider max-pooling as a type of non-linear activation function. However, it's [reported](https://ai.stackexchange.com/questions/17937/is-a-non-linear-activation-function-needed-if-we-perform-max-pooling-after-the-c) that using it to replace a non-linearity such as ReLU [affects the network's performance](https://arxiv.org/pdf/1606.02228.pdf). In contrast, average pooling can not be considered as a nonlinear function since it uses all its inputs to produce an output that is a linear combination of its inputs.\nThis covers all the basic building blocks of deep CNNs. Now, let's put them together to create a model. The model we have chosen for this exercise is called a SegNet. We'll discuss it next.\n* * *\n## SegNet: A CNN-based model\n[SegNet](https://arxiv.org/abs/1511.00561) is a deep CNN model based on the fundamental blocks that we have discussed in this article. It has two distinct sections. The bottom section, also called an encoder, down-samples the input to generate features representative of the input. The top decoder section up-samples the features to create per-pixel classification. Each section is composed of a sequence of Conv-BN-ReLU blocks. These blocks also incorporate pooling or un-pooling layers in downsampling and upsampling paths respectively. Figure 6 shows the arrangement of the layers in more detail. SegNet uses the pooling indices from the max-pooling operation in the encoder to determine which values to copy over during the max-unpooling operation in the decoder. While each element of an activation tensor is 4-bytes (32-bits), an offset within a 2x2 square can be stored using just 2-bits. This is more efficient in terms of memory used since these activations (or indices in the case of SegNet) need to be stored while the model runs.\n![Figure 6: The SegNet model architecture for image segmentation. Source: SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation](../images/005.png)\nFigure 6: The SegNet model architecture for image segmentation. Source: SegNet: [A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation](https://arxiv.org/pdf/1511.00561.pdf)\n[This notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/pets_segmentation/oxford-iiit-pets-segmentation-using-pytorch-segnet-and-depth-wise-separable-convs.ipynb) contains all the code for this section.\nThis model has 15.27M trainable parameters.\nThe following configuration was used during model training and validation.\n  1. The _random horizontal flip_ and _color jitter_ data augmentations are applied to the training set to prevent overfitting\n  2. The images are resized to 128x128 pixels in a non-aspect preserving resize operation\n  3. No input normalization is applied to the images; instead a [batch normalization layer is used as the first layer of the model](https://towardsdatascience.com/replace-manual-normalization-with-batch-normalization-in-vision-ai-models-e7782e82193c)\n  4. The model is trained for 20 epochs using the Adam optimizer with a LR of 0.001 and a StepLR Scheduler that decays the learning rate by 0.7 every 7 epochs\n  5. The cross-entropy loss function is used to classify a pixel as belonging to a pet, the background, or a pet border\n\n\nThe model achieved a validation accuracy of 88.28% after 20 training epochs.\nWe plotted a gif showing how the model is learning to predict the segmentation masks for 21 images in the validation set.\n![Figure 6: A gif showing how the SegNet model is learning to predict segmentation masks for 21 images in the validation set. Source: Author\\(s\\)](../images/body-5f80124c20ed42107acb.img)\nFigure 6: A gif showing how the SegNet model is learning to predict segmentation masks for 21 images in the validation set. Source: Author(s)\nThe definitions of all the validation metrics are described in [Part-1 of this series](https://medium.com/p/89e8297a0923/).\nIf you'd like to see a fully-convolutional model for segmenting pet images implemented using Tensorflow, please see Chapter-4: Efficient Architectures of the [Efficient Deep Learning Book](https://efficientdlbook.com/#table-of-contents).\n### Observations from model learning\nBased on the development of the predictions that the trained model makes after every epoch, we can observe the following.\n  1. The model is able to learn enough to make the output look in the right ballpark of the pet in the image even as early as 1 training epoch\n  2. The border pixels are harder to segment since we're using an unweighted loss function that treats each success (or failure) equally, so getting the border pixels wrong doesn't cost the model much in terms of the loss. We would encourage you to investigate this and check what strategies you could try to fix this issue. Try using [Focal Loss](https://towardsdatascience.com/focal-loss-a-better-alternative-for-cross-entropy-1d073d92d075) and see how it performs\n  3. The model seems to be learning even after 20 training epochs. This suggests that we could improve validation accuracy if we trained the model longer\n  4. Some of the ground-truth labels themselves are hard to figure out - for example, the mask of the dog in the middle row, last column has a lot of unknown pixels in the area where the body of the dog is occluded by plants. This is very hard for the model to figure out, so one should always expect loss in accuracy for such examples. However, this doesn't mean that the model isn't doing well. One should always spot check the predictions to develop a sense of the model's behavior in addition to looking at the overall validation metrics.\n\n\n![Figure 7: An example of the ground truth segmentation mask containing a lot of unknown pixels. This is a very hard input for any ML model. Source: Author\\(s\\)](../images/006.png)\nFigure 7: An example of the ground truth segmentation mask containing a lot of unknown pixels. This is a very hard input for any ML model. Source: Author(s)\n* * *\n## Conclusion\nIn part-2 of this series, we learned about the basic building blocks of deep CNNs for vision AI. We saw how to implement the SegNet model from scratch in PyTorch, and we visualized how the model trained on successive epochs performs on 21 validation images. This should help you appreciate how quickly models can learn enough to make the output look somewhere in the right ballpark. In this case, we can see segmentation masks that roughly resemble the actual segmentation mask as early as the first training epoch!\nIn the [next part of this series](https://medium.com/p/3534cf04fb89/), we'll take a look at how we can optimize our model for on-device inference and reduce the number of trainable parameters (and hence model size) while keeping the validation accuracy roughly the same.\n* * *\n## Further Reading\nRead more about convolutions here:\n  1. The course titled \"[Ancient Secrets of computer vision](https://pjreddie.com/courses/computer-vision/)\" at The University of Washington taught by Joseph Redmon has an excellent set of videos on Convolutions (especially chapters 4, 5, and 13), which we highly recommend watching\n  2. [A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285) (highly recommended)\n  3. <https://towardsdatascience.com/computer-vision-convolution-basics-2d0ae3b79346>\n  4. [The Conv2d layer in PyTorch (documentation)](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d)\n  5. [What do convolutions learn?](https://www.kdnuggets.com/2016/11/intuitive-explanation-convolutional-neural-networks.html/3)\n  6. [Convolution visualizer](https://ezyang.github.io/convolution-visualizer/index.html)\n\n\nRead more about batch normalization here:\n  1. [Batch normalization: Wikipedia](https://en.wikipedia.org/wiki/Batch_normalization)\n  2. [Batch normalization: Machine learning mastery](https://machinelearningmastery.com/batch-normalization-for-training-of-deep-neural-networks/)\n  3. [BatchNorm2d layer in PyTorch here](https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html).\n\n\nRead more about activation functions and ReLU here:\n  1. [ReLU: Machine learning mastery](https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/)\n  2. [ReLU: Wikipedia](https://en.wikipedia.org/wiki/Rectifier_\\(neural_networks\\))\n  3. [ReLU: Quora](https://www.quora.com/Why-is-ReLU-used-so-much-in-neural-networks)\n  4. [ReLU API in PyTorch](https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-a3403563a948ce1eab7b.jpeg)\nWritten By\n## [Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[See all from Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[Cnn](https://towardsdatascience.com/tag/cnn/)[Convolutional Network](https://towardsdatascience.com/tag/convolutional-network/)[Deep Learning](https://towardsdatascience.com/tag/deep-learning/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)[Pytorch Image Segment](https://towardsdatascience.com/tag/pytorch-image-segment/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fefficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7%2F&title=Efficient%20Image%20Segmentation%20Using%20PyTorch%3A%20Part%202)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fefficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7%2F&title=Efficient%20Image%20Segmentation%20Using%20PyTorch%3A%20Part%202)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fefficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7%2F&text=Efficient%20Image%20Segmentation%20Using%20PyTorch%3A%20Part%202)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/007.jpeg)](https://towardsdatascience.com/make-amateur-radio-cool-again-said-mr-artificial-intelligence-36cb32978fb2/)\n## [\"Make amateur radio cool again\", said Mr Artificial Intelligence.](https://towardsdatascience.com/make-amateur-radio-cool-again-said-mr-artificial-intelligence-36cb32978fb2/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nA project on building a speech recognition system for amateur radio communication.\n[Chris](https://towardsdatascience.com/author/kakittwo/)\nOctober 6, 20183 min read\n  * [![](../images/008.png)](https://towardsdatascience.com/benchmark-m1-vs-xeon-vs-core-i5-vs-k80-and-t4-e3802f27421c/)\n## [Benchmark M1 vs Xeon vs Core i5 vs K80 and T4](https://towardsdatascience.com/benchmark-m1-vs-xeon-vs-core-i5-vs-k80-and-t4-e3802f27421c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCompare Apple Silicon M1 CPU and GPU performances to high-end configurations on MLP, CNN and LSTM models\n[Fabrice Daniel](https://towardsdatascience.com/author/fabrice-daniel/)\nDecember 26, 20206 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/how-to-organize-and-track-your-pytorch-training-by-creating-a-run-manager-878cc830ea90/)\n## [How to organize and track your PyTorch training by creating a run manager](https://towardsdatascience.com/how-to-organize-and-track-your-pytorch-training-by-creating-a-run-manager-878cc830ea90/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIf you are searching for a way to organize, manage and log the steps and operations during a training process and don't want to use PyTorch...\n[Tudor Surdoiu](https://towardsdatascience.com/author/dacus-augustus/)\nOctober 4, 20224 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/tune-deep-neural-networks-using-bayesian-optimization-c9f6503a049f/)\n## [Tune Deep Neural Networks using Bayesian Optimization](https://towardsdatascience.com/tune-deep-neural-networks-using-bayesian-optimization-c9f6503a049f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nLeverage Bayesian Theory to boost your performance\n[Nikos Kafritsas](https://towardsdatascience.com/author/nikoskafritsas/)\nJune 8, 20222 min read\n  * [![](../images/011.jpg)](https://towardsdatascience.com/shahrukh-khan-face-recognizer-your-4th-cnn-38668dae5afc/)\n## [Shahrukh Khan Face Recognizer - Your 4th CNN](https://towardsdatascience.com/shahrukh-khan-face-recognizer-your-4th-cnn-38668dae5afc/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFourth CNN?\n[Vidisha Jitani](https://towardsdatascience.com/author/vidishajitani/)\nOctober 6, 20204 min read\n  * [![](../images/012.jpg)](https://towardsdatascience.com/llm-and-gnn-how-to-improve-reasoning-of-both-ai-systems-on-graph-data-5ebd875eef30/)\n## [LLM and GNN: How to Improve Reasoning of Both AI Systems on Graph Data](https://towardsdatascience.com/llm-and-gnn-how-to-improve-reasoning-of-both-ai-systems-on-graph-data-5ebd875eef30/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nArtificial intelligence software was used to enhance the grammar, flow, and readability of this article's text.\n[Anthony Alcaraz](https://towardsdatascience.com/author/alcarazanthony1/)\nDecember 3, 20239 min read\n  * [![](../images/013.png)](https://towardsdatascience.com/face-mask-detection-using-darknets-yolov3-84cde488e5a1/)\n## [Face Mask Detection using darknet's YOLOv3](https://towardsdatascience.com/face-mask-detection-using-darknets-yolov3-84cde488e5a1/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nCOVID-19: Tutorial on how to build a face mask detector using YOLOv3. *For inference, both video streams and images can be used.\n[Stefanos Kanellopoulos](https://towardsdatascience.com/author/skanelo/)\nApril 12, 20219 min read\n  * [![](../images/014.png)](https://towardsdatascience.com/metropolitan-museum-of-art-data-analysis-and-visualization-7d1d023c68fe/)\n## [The Metropolitan Museum of Art Data Analysis and Visualization](https://towardsdatascience.com/metropolitan-museum-of-art-data-analysis-and-visualization-7d1d023c68fe/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAnalyze and Visualize Artists and Artworks Metadata\n[Margaret Maynard-Reid](https://towardsdatascience.com/author/margaretmz/)\nNovember 23, 20203 min read\n  * [![](../images/015.jpg)](https://towardsdatascience.com/multiple-gpu-training-in-pytorch-and-gradient-accumulation-as-an-alternative-to-it-e578b3fc5b91/)\n## [Multiple GPU training in PyTorch and Gradient Accumulation as an alternative to it](https://towardsdatascience.com/multiple-gpu-training-in-pytorch-and-gradient-accumulation-as-an-alternative-to-it-e578b3fc5b91/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCode and Theory\n[Alexey Kravets](https://towardsdatascience.com/author/alexml0123/)\nJuly 24, 20237 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "Efficient Image Segmentation Using PyTorch: Part 2 | Towards Data Science",
    "description": "A CNN-based model",
    "keywords": null,
    "author": "Dhruv Matani",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Efficient Image Segmentation Using PyTorch: Part 2",
    "og:description": "A CNN-based model",
    "og:url": "https://towardsdatascience.com/efficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/1ZC7cxgypMANduMyG_zOIGw.png",
    "og:image:width": "659",
    "og:image:height": "380",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Dhruv Matani",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "12 min read",
    "article:published_time": "2023-06-27T05:11:46.000Z",
    "article:modified_time": "2023-06-27T05:11:46.000Z",
    "article:author": "https://towardsdatascience.com/author/dhruvbird/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:09:22Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:09:22Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:09:22Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T18:09:22Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/deep-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/dhruvbird/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/replace-manual-normalization-with-batch-normalization-in-vision-ai-models-e7782e82193c"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/focal-loss-a-better-alternative-for-cross-entropy-1d073d92d075"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/computer-vision-convolution-basics-2d0ae3b79346"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/cnn/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/convolutional-network/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/deep-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/pytorch/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/pytorch-image-segment/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/make-amateur-radio-cool-again-said-mr-artificial-intelligence-36cb32978fb2/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/kakittwo/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/benchmark-m1-vs-xeon-vs-core-i5-vs-k80-and-t4-e3802f27421c/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://medium.com/@brocolishbroxoli"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Convolutional_neural_network"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/abs/1511.00561"
    },
    {
      "type": "external",
      "href": "https://www.robots.ox.ac.uk/~vgg/data/pets/"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/"
    },
    {
      "type": "external",
      "href": "https://github.com/dhruvbird/ml-notebooks/blob/main/pets_segmentation/oxford-iiit-pets-segmentation-using-pytorch-segnet-and-depth-wise-separable-convs.ipynb"
    },
    {
      "type": "external",
      "href": "https://medium.com/p/89e8297a0923/"
    },
    {
      "type": "external",
      "href": "https://medium.com/p/3534cf04fb89/"
    },
    {
      "type": "external",
      "href": "https://medium.com/p/6c86da083432/"
    },
    {
      "type": "external",
      "href": "http://web.eecs.umich.edu/~honglak/icml09-ConvolutionalDeepBeliefNetworks.pdf"
    },
    {
      "type": "external",
      "href": "https://theaisummer.com/receptive-field/"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/docs/stable/generated/torch.nn.MaxUnpool2d.html"
    },
    {
      "type": "external",
      "href": "https://www.researchgate.net/publication/306081538_DeepPainter_Painter_Classification_Using_Deep_Convolutional_Autoencoders"
    },
    {
      "type": "external",
      "href": "https://ai.stackexchange.com/questions/17937/is-a-non-linear-activation-function-needed-if-we-perform-max-pooling-after-the-c"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:33:59Z",
  "source_url": "https://towardsdatascience.com/efficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\n# Efficient Image Segmentation Using PyTorch: Part 2\nA CNN-based model\n[Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\nJune 27, 202312 min read\nThis is the second part of the 4-part series to implement image segmentation step by step from scratch using deep learning techniques in PyTorch. This part will focus on implementing a baseline image segmentation Convolutional Neural Network (CNN) model.\nCo-authored with [Naresh Singh](https://medium.com/@brocolishbroxoli)\n![Figure 1: Result of running image segmentation using a CNN. In order from top to bottom, input images, ground truth segmentation masks, predicted segmentation masks. Source: Author\\(s\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/1ZC7cxgypMANduMyG_zOIGw.png)\nFigure 1: Result of running image segmentation using a CNN. In order from top to bottom, input images, ground truth segmentation masks, predicted segmentation masks. Source: Author(s)\n* * *\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## Article outline\nIn this article, we will implement a [Convolutional Neural Network (CNN)](https://en.wikipedia.org/wiki/Convolutional_neural_network) based architecture called [SegNet](https://arxiv.org/abs/1511.00561) which will assign each pixel in an input image to a corresponding pet such as a cat or a dog. The pixels which don't belong to any pet will be classified as background pixels. We will build and train this model on the [Oxford Pets dataset](https://www.robots.ox.ac.uk/~vgg/data/pets/) using [PyTorch](https://pytorch.org/) to develop a sense of what it takes to deliver a successful image segmentation task. The model building process will be hands-on where we will discuss in detail the role of each layer in our model. The article will contain plenty of references to research papers and articles for further learning.\nThroughout this article, we will reference the code and results from this [notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/pets_segmentation/oxford-iiit-pets-segmentation-using-pytorch-segnet-and-depth-wise-separable-convs.ipynb). If you wish to reproduce the results, you'll need a GPU to ensure that the notebook completes running in a reasonable amount of time.\n* * *\n## Articles in this series\nThis series is for readers at all experience levels with deep learning. If you want to learn about the practice of deep learning and vision AI along with some solid theory and hands-on experience, you've come to the right place! This is expected to be a 4-part series with the following articles:\n  1. [Concepts and Ideas](https://medium.com/p/89e8297a0923/)\n  2. **A CNN-based model (this article)**\n  3. [Depthwise separable convolutions](https://medium.com/p/3534cf04fb89/)\n  4. [A Vision Transformer-based model](https://medium.com/p/6c86da083432/)\n\n\nLet's start this discussion with a short introduction to the Convolution layers and a few other layers that are typically used together as a convolution block.\n* * *\n## Conv-BatchNorm-ReLU and Max Pooling/Unpooling\nA convolution, batch-normalization, ReLU block is the holy trinity of vision AI. You'll see it used frequently with CNN-based vision AI models. Each of these terms stands for a distinct layer implemented in PyTorch. The convolution layer is responsible for performing a cross-correlation operation of learned filters on the input tensor. Batch Normalization centers the elements in the batch to zero mean and unit variance, and ReLU is a non-linear activation function that keeps just the positive values in the input.\nA typical CNN progressively reduces the input spatial dimensions as layers are stacked. The motivation behind the reduction of spatial dimensions is discussed in the next section. This reduction is achieved by pooling the neighboring values using a simple function such as max or average. We will discuss this further in the Max-Pooling section. In classification problems, the stack of Conv-BN-ReLU-Pool blocks is followed by a classification head which predicts the probability that input belongs to one of the target classes. Some sets of problems such as Semantic Segmentation require per-pixel prediction. For such cases, a stack of upsampling blocks are appended after the downsampling blocks to project their output to the required spatial dimension. The upsampling blocks are nothing but Conv-BN-ReLU-Unpool blocks which replace the pooling layer with an un-pooling layer. We will talk more about un-pooling in the Max-Pooling section.\nNow, let's further elaborate on the motivation behind convolution layers.\n### Convolution\nConvolutions are the basic building blocks of vision AI models. They are used heavily in computer vision and have historically been used to implement vision transformations such as:\n  1. Edge detection\n  2. Image blurring and sharpening\n  3. Embossing\n  4. Intensification\n\n\nA convolution operation is an elementwise multiplication and aggregation of two matrices. An example convolution operation is shown in Figure 2.\n![Figure 2: An illustration of the convolution operation. Source: Author\\(s\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/09-7pcgAWstNxekPT.png)\nFigure 2: An illustration of the convolution operation. Source: Author(s)\nIn a deep learning context, convolution is carried out between an _n-dimensional_ parameter matrix called a filter or a kernel over a larger-sized input. This is achieved by sliding the filter over the input and applying convolution to the corresponding section. The extent of the slide is configured using a stride parameter. A stride of one means the kernel slides over by one step to operate on the next section. As opposed to the traditional approaches where a fixed filter is used, deep learning learns the filter from the data using backpropagation.\n**So how do convolutions assist in deep learning?**\nIn deep learning, a convolution layer is used to detect visual features. A typical CNN model contains a stack of such layers. The bottom layers in the stack detect simple features such as lines and edges. As we move up in the stack, the layers detect increasingly complex features. Middle layers in the stack detect combinations of lines and edges and the top layers detect complex shapes such as a car, a face or an airplane. Figure 3 shows visually the output of top and bottom layers for a trained model.\n![Figure 3: What convolutional filters learn to identify. Source: Convolutional Deep Belief Networks for Scalable Unsupervised Learning of Hierarchical Representations](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/0TSlsgbgCw7Ddq8ux.png)\nFigure 3: What convolutional filters learn to identify. Source: [Convolutional Deep Belief Networks for Scalable Unsupervised Learning of Hierarchical Representations](http://web.eecs.umich.edu/~honglak/icml09-ConvolutionalDeepBeliefNetworks.pdf)\nA convolution layer has a set of learnable filters that act on small regions in the input to produce a representative output value for each region. For example, a 3x3 filter operates over a 3x3 size region and produces a value representative of the region. The repeated application of a filter over input regions produces an output which becomes the input to the next layer in the stack. Intuitively, the layers higher up get to \"see\" a larger region of the input. For example, a 3x3 filter in the second convolution layer operates on the output of the first convolution layer where each cell contains information about the 3x3 sized region in the input. If we assume a convolution operation with stride=1, then the filter in the second layer will \"see'' the 5x5 sized region of the original input. This is called the [receptive field](https://theaisummer.com/receptive-field/) of the convolution. The repeated application of convolutional layers progressively reduces the spatial dimensions of the input image and increases the field of vision of the filters which enables them to \"see\" complex shapes. Figure 4 shows the processing of a 1-D input by a convolution network. An element in the output layer is a representative of a relatively larger input chunk.\n![Figure 4: Receptive field of a 1d convolution with kernel size=3, applied 3 times. Assume stride=1 and no padding. After the 3rd successive application of the convolutional kernel, a single pixel is able to see 7 pixels in the original input image. Source: Author\\(s\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/0LKQOxTXGm5lTJtoc.png)\nFigure 4: Receptive field of a 1d convolution with kernel size=3, applied 3 times. Assume stride=1 and no padding. After the 3rd successive application of the convolutional kernel, a single pixel is able to see 7 pixels in the original input image. Source: Author(s)\nOnce a convolutional layer can detect these objects and is able to generate their representations, we can use these representations for image classification, image segmentation, and object detection and localization. Broadly speaking, CNNs adhere to the following general principles:\n  1. A Convolution layer either keeps the number of output channels © intact or doubles them.\n  2. It keeps the spatial dimensions intact using a stride=1 or reduces them to a half using stride=2.\n  3. It's common to pool the output of a convolution block to change the spatial dimensions of an image.\n\n\nA convolution layer applies the kernel independently to each input. This could cause its output to vary for different inputs. A Batch Normalization layer typically follows a convolution layer to address this problem. Let's understand its role in detail in the next section.\n### Batch Normalization\nBatch Normalization layer normalizes the channel values in the batch input to have a zero mean and a unit variance. This normalization is performed independently for each channel in the batch to ensure that the channel values for the inputs have the same distribution. Batch Normalization has the following benefits:\n  1. It stabilizes the training process by preventing the gradients from becoming too small.\n  2. It achieves faster convergence on our tasks.\n\n\nIf all we had was a stack of convolution layers, it would essentially be equivalent to a single convolution layer network because of the cascading effect of linear transformations. In other words, a sequence of linear transformations can be replaced with a single linear transformation which has the same effect. Intuitively, if we multiply a vector with a constant _k₁_ followed by multiplication with another constant _k₂_ , it is equivalent to a single multiplication by a constant _k₁k₂_. Hence, for the networks to be realistically deep, they must have a non-linearity to prevent their _collapse_. We will discuss ReLU in the next section which is frequently used as a non-linearity.\n### ReLU\nReLU is a simple non-linear activation function which clips the lowest input values to be greater than or equal to 0. It also helps with the vanishing gradients problem limiting the outputs to be greater than or equal to 0. The ReLU layer is typically followed by a pooling layer to shrink the spatial dimensions in the downscaling subnetwork or an un-pooling layer to bump the spatial dimensions in the upscaling subnetwork. The details are provided in the next section.\n### Pooling\nA pooling layer is used to shrink the spatial dimensions of our inputs. Pooling with _stride=2_ will transform an input with spatial dimensions (H, W) to (H/2, W/2). [Max-pooling](https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html) is the most commonly used pooling technique in deep CNNs. It projects the maximum value in a grid of (say) 2x2 onto the output. Then, we slide the 2x2 pooling window to the next section based on the stride similar to convolutions. Doing this repeatedly with a _stride=2_ results in an output that is half the height and half the width of the input. Another commonly used pooling layer is the [average-pooling](https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html#torch.nn.AvgPool2d) layer, which computes the average instead of the max.\nThe reverse of a pooling layer is called an un-pooling layer. It takes an (H, W) dimension input and converts it into a (2H, 2W) dimension output for _stride=2_. A necessary ingredient of this transformation is selecting the location in the 2x2 section of the output to project the input value. To do this, we need a [max-unpooling](https://pytorch.org/docs/stable/generated/torch.nn.MaxUnpool2d.html#torch.nn.MaxUnpool2d)-index-map which tells us the target locations in the output section. This unpooling-map is produced by a previous max-pooling operation. Figure 5 shows examples of pooling and un-pooling operations.\n![Figure 5: Max pooling and un-pooling. Source: DeepPainter: Painter Classification Using Deep Convolutional Autoencoders](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/0ZFlYSQX-8bTujUT4.png)\nFigure 5: Max pooling and un-pooling. Source: [DeepPainter: Painter Classification Using Deep Convolutional Autoencoders](https://www.researchgate.net/publication/306081538_DeepPainter_Painter_Classification_Using_Deep_Convolutional_Autoencoders)\nWe can consider max-pooling as a type of non-linear activation function. However, it's [reported](https://ai.stackexchange.com/questions/17937/is-a-non-linear-activation-function-needed-if-we-perform-max-pooling-after-the-c) that using it to replace a non-linearity such as ReLU [affects the network's performance](https://arxiv.org/pdf/1606.02228.pdf). In contrast, average pooling can not be considered as a nonlinear function since it uses all its inputs to produce an output that is a linear combination of its inputs.\nThis covers all the basic building blocks of deep CNNs. Now, let's put them together to create a model. The model we have chosen for this exercise is called a SegNet. We'll discuss it next.\n* * *\n## SegNet: A CNN-based model\n[SegNet](https://arxiv.org/abs/1511.00561) is a deep CNN model based on the fundamental blocks that we have discussed in this article. It has two distinct sections. The bottom section, also called an encoder, down-samples the input to generate features representative of the input. The top decoder section up-samples the features to create per-pixel classification. Each section is composed of a sequence of Conv-BN-ReLU blocks. These blocks also incorporate pooling or un-pooling layers in downsampling and upsampling paths respectively. Figure 6 shows the arrangement of the layers in more detail. SegNet uses the pooling indices from the max-pooling operation in the encoder to determine which values to copy over during the max-unpooling operation in the decoder. While each element of an activation tensor is 4-bytes (32-bits), an offset within a 2x2 square can be stored using just 2-bits. This is more efficient in terms of memory used since these activations (or indices in the case of SegNet) need to be stored while the model runs.\n![Figure 6: The SegNet model architecture for image segmentation. Source: SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/04ch5izpkkQaJuGjH.png)\nFigure 6: The SegNet model architecture for image segmentation. Source: SegNet: [A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation](https://arxiv.org/pdf/1511.00561.pdf)\n[This notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/pets_segmentation/oxford-iiit-pets-segmentation-using-pytorch-segnet-and-depth-wise-separable-convs.ipynb) contains all the code for this section.\nThis model has 15.27M trainable parameters.\nThe following configuration was used during model training and validation.\n  1. The _random horizontal flip_ and _color jitter_ data augmentations are applied to the training set to prevent overfitting\n  2. The images are resized to 128x128 pixels in a non-aspect preserving resize operation\n  3. No input normalization is applied to the images; instead a [batch normalization layer is used as the first layer of the model](https://towardsdatascience.com/replace-manual-normalization-with-batch-normalization-in-vision-ai-models-e7782e82193c)\n  4. The model is trained for 20 epochs using the Adam optimizer with a LR of 0.001 and a StepLR Scheduler that decays the learning rate by 0.7 every 7 epochs\n  5. The cross-entropy loss function is used to classify a pixel as belonging to a pet, the background, or a pet border\n\n\nThe model achieved a validation accuracy of 88.28% after 20 training epochs.\nWe plotted a gif showing how the model is learning to predict the segmentation masks for 21 images in the validation set.\n![Figure 6: A gif showing how the SegNet model is learning to predict segmentation masks for 21 images in the validation set. Source: Author\\(s\\)](https://assets.insightmediagroup.io/media/0*NPAnhNGXXCnP3W_B)\nFigure 6: A gif showing how the SegNet model is learning to predict segmentation masks for 21 images in the validation set. Source: Author(s)\nThe definitions of all the validation metrics are described in [Part-1 of this series](https://medium.com/p/89e8297a0923/).\nIf you'd like to see a fully-convolutional model for segmenting pet images implemented using Tensorflow, please see Chapter-4: Efficient Architectures of the [Efficient Deep Learning Book](https://efficientdlbook.com/#table-of-contents).\n### Observations from model learning\nBased on the development of the predictions that the trained model makes after every epoch, we can observe the following.\n  1. The model is able to learn enough to make the output look in the right ballpark of the pet in the image even as early as 1 training epoch\n  2. The border pixels are harder to segment since we're using an unweighted loss function that treats each success (or failure) equally, so getting the border pixels wrong doesn't cost the model much in terms of the loss. We would encourage you to investigate this and check what strategies you could try to fix this issue. Try using [Focal Loss](https://towardsdatascience.com/focal-loss-a-better-alternative-for-cross-entropy-1d073d92d075) and see how it performs\n  3. The model seems to be learning even after 20 training epochs. This suggests that we could improve validation accuracy if we trained the model longer\n  4. Some of the ground-truth labels themselves are hard to figure out - for example, the mask of the dog in the middle row, last column has a lot of unknown pixels in the area where the body of the dog is occluded by plants. This is very hard for the model to figure out, so one should always expect loss in accuracy for such examples. However, this doesn't mean that the model isn't doing well. One should always spot check the predictions to develop a sense of the model's behavior in addition to looking at the overall validation metrics.\n\n\n![Figure 7: An example of the ground truth segmentation mask containing a lot of unknown pixels. This is a very hard input for any ML model. Source: Author\\(s\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/06KfiVzgGqga_XOry.png)\nFigure 7: An example of the ground truth segmentation mask containing a lot of unknown pixels. This is a very hard input for any ML model. Source: Author(s)\n* * *\n## Conclusion\nIn part-2 of this series, we learned about the basic building blocks of deep CNNs for vision AI. We saw how to implement the SegNet model from scratch in PyTorch, and we visualized how the model trained on successive epochs performs on 21 validation images. This should help you appreciate how quickly models can learn enough to make the output look somewhere in the right ballpark. In this case, we can see segmentation masks that roughly resemble the actual segmentation mask as early as the first training epoch!\nIn the [next part of this series](https://medium.com/p/3534cf04fb89/), we'll take a look at how we can optimize our model for on-device inference and reduce the number of trainable parameters (and hence model size) while keeping the validation accuracy roughly the same.\n* * *\n## Further Reading\nRead more about convolutions here:\n  1. The course titled \"[Ancient Secrets of computer vision](https://pjreddie.com/courses/computer-vision/)\" at The University of Washington taught by Joseph Redmon has an excellent set of videos on Convolutions (especially chapters 4, 5, and 13), which we highly recommend watching\n  2. [A guide to convolution arithmetic for deep learning](https://arxiv.org/abs/1603.07285) (highly recommended)\n  3. <https://towardsdatascience.com/computer-vision-convolution-basics-2d0ae3b79346>\n  4. [The Conv2d layer in PyTorch (documentation)](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html#torch.nn.Conv2d)\n  5. [What do convolutions learn?](https://www.kdnuggets.com/2016/11/intuitive-explanation-convolutional-neural-networks.html/3)\n  6. [Convolution visualizer](https://ezyang.github.io/convolution-visualizer/index.html)\n\n\nRead more about batch normalization here:\n  1. [Batch normalization: Wikipedia](https://en.wikipedia.org/wiki/Batch_normalization)\n  2. [Batch normalization: Machine learning mastery](https://machinelearningmastery.com/batch-normalization-for-training-of-deep-neural-networks/)\n  3. [BatchNorm2d layer in PyTorch here](https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html).\n\n\nRead more about activation functions and ReLU here:\n  1. [ReLU: Machine learning mastery](https://machinelearningmastery.com/rectified-linear-activation-function-for-deep-learning-neural-networks/)\n  2. [ReLU: Wikipedia](https://en.wikipedia.org/wiki/Rectifier_\\(neural_networks\\))\n  3. [ReLU: Quora](https://www.quora.com/Why-is-ReLU-used-so-much-in-neural-networks)\n  4. [ReLU API in PyTorch](https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657076238_edr3rv.jpeg)\nWritten By\n## [Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[See all from Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[Cnn](https://towardsdatascience.com/tag/cnn/)[Convolutional Network](https://towardsdatascience.com/tag/convolutional-network/)[Deep Learning](https://towardsdatascience.com/tag/deep-learning/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)[Pytorch Image Segment](https://towardsdatascience.com/tag/pytorch-image-segment/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fefficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7%2F&title=Efficient%20Image%20Segmentation%20Using%20PyTorch%3A%20Part%202)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fefficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7%2F&title=Efficient%20Image%20Segmentation%20Using%20PyTorch%3A%20Part%202)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fefficient-image-segmentation-using-pytorch-part-2-bed68cadd7c7%2F&text=Efficient%20Image%20Segmentation%20Using%20PyTorch%3A%20Part%202)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2018/10/1VmQFG9-xhcV3ZE9jKS3JKw.jpeg)](https://towardsdatascience.com/make-amateur-radio-cool-again-said-mr-artificial-intelligence-36cb32978fb2/)\n## [\"Make amateur radio cool again\", said Mr Artificial Intelligence.](https://towardsdatascience.com/make-amateur-radio-cool-again-said-mr-artificial-intelligence-36cb32978fb2/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nA project on building a speech recognition system for amateur radio communication.\n[Chris](https://towardsdatascience.com/author/kakittwo/)\nOctober 6, 20183 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/1P9EecL-PWBb9K47eY7vkIw.png)](https://towardsdatascience.com/benchmark-m1-vs-xeon-vs-core-i5-vs-k80-and-t4-e3802f27421c/)\n## [Benchmark M1 vs Xeon vs Core i5 vs K80 and T4](https://towardsdatascience.com/benchmark-m1-vs-xeon-vs-core-i5-vs-k80-and-t4-e3802f27421c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCompare Apple Silicon M1 CPU and GPU performances to high-end configurations on MLP, CNN and LSTM models\n[Fabrice Daniel](https://towardsdatascience.com/author/fabrice-daniel/)\nDecember 26, 20206 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/10/0CfuPm_J-myA3BNwn-scaled.jpg)](https://towardsdatascience.com/how-to-organize-and-track-your-pytorch-training-by-creating-a-run-manager-878cc830ea90/)\n## [How to organize and track your PyTorch training by creating a run manager](https://towardsdatascience.com/how-to-organize-and-track-your-pytorch-training-by-creating-a-run-manager-878cc830ea90/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIf you are searching for a way to organize, manage and log the steps and operations during a training process and don't want to use PyTorch...\n[Tudor Surdoiu](https://towardsdatascience.com/author/dacus-augustus/)\nOctober 4, 20224 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/06/094Pwx0VtVeMGOOo1-scaled.jpg)](https://towardsdatascience.com/tune-deep-neural-networks-using-bayesian-optimization-c9f6503a049f/)\n## [Tune Deep Neural Networks using Bayesian Optimization](https://towardsdatascience.com/tune-deep-neural-networks-using-bayesian-optimization-c9f6503a049f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nLeverage Bayesian Theory to boost your performance\n[Nikos Kafritsas](https://towardsdatascience.com/author/nikoskafritsas/)\nJune 8, 20222 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/10/06p3QmDP9-61JhTuD-scaled.jpg)](https://towardsdatascience.com/shahrukh-khan-face-recognizer-your-4th-cnn-38668dae5afc/)\n## [Shahrukh Khan Face Recognizer - Your 4th CNN](https://towardsdatascience.com/shahrukh-khan-face-recognizer-your-4th-cnn-38668dae5afc/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFourth CNN?\n[Vidisha Jitani](https://towardsdatascience.com/author/vidishajitani/)\nOctober 6, 20204 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/01V9C09FwQjQEGcj1.jpg)](https://towardsdatascience.com/llm-and-gnn-how-to-improve-reasoning-of-both-ai-systems-on-graph-data-5ebd875eef30/)\n## [LLM and GNN: How to Improve Reasoning of Both AI Systems on Graph Data](https://towardsdatascience.com/llm-and-gnn-how-to-improve-reasoning-of-both-ai-systems-on-graph-data-5ebd875eef30/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nArtificial intelligence software was used to enhance the grammar, flow, and readability of this article's text.\n[Anthony Alcaraz](https://towardsdatascience.com/author/alcarazanthony1/)\nDecember 3, 20239 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1uHqlK9f1ZzvC3vNxOj-UWQ.png)](https://towardsdatascience.com/face-mask-detection-using-darknets-yolov3-84cde488e5a1/)\n## [Face Mask Detection using darknet's YOLOv3](https://towardsdatascience.com/face-mask-detection-using-darknets-yolov3-84cde488e5a1/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nCOVID-19: Tutorial on how to build a face mask detector using YOLOv3. *For inference, both video streams and images can be used.\n[Stefanos Kanellopoulos](https://towardsdatascience.com/author/skanelo/)\nApril 12, 20219 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1HW-gsjSyg4k-TwP9SNEdvA.png)](https://towardsdatascience.com/metropolitan-museum-of-art-data-analysis-and-visualization-7d1d023c68fe/)\n## [The Metropolitan Museum of Art Data Analysis and Visualization](https://towardsdatascience.com/metropolitan-museum-of-art-data-analysis-and-visualization-7d1d023c68fe/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAnalyze and Visualize Artists and Artworks Metadata\n[Margaret Maynard-Reid](https://towardsdatascience.com/author/margaretmz/)\nNovember 23, 20203 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/0jp3V1zwOdipUSAK7.jpg)](https://towardsdatascience.com/multiple-gpu-training-in-pytorch-and-gradient-accumulation-as-an-alternative-to-it-e578b3fc5b91/)\n## [Multiple GPU training in PyTorch and Gradient Accumulation as an alternative to it](https://towardsdatascience.com/multiple-gpu-training-in-pytorch-and-gradient-accumulation-as-an-alternative-to-it-e578b3fc5b91/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCode and Theory\n[Alexey Kravets](https://towardsdatascience.com/author/alexml0123/)\nJuly 24, 20237 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/c0bcb16b6731/pages/",
  "body_markdown_path": "attachments/c0bcb16b6731/pages/archived-body.md",
  "local_html": "attachments/c0bcb16b6731/pages/archived-body.html",
  "body_source": "prior_capture"
}