<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jiaen on Medium]]></title>
        <description><![CDATA[Stories by Jiaen on Medium]]></description>
        <link>https://medium.com/@john20050826?source=rss-a590a0c11a1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N_qc2W0ewLGT0M0TwyIcfQ.jpeg</url>
            <title>Stories by Jiaen on Medium</title>
            <link>https://medium.com/@john20050826?source=rss-a590a0c11a1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:36:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@john20050826/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Computer Vision : Chapter 3]]></title>
            <link>https://medium.com/@john20050826/computer-vision-chapter-3-d9e47b7ed9f1?source=rss-a590a0c11a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9e47b7ed9f1</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Jiaen]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 19:04:47 GMT</pubDate>
            <atom:updated>2026-10-08T19:04:47.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srhHjhfjw2B3ccU0dEAFNQ.jpeg" /></figure><h3>Computer Vision : CNN-Based Spatial Understanding Tasks</h3><p>The early success of convolutional neural networks first established deep learning as a powerful machinery for visual recognition, yet classification alone offered only a coarse answer to what an image contained. The next challenge was fundamentally spatial: understanding where objects appeared, how their boundaries were organized, and how their identities persisted through time. Early CNN-based object detection, semantic segmentation, and visual tracking therefore marked a decisive transition from image-level recognition toward structured scene understanding. These models progressively transformed convolutional features into bounding-box hypotheses, dense pixel-wise predictions, and temporally consistent target representations. Although their architectures were often computationally heavy and task-specific, they introduced many of the central ideas that would shape modern computer vision: region-based reasoning, multi-scale representation, fully convolutional prediction, feature correspondence, and learned spatial localization.</p><h3>R-CNN</h3><p>R-CNN, proposed by UC Berkeley at CVPR 2014, emerged from a historical discontinuity in computer vision. By 2010–2012, progress on PASCAL VOC object detection had largely stagnated around systems built from HOG, SIFT, deformable part models, spatial pyramids, and engineered contextual cues. These methods treated representation design as a human task: researchers specified gradients, parts, codebooks, and geometry, while classifiers learned boundaries over fixed descriptors. AlexNet’s 2012 ImageNet result challenged this division of labor by showing that a high-capacity convolutional network could learn increasingly semantic features from large-scale data. The unresolved question was whether classification features could survive the transition from “what is in the image?” to “what is present, and where?” Detection was harder because an image may contain multiple objects at unknown positions, scales, and aspect ratios, while contemporary deep networks had coarse high-level spatial resolution and required fixed-size inputs. Girshick and colleagues therefore decomposed the problem: a class-independent mechanism would hypothesize plausible regions, and a CNN would judge their visual content. R-CNN was not yet a unified detector, but a bridge between bottom-up localization and learned recognition. Its central contribution was to prove that deep features could replace the hand-crafted visual vocabulary constraining detection research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JujbYiM29U4EXfF_Hk5ktg.png" /></figure><p>A region proposal is not a detection; it is a hypothesis that restricts the search space. Its purpose is to preserve high recall — ensuring that almost every object is covered by at least one candidate — while discarding most meaningless windows. Exhaustive sliding-window search samples positions, scales, and aspect ratios nearly blindly, creating a combinatorial burden that forces each classifier to remain cheap. Selective Search instead uses image structure to decide where objects might exist. It begins with an over-segmentation into small regions and performs greedy hierarchical grouping: similarities are computed between adjacent regions, the most similar pair is merged, and similarities are updated until the whole image becomes one region. Every intermediate region becomes a candidate, naturally producing hypotheses from object parts to complete objects and contextual structures. No single cue defines objecthood. Regions may belong together because of color, texture, compatible size, or enclosure, while parts of one object may differ sharply in appearance. Selective Search therefore diversifies its partitions through multiple color spaces, initialization scales, and complementary similarity measures involving color, texture, size, and fill. In R-CNN, fast mode yields roughly 2,000 category-independent proposals per image. The proposal stage is therefore a recall-oriented filter: it decides which regions deserve expensive analysis, while the CNN determines what those regions mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkwCjox2gAM6csAbeVX-pQ.png" /></figure><p>Within R-CNN, the CNN does not discover bounding boxes directly; it acts as a high-capacity representation function applied independently to each proposed region. Every Selective Search box is slightly enlarged to retain context, warped to a fixed 227 × 227 RGB input, and propagated through an AlexNet-like network with five convolutional and two fully connected layers. A 4,096-dimensional feature vector, usually from fc6 or fc7, is then evaluated by one linear SVM per category. A linear SVM was preferred over an additional neural classifier because the CNN had already transformed the raw image into a highly separable representation, making a maximum-margin decision boundary sufficient while preserving the modular training paradigm and enabling effective hard-negative mining over the vast number of background proposals. This modular design assigns distinct roles to each component: proposals encode the prior that objects occupy coherent regions, the CNN learns appearance invariances and semantic compositions, and SVMs impose class-specific boundaries. More importantly, R-CNN established supervised transfer learning as an answer to scarce detection annotations. The network was first trained for ImageNet classification and then fine-tuned using warped PASCAL VOC proposals labeled as object classes or background. Pre-training supplied generic visual primitives; fine-tuning adapted them to cropped objects and detection-specific confusions. Ablation studies showed that much of the representational power resided in convolutional layers rather than the parameter-heavy fully connected layers. Pool5 units captured shapes, textures, colors, materials, faces, text-like structures, and object fragments, while fc6 composed these cues into discriminative region descriptions. Yet classification pre-training also encouraged positional invariance, creating a mismatch with precise localization and explaining the need for bounding-box regression.</p><p>R-CNN produced a decisive empirical break with the preceding detection paradigm. On PASCAL VOC 2010, the system with bounding-box regression reached 53.7% mAP, compared with 35.1% for a method using the same Selective Search proposals but hand-crafted spatial-pyramid and bag-of-visual-words features, and 33.4% for DPM v5. On VOC 2011/2012 it achieved about 53.3% mAP, while on VOC 2007 the fine-tuned fc7 model with bounding-box regression reached 58.5%. Fine-tuning improved detection by roughly eight percentage points, showing that transfer learning reconciled generic recognition with a domain-specific task. Bounding-box regression added about three to four points by correcting imprecise localization, the dominant error mode. The conceptual consequence exceeded the benchmark gain: region-level deep representations were substantially more discriminative than HOG-like features and could support both detection and semantic segmentation. Its weaknesses, however, defined the next research agenda. CNN computation was repeated for approximately 2,000 overlapping regions, requiring about 13 seconds per image on a GPU in the original analysis; training also separated fine-tuning, feature extraction, SVM learning, hard-negative mining, and box regression.</p><h3>SPPnet</h3><p>SPP-net was introduced at ECCV 2014 by Kaiming He and Jian Sun of Microsoft Research Asia, with Xiangyu Zhang of Xi’an Jiaotong University and Shaoqing Ren of the University of Science and Technology of China, in <em>Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition</em>. Its point of departure was a structural contradiction in early CNNs: convolutional layers could naturally process arbitrary image dimensions, yet fully connected layers imposed a fixed input size, forcing images and R-CNN proposals to be warped. The authors recognized this constraint as architectural rather than fundamental, and sought a representation that preserved native geometry while removing repeated regional convolution.</p><p>Spatial Pyramid Pooling (SPP) replaces fixed-size pooling with a hierarchy of adaptive spatial partitions. Given a convolutional feature map of arbitrary dimensions, it divides the map into several grids, such as 1 × 1, 2 × 2, and 4 × 4, performs max pooling within each bin, and concatenates the outputs into a fixed-length descriptor. Its dimensionality depends only on the number of channels and pooling bins, rather than the input resolution. The coarse levels capture global semantic evidence, while finer levels preserve localized activation patterns. SPP therefore allows convolutional networks to accept variable-sized images without destructive cropping, warping, or modification of conventional fully connected classifiers. Conceptually, it transforms pooling from simple downsampling into a multi-resolution representation operator that connects classical spatial pyramid matching with learned convolutional features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUrW9pkZmCxnxATDY1br7g.png" /></figure><p>The pyramid resolves the tension between invariance and spatial discrimination. Global pooling is robust to translation but discards spatial arrangement, whereas a fine grid preserves location but becomes sensitive to geometric variation. Multi-level pooling combines both properties: coarse bins encode object presence and scene context, while finer bins describe part configuration, layout, and asymmetry. Because the output length remains fixed, SPP-net can also alternate between multiple input resolutions during training. This exposes shared convolutional filters to different receptive-field geometries, improves scale robustness, and reduces dependence on a single canonical image size.</p><p>SPP-net’s most important contribution appeared in object detection. Unlike R-CNN, which independently cropped, warped, and processed approximately two thousand overlapping proposals, SPP-net computed convolutional features once for the entire image. Each proposal was then projected onto the shared feature map and converted into a fixed-length regional descriptor through SPP. This substantially reduced redundant convolution and avoided proposal-level geometric distortion. However, the pipeline still depended on external proposals, feature caching, SVM classifiers, bounding-box regression, and stage-wise training that could not effectively fine-tune convolutional layers below SPP. These limitations directly motivated the unified design of Fast R-CNN.</p><p>On PASCAL VOC 2007, the five-scale SPP-net detector reached 59.2% mAP, slightly exceeding R-CNN’s 58.5%, while reducing GPU processing time from about 9 seconds to 0.38 seconds per image — a 24-fold speed-up; the one-scale variant required only 0.14 seconds and achieved 58.0% mAP. The method also improved several CNN architectures in ImageNet classification and placed second in detection and third in classification in the ILSVRC 2014 provided-data tracks. Its historical importance lies in proving that region-based detection need not repeat convolution: shared feature maps could preserve accuracy while collapsing the dominant computational redundancy.</p><h3>Fast R-CNN</h3><p>Fast R-CNN was introduced by Ross Girshick of Microsoft Research in the ICCV 2015 paper <em>Fast R-CNN</em>. The work begins not from dissatisfaction with R-CNN’s accuracy, but from the architectural cost of obtaining it. R-CNN performed an independent convolutional forward pass for every proposal, required separate stages for fine-tuning, SVM fitting, and bounding-box regression, and cached hundreds of gigabytes of intermediate features. SPPnet revealed that convolution could be shared, yet its training procedure could not effectively fine-tune the convolutional layers below spatial pooling. Girshick’s deeper insight was therefore to reorganize detection as one differentiable, image-level computation rather than a proposal-by-proposal classification pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Z5KbrYYzL-WlqADfYOquQ.png" /></figure><h4>Feature Map Computing</h4><p>The decisive change in Fast R-CNN is the relocation of convolution from the region level to the image level. Instead of cropping approximately two thousand proposals and recomputing nearly identical filters for every overlapping region, the network processes the complete image once and produces a single dense convolutional feature map. Region proposals are subsequently projected onto this shared map, so proposals that overlap spatially also reuse the same underlying activations.</p><p>The convolutional backbone therefore constructs one coherent representation of texture, contour, object parts, spatial configuration, and semantic context, while region-specific computation begins only after expensive convolution has been completed. During training, hierarchical mini-batches sample a small number of images and multiple RoIs from each image, permitting both forward and backward computation to be shared. With two images and 128 RoIs, this sampling organization was estimated to be roughly sixty-four times faster than drawing each RoI from a different image. Shared convolution consequently provides not only faster inference, but also a practical mechanism for fine-tuning deep convolutional layers for detection.</p><h4>ROI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuKEGO6Smx_wsKSRQkDNxg.png" /></figure><p>RoI Pooling is the operator that reconciles two incompatible geometries: object proposals possess arbitrary dimensions and aspect ratios, whereas fully connected layers require tensors of fixed spatial size. Each proposal is first mapped from image coordinates onto the shared convolutional feature map, producing a rectangular region of interest. The RoI Pooling layer divides this region into an H × W grid — typically 7 × 7 — and independently applies max pooling within every spatial bin and feature channel. Whether the original proposal is narrow, wide, small, or large, the resulting representation has identical dimensions and can therefore be processed by the same fully connected layers.</p><p>Conceptually, RoI Pooling is a single-level specialization of spatial pyramid pooling, but its role extends beyond dimensional normalization. It transforms a scene-level feature map into a proposal-conditioned representation without repeating convolution. The grid preserves a coarse spatial arrangement of visual evidence, while max pooling retains the strongest activation within each subregion, providing limited tolerance to local translation and deformation. At the same time, it compresses exact spatial detail: a continuous proposal is projected onto a discrete feature lattice and summarized through coarse pooling bins. RoI Pooling thus embodies Fast R-CNN’s central compromise — preserving sufficient spatial organization for recognition and localization while aggressively sharing computation across regions. Crucially, gradients can pass through the selected max-pooling locations, enabling the convolutional representation itself to be adapted through end-to-end detection training.</p><h4>Classification and Bounding-Box Regression</h4><p>For every RoI, the first branch predicts a softmax probability distribution over object categories and a background class. The second predicts class-specific offsets that refine the proposal’s center position, width, and height. A multi-task objective jointly optimizes these outputs, combining a classification log loss with a robust smooth-L1 localization loss. Background regions contribute to classification but not to bounding-box regression because no meaningful target box exists for them.</p><p>This integration carries an important representational consequence. Classification encourages the shared network to encode semantic evidence that distinguishes one category from another, while bounding-box regression requires the same features to preserve information about object extent and boundary displacement. Their gradients converge in the shared fully connected and convolutional layers, allowing recognition and localization to influence the formation of a common visual representation. The paper’s ablation experiments showed that multi-task learning improved classification performance by approximately 0.8–1.1 mAP points and outperformed stage-wise optimization.</p><p>The learned softmax classifier also eliminated the separately trained one-versus-rest SVMs and hard-negative-mining procedure used by R-CNN. Because RoI features are generated, consumed, and differentiated within the same computation graph, they no longer need to be exported to disk for later classifier and regressor training.</p><h4>Results</h4><p>With VGG16, Fast R-CNN achieved 66.9% mAP on PASCAL VOC 2007, compared with 66.0% for R-CNN and 63.1% for SPPnet. On VOC 2012, it reached 65.7% mAP, or 68.4% with additional training data. VGG16 training time fell from 84 hours to 9.5 hours, while inference decreased from 47 seconds to 0.32 seconds per image, or 0.22 seconds with truncated SVD, excluding proposal generation. More fundamentally, Fast R-CNN demonstrated that accuracy and efficiency were not inherently opposed: the real obstacle had been redundant computation and fragmented optimization.</p><h3>Faster RCNN</h3><p>Faster R-CNN was introduced in 2015 by Shaoqing Ren, Kaiming He, Ross Girshick, and Jian Sun at Microsoft Research, in “Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks.” Fast R-CNN had made region-wise classification efficient by sharing convolutional computation, yet its speed remained constrained by Selective Search, an external, hand-engineered CPU procedure. The authors recognized that proposal generation was no longer a preprocessing detail but the dominant systems bottleneck. Their central insight was to learn where objects might exist directly from the detector’s deep feature map, turning proposal generation into a trainable component of the recognition pipeline.</p><h4>Region Proposal Network</h4><p>The Region Proposal Network converts proposal generation from a separate algorithm into a fully convolutional prediction task. A small sliding network traverses the shared feature map, reading a 3 × 3 window at each spatial position and mapping it into an intermediate representation. Two sibling heads then operate on this representation: an objectness classifier estimates whether each candidate corresponds to foreground or background, while a regression head predicts bounding-box corrections. Because these heads are convolutional, the same parameters are reused across all spatial locations, preserving translation-consistent inference. Training employs a multi-task objective coupling binary objectness classification with box regression, so confidence and geometric precision are learned together. After scoring and refinement, non-maximum suppression removes redundant candidates, and only the highest-ranked regions are forwarded to Fast R-CNN. The RPN therefore acts as learned spatial attention: it does not assign semantic categories, but concentrates later computation on regions likely to contain objects efficiently.</p><h4>Anchor Boxes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbGCIBcfIU7wpH0eJho71Q.png" /></figure><p>Anchor boxes provide the geometric reference system that allows the RPN to predict many object hypotheses without scanning an image pyramid. At every feature-map location, Faster R-CNN places nine anchors formed from three scales and three aspect ratios. Each anchor shares the same center but represents a different prior shape; the regression branch predicts relative center, width, and height transformations rather than absolute coordinates. This parameterization makes prediction translation invariant: when an object shifts, the corresponding anchor and proposal shift through the same shared operation. During training, anchors with the highest overlap for a ground-truth object, or with Intersection over Union above 0.7, are labeled positive; anchors below 0.3 are negative, while ambiguous cases are ignored. Anchors are therefore not final detections or rigid templates. They discretize the continuous space of possible boxes into learnable local hypotheses, allowing one compact convolutional head to cover variation in object scale and shape.</p><h4>Shared Convolutional Features</h4><p>Faster R-CNN unifies proposal generation and region classification by letting the RPN and Fast R-CNN consume the same backbone feature map. The paper used a four-step alternating procedure: train the RPN, train Fast R-CNN from its proposals, re-train the RPN while fixing shared layers, and finally fine-tune detector-specific layers. This strategy resolves the circular dependence between changing proposals and detector optimization while producing one shared representation. Proposal generation therefore adds only marginal computation instead of requiring another complete image pass; with VGG-16, the additional RPN layers required approximately ten milliseconds per image across both stages without sacrificing task-specific prediction heads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDzWm67Qsa1hJIYzisFP7w.png" /></figure><h4>Learnable Proposal Quality</h4><p>The significance of the RPN is not that proposals become faster, but that their quality becomes learnable. Selective Search ranks regions through fixed low-level grouping cues, whereas the RPN optimizes objectness and localization using semantic features shaped by detection supervision. Proposal quality can therefore improve with a stronger backbone and with features adapted by the detector itself. The paper showed that VGG-based RPN proposals surpassed those from the shallower ZF network, while sharing detector-tuned convolutional layers improved detection over an unshared configuration. Candidate generation thus became a representation-dependent prediction problem whose recall, ranking, and geometric fidelity co-evolve with the model.</p><h4>Result</h4><p>With VGG-16 and only 300 proposals per image, Faster R-CNN achieved 73.2% mAP on PASCAL VOC 2007 and 70.4% on VOC 2012. The complete shared system required about 198 milliseconds per image on a K40 GPU, corresponding to five frames per second, compared with roughly 1.83 seconds for Selective Search with Fast R-CNN. The lighter ZF configuration reached seventeen frames per second. These results showed that high-quality detection did not require thousands of externally generated regions: a compact, learned proposal set could improve accuracy and efficiency. Faster R-CNN consequently established the two-stage detector as a unified learned system in practice.</p><h3>YOLOv1</h3><p>In 2015, Joseph Redmon and collaborators from the University of Washington, Allen Institute for AI, and Microsoft Research introduced <em>You Only Look Once: Unified, Real-Time Object Detection</em>. Rejecting R-CNN’s multi-stage logic, they reframed detection as global regression, eliminating region proposals, repeated feature extraction, and fragmented optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXOZmh41VQfmCdQh0LwuPQ.png" /></figure><p>YOLOv1 treats an image not as a collection of independently inspected regions, but as one structured visual field. A 448 × 448 image passes through 24 convolutional layers and two fully connected layers, producing a 7 × 7 grid. Each grid cell predicts two bounding boxes, their confidence scores, and conditional class probabilities. Confidence jointly represents object presence and localization quality through predicted IoU, while class probabilities are shared across the boxes assigned to the cell. These outputs form a fixed tensor and are converted into class-specific detection scores before non-maximum suppression. Architecturally, the decisive idea is not any isolated layer, but the removal of the proposal–classification boundary: localization and recognition are learned through one differentiable objective from full-image context. This global reasoning suppresses many background false positives and permits one-pass inference, although the rigid grid, limited box allocation, and coarse spatial resolution constrain crowded scenes and small-object localization.</p><p>On PASCAL VOC 2007, YOLO achieved 63.4% mAP at 45 FPS, while Fast YOLO reached 52.7% mAP at 155 FPS. It was substantially faster than contemporary detectors and generalized strongly to artwork, but remained behind state-of-the-art accuracy. Its characteristic failure mode was localization error: speed came from unified global prediction, while spatial precision was sacrificed by coarse grid assignment and limited bounding-box capacity.</p><h3>SSD</h3><p>Introduced at ECCV 2016 by researchers from Google, the University of North Carolina at Chapel Hill, and the University of Michigan, <em>SSD: Single Shot MultiBox Detector</em> challenged the proposal-driven logic of R-CNN–style detection. The authors recognized that proposal generation, RoI feature extraction, and second-stage classification imposed unnecessary computational separation. Their central insight was to reinterpret detection as dense prediction over structured geometric hypotheses. Localization and recognition are optimized within one convolutional network, so candidate boxes are no longer intermediate proposals: they are the final detections.</p><h4>Proposal-Free Dense Detection with Default Boxes</h4><p>SSD transforms the convolutional hierarchy into a scale-sensitive detection space. High-resolution early maps preserve fine spatial detail, whereas downsampled layers acquire broader receptive fields suited to larger objects. Each location predicts class scores and coordinate offsets for default boxes with prescribed scales and aspect ratios. Although Faster R-CNN also uses anchors, their roles differ: RPN anchors generate class-agnostic proposals that must later be pooled and reclassified, whereas SSD default boxes directly support final category prediction and box regression. Network depth thus becomes an implicit scale axis, coupling receptive-field size, semantic abstraction, and object extent without a separate proposal-and-refinement pipeline.</p><h4>Multi-Scale Feature Prediction and Unified Optimization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2wLg-yp0-SzROY-s_QQsQ.png" /></figure><p>The canonical SSD300 employs a truncated VGG-16 backbone followed by auxiliary convolutional layers of progressively lower resolution. Prediction heads are attached to several layers, including the shallow conv4_3 map. Because conv4_3 activations differ markedly in magnitude from deeper features, SSD applies L2 normalization followed by a learnable scale, stabilizing cross-layer optimization. Ground-truth assignment combines best-match bipartite matching with an IoU threshold: every object is guaranteed one matched box, while additional compatible boxes become positives. This mechanism directly links default-box geometry to the distribution of supervision.</p><p>Dense prediction produces far more background boxes than objects. SSD ranks unmatched boxes by classification loss and retains only the hardest negatives, usually at a 3:1 negative-to-positive ratio. Unlike Faster R-CNN’s proposal sampling, hard-negative mining operates on the final dense classifier, preventing easy background examples from overwhelming the gradient. Localization uses Smooth L1 loss over encoded center and scale offsets, while softmax classification supervises categories and background in a unified multi-task objective. The formulation is efficient, but classification confidence remains only indirectly related to localization quality, motivating later IoU-aware scoring and improved regression losses.</p><h4>Training Strategy &amp; Small-Object Limitations</h4><p>SSD’s augmentation is also structural. Random crops sampled under different minimum-IoU constraints alter object scale, truncation, context, and border placement before resizing, flipping, and photometric distortion. Augmentation therefore changes the distribution of positive default-box matches rather than merely regularizing appearance. SSD nevertheless remains weak on small objects: shallow maps preserve position but lack strong semantics, whereas deeper maps contain semantics after fine structures have been erased. DSSD, FPN-style top-down fusion, higher-resolution heads, and feature-fusion necks can be understood as direct attempts to repair this semantic–spatial mismatch.</p><p>SSD300 achieved 72.1% mAP on PASCAL VOC 2007 at 58 FPS on a Titan X, while SSD500 reached 75.1% mAP and surpassed a comparable Faster R-CNN configuration. Its historical importance lies in establishing a coherent one-stage doctrine: multiscale prediction, final-stage default boxes, explicit sample assignment, hard-negative selection, and joint localization–classification learning could collectively replace proposal-based inference without forfeiting competitive accuracy.</p><h3>Pixel-Level Understanding</h3><p>Segmentation emerged because image classification and bounding-box detection could identify what was present, yet could not explain where each object, surface, or boundary existed. Many systems — medical imaging, autonomous driving, robotics, remote sensing, and image editing — require dense spatial reasoning rather than coarse labels. Researchers were therefore driven by a deeper question: can a model assign semantic meaning to every pixel while preserving object shape and scene structure? This demand transformed vision from recognition into structured scene understanding.</p><h3>FCN</h3><p>Presented at CVPR 2015 by Jonathan Long, Evan Shelhamer, and Trevor Darrell of UC Berkeley, <strong><em>Fully Convolutional Networks for Semantic Segmentation</em></strong> confronted the fragmentation of earlier segmentation pipelines, which relied on patchwise classification, proposals, superpixels, or external refinement. Their decisive insight was to reinterpret classification networks as spatial operators: replace fully connected layers with convolutions, preserve coordinate structure, and train the entire system end-to-end from images to dense pixel labels.</p><h4>Transposed-Convolution Upsampling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vtgQBxoMBuvHlPK87t62g.png" /></figure><p>Classification backbones progressively subsample feature maps, producing semantically strong but spatially coarse score grids. FCN restores image-scale predictions through transposed convolution, described in the paper as backwards strided convolution. Rather than estimating isolated pixels, the operator distributes each coarse activation across a larger output lattice through a convolutional kernel, permitting gradients from pixelwise loss to propagate directly through upsampling. The filters may implement fixed bilinear interpolation or become learnable; in the reported system, final upsampling is fixed to bilinear interpolation, whereas intermediate upsampling layers are bilinearly initialized and subsequently optimized. Upsampling thus becomes part of dense inference, not an external resizing procedure.</p><h4>Skip Connections</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpYkmKa6edRyNnB9UGt8kA.png" /></figure><p>The skip architecture resolves the semantic–localization tension by summing coarse class-score maps with predictions derived from shallower, higher-resolution layers. Deep features determine what is present; pool4 and pool3 restore where it occurs. Importantly, FCN fuses projected score maps rather than concatenating entire encoder tensors.</p><h4>FCN-32s, FCN-16s, and FCN-8s</h4><p>FCN-32s converts VGG16 into a dense predictor whose stride-32 score map is upsampled to the input resolution in one coarse step. FCN-16s first upsamples the conv7 prediction by 2×, sums it with a stride-16 class-score map projected from pool4, and then upsamples the fused output by 16×. FCN-8s repeats this refinement: the fused stride-16 prediction is upsampled by 2×, combined with stride-8 predictions from pool3, and finally enlarged by 8×. This progression is not merely higher-resolution decoding; it is staged reconciliation between global semantic consistency and increasingly precise spatial evidence.</p><p>FCN-8s reached 62.2% mean intersection-over-union on PASCAL VOC 2012, a 20% relative improvement over the preceding SDS system, while reducing inference from roughly 50 seconds to about 175 milliseconds per image. It also achieved leading results on PASCAL VOC 2011, NYUDv2, and SIFT Flow. More consequentially, FCN established semantic segmentation as direct, whole-image, end-to-end dense prediction, becoming the conceptual foundation for later encoder–decoder architectures.</p><h3>DeconvNet</h3><p>Introduced at ICCV 2015 by Hyeonwoo Noh, Seunghoon Hong, and Bohyung Han of POSTECH, <em>Learning Deconvolution Network for Semantic Segmentation</em> challenged coarse decoding logic in FCNs. The authors observed that fixed receptive fields mishandled extreme object scales, while single-step bilinear upsampling erased boundaries and structure. Their response was to treat segmentation as learned spatial reconstruction: recover object geometry progressively through a deep decoder and perform prediction over object-centered region proposals.</p><h4>Unpooling with Pooling Switche</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKxujQ9v5WLHUbpdJOoRlg.png" /></figure><p>Max pooling preserves evidence but discards where that evidence arose, creating a localization deficit unsuitable for dense prediction. DeconvNet therefore records each pooling argmax as a switch variable. During decoding, unpooling returns every retained activation to its original position inside the enlarged feature map, leaving all remaining locations zero. The operation is not itself interpolation: it restores sample-specific spatial traces. Subsequent learned deconvolutions densify this sparse scaffold, converting remembered activation geometry into coherent boundaries, parts, and progressively finer object structure.</p><h4>Symmetric Encoder–Decoder Reconstruction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfZqR9qDIVzjkWD-zwDuRw.png" /></figure><p>DeconvNet places a deep decoder above a VGG-16 encoder, forming a nearly mirrored architecture around the fully connected bottleneck. Whereas the encoder contracts resolution and converts appearance into class-discriminative abstraction, the decoder reverses this trajectory through repeated unpooling, learned deconvolution, batch normalization, and rectification. Reconstruction proceeds coarse-to-fine: lower decoding stages establish location and global silhouette, while higher stages recover class-specific parts and contours. The symmetry is therefore functional, not merely geometric — a deliberate inversion from recognition toward structured, pixel-level generation.</p><p>At inference, DeconvNet segments roughly fifty high-objectness Edge Box proposals and aggregates their class-score maps, allowing differently sized proposals to normalize object scale and reveal fine structures. DeconvNet obtained 69.6% mIoU on PASCAL VOC 2012; a fully connected CRF refined boundaries to 70.5%. EDeconvNet denotes probability-map averaging with FCN-8s, whose global contextual bias complements proposal-wise detail, reaching 71.7%. Applying CRF after this ensemble produced EDeconvNet+CRF at 72.5%, the strongest result reported without additional training data on that benchmark setting.</p><h3>SegNet（2015）</h3><p>Developed by <strong>Vijay Badrinarayanan, Alex Kendall, and Roberto Cipolla at the University of Cambridge</strong>, SegNet was introduced in <em>“SegNet: A Deep Convolutional Encoder-Decoder Architecture for Image Segmentation.”</em> The work addressed dense scene understanding under severe memory and computational constraints. Its central insight was that spatial structure discarded by max-pooling could be preserved cheaply, avoiding parameter-heavy learned upsampling while retaining boundary information.</p><p>SegNet treats <strong>max-pooling indices as a compressed spatial memory</strong> linking encoder and decoder. During encoding, each pooling operation records the location of the maximum activation rather than preserving full-resolution feature maps. The decoder reuses these indices to place activations during non-linear unpooling, restoring spatial support before convolution. This transfers geometric localization with almost negligible additional memory and no learned upsampling parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81dkbxc38awHUASobac4Ig.png" /></figure><p>SegNet’s decoder differs fundamentally from both DeconvNet and FCN. FCN primarily restores resolution through learned transposed convolution and combines coarse semantic maps with earlier encoder features through skip fusion. DeconvNet also employs pooling switches, but uses a substantially larger decoder architecture. SegNet instead performs index-guided unpooling followed by convolution, deliberately prioritizing memory efficiency, architectural symmetry, and deployment-oriented dense prediction. SegNet was evaluated on road-scene and indoor semantic segmentation, including CamVid and SUN RGB-D, where accurate delineation of vehicles, pedestrians, roads, buildings, and object boundaries is essential. It achieved competitive segmentation accuracy while requiring markedly less inference memory than architectures storing encoder feature maps. Its significance therefore lay not merely in accuracy, but in demonstrating that spatial localization can be recovered through compact structural metadata.</p><h3>U-Net（2015）</h3><p>U-Net was introduced in 2015 by Olaf Ronneberger, Philipp Fischer, and Thomas Brox at the University of Freiburg in <em>“U-Net: Convolutional Networks for Biomedical Image Segmentation.”</em> Confronting scarce annotations and the localization–context trade-off of sliding-window CNNs, they reframed segmentation as dense, end-to-end prediction, extending fully convolutional learning with a symmetric reconstruction path designed for data efficiency and spatial precision.</p><h4><strong>Symmetric Encoder–Decoder</strong></h4><p>U-Net forms a nearly symmetric encoder–decoder: the contracting path repeatedly downsamples while increasing channel capacity to encode broader semantic context; the expansive path upsamples these compressed representations and restores resolution. This symmetry is functional: the decoder preserves substantial feature capacity, allowing high-level context to survive reconstruction rather than collapsing into coarse interpolation.</p><h4><strong>Long Skip Connections</strong></h4><p>Long skip connections transfer high-resolution encoder features directly to decoder stages at matching scales, shortening the route for spatial detail. Unlike FCN skip fusion, which mainly <strong>sums class-score predictions</strong> from coarse and shallow layers, U-Net <strong>concatenates feature tensors</strong>, preserving richer spatial representations and allowing subsequent convolutions to learn how localization should interact with context.</p><h4><strong>Feature Concatenation and Precise Localization</strong></h4><p>At each decoding stage, the upsampled representation is concatenated with the correspondingly cropped encoder feature map. Fine edges, textures, and morphology lost through pooling are reintroduced beside deeper semantic context. Subsequent convolutions reinterpret both sources jointly, making reconstruction a learned integration process that recovers sharper boundaries rather than merely enlarging coarse predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58vyIMUT68n2YASf99Ty4w.png" /></figure><p>U-Net targets biomedical regimes where exhaustive annotation is expensive and datasets may contain only dozens of labeled images. Augmentation therefore becomes a source of learned invariance: rotations, shifts, intensity variation, and especially elastic deformations simulate plausible tissue morphology. Biological variability is thus encoded as synthetic supervision, reducing dependence on newly acquired manual labels. U-Net proved effective in neuronal membrane and light-microscopy cell segmentation. On the ISBI EM challenge, it achieved 0.000353 warping error, outperforming the earlier sliding-window CNN; on PhC-U373 and DIC-HeLa, IoU reached 0.9203 and 0.7756. These results established U-Net as a data-efficient architecture for precise biomedical dense prediction.</p><h3>DeepLab v1（2014）</h3><p>Google researchers introduced DeepLab in <em>Semantic Image Segmentation with Deep Convolutional Nets and Fully Connected CRFs</em>, confronting CNNs’ intrinsic localization loss. DeepLab replaces excessive downsampling with atrous convolution, enlarging the effective receptive field while preserving denser spatial resolution and computational efficiency. Yet semantic activations remain spatially coarse; a fully connected CRF therefore couples pixels through appearance and positional affinities, restoring sharp object boundaries and enforcing fine-scale local consistency beyond CNN predictions. On PASCAL VOC 2012 semantic segmentation, DeepLab established state-of-the-art performance, reaching 71.6% IoU while markedly improving boundary localization accuracy.</p><h3>DeepLab v2（2016）</h3><p>DeepLab v2 emerged from a 2016 Google–UCLA-led collaboration in <em>DeepLab: Semantic Image Segmentation with Deep Convolutional Nets, Atrous Convolution, and Fully Connected CRFs</em>. Beyond DeepLab v1’s localization problem, the authors recognized a deeper limitation: objects inhabit radically different spatial scales, demanding representations that preserve resolution while reasoning across multiple receptive fields.</p><h4><strong>Atrous Spatial Pyramid Pooling</strong></h4><p>Atrous Spatial Pyramid Pooling transforms multi-scale reasoning into a parallel feature-sampling problem. Instead of repeatedly resizing the input image, ASPP applies several atrous convolutions to the same feature map, each observing a distinct effective field-of-view. The architecture therefore extracts scale-diverse semantic evidence without repeatedly recomputing the entire backbone.</p><h4><strong>Multi-scale Context</strong></h4><p>Semantic segmentation requires more than local appearance: a pixel’s identity often depends on structures extending far beyond its immediate neighborhood. DeepLab v2 treats context as explicitly scale-dependent. ASPP allows fine structures, complete objects, and surrounding scene evidence to coexist within one representation, making recognition less dependent on any single spatial extent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3gjLHykVBaeH7gdbjSf-g.png" /></figure><p>Different dilation rates define distinct spatial sampling lattices over the same feature tensor. Small rates emphasize comparatively local evidence; larger rates sparsely sample wider regions and enlarge the effective receptive field. Their parallel composition approximates a family of scale-specific observers, allowing the network to decide which contextual extent best explains each semantic structure. DeepLab v2 further replaced the earlier VGG-16 backbone with ResNet-101. Rather than accepting classification networks’ severe 32× spatial downsampling, later strides are suppressed and atrous convolution preserves receptive-field coverage while producing responses every eight pixels. Residual depth strengthens semantic abstraction without sacrificing the spatial density required for pixel-level prediction.</p><p>The resulting system advanced semantic segmentation across PASCAL VOC 2012, PASCAL-Context, PASCAL-Person-Part, and Cityscapes. With multi-scale representation, ResNet features, atrous convolution, and DenseCRF refinement, DeepLab reached <strong>79.7% mIoU on PASCAL VOC 2012 test</strong>, establishing ASPP as a foundational design for subsequent multi-scale dense-prediction architectures.</p><h3>ParseNet（2015）</h3><p>Developed by Wei Liu and Alexander C. Berg at UNC Chapel Hill with Andrew Rabinovich of Magic Leap, <em>ParseNet: Looking Wider to See Better</em> (2015; ICLR 2016 Workshop) challenged FCN’s locally biased prediction. Its key insight was that theoretical receptive fields did not guarantee effective global perception, motivating scene-level context.</p><p>ParseNet extracts a global context vector by spatially averaging the final convolutional feature map. This image-level descriptor summarizes scene-wide semantic evidence, is L2-normalized with a learnable scale, then replicated across spatial positions. Each pixel therefore receives not merely its local activation, but a compact representation of the entire visual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lukiqNt_g7SR2xM3xi1P3A.png" /></figure><p>The replicated global descriptor is concatenated with each location’s normalized local feature, allowing pixel classification to condition on both appearance and scene identity. This resolves ambiguities where locally similar regions imply different classes under different environments. Crucially, normalization prevents unequal feature magnitudes from letting one cue dominate optimization during fusion.</p><p>ParseNet established explicit image-level context as a first-class segmentation signal, anticipating later pyramid pooling and richer multi-scale context aggregation mechanisms. Applied to semantic scene parsing, ParseNet achieved state-of-the-art results on SIFT Flow and PASCAL-Context, while approaching state of the art on PASCAL VOC 2012. Its gains demonstrated that inexpensive global conditioning could substantially improve dense prediction without elaborate graphical post-processing.</p><h3>Transitional Models Toward Instance Segmentation</h3><h4><strong>SDS — Simultaneous Detection and Segmentation (2014)</strong></h4><p>Hariharan et al. introduced <em>Simultaneous Detection and Segmentation</em>, reframing recognition beyond bounding boxes by demanding a category label and pixel mask for every object instance. Building on R-CNN and region proposals, SDS coupled bottom-up candidates with category-specific top-down figure–ground refinement, establishing instance segmentation as a distinct structured recognition problem.</p><h4><strong>Hypercolumns (2015)</strong></h4><p>Hypercolumns exposed a representational mismatch inside CNNs: deep layers know what an object is but lose where its boundaries lie, while shallow layers preserve geometry without semantics. By concatenating multi-layer activations at each pixel, Hariharan et al. created semantically informed, spatially precise descriptors, substantially improving SDS-style mask localization and fine-grained prediction.</p><h4><strong>DeepMask (2015)</strong></h4><p>DeepMask shifted instance segmentation toward learned class-agnostic mask proposals. Pinheiro, Collobert, and Dollár jointly trained one branch to predict an object mask and another to estimate whether a patch contains a centered object. This replaced handcrafted edges and superpixels with discriminative representation learning, yielding higher recall with fewer proposals and generalization to unseen categories.</p><h4><strong>SharpMask (2016)</strong></h4><p>SharpMask addressed DeepMask’s coarse masks by recognizing that object identity emerges in deep features whereas boundary fidelity survives in earlier layers. Its bottom-up/top-down refinement pathway progressively fused coarse mask encodings with finer features. The resulting proposals became sharper, faster, and more accurate, improving average recall by roughly 10–20% while reducing inference cost.</p><h3>Tracking Task Basics</h3><p>Single-object tracking begins with a target specified in the first frame, typically by a bounding box. The tracker must subsequently localize the same instance without further annotation. This formulation transforms tracking into sequential state estimation, where temporal continuity provides supervision but prediction errors can recursively contaminate future target representations.</p><p><strong>Tracking-by-detection</strong> reframes localization as repeated discrimination between the target and surrounding candidates. Rather than explicitly modeling motion alone, the tracker learns or updates an appearance-based decision function that selects the most plausible target region in each frame. This paradigm enabled strong integration with modern visual representations, correlation filters, and deep networks. Its central weakness is recursive dependency: inaccurate detections corrupt model updates, creating feedback loops that progressively amplify localization error and ultimately cause drift.</p><p>Tracking is fundamentally challenged by non-stationary target appearance, partial or complete occlusion, geometric scale changes, and background ambiguity. These factors weaken feature consistency across time. Incorrect adaptation can then reinforce contaminated observations, producing model drift. Robust trackers therefore require representations that balance invariance, discriminability, temporal adaptation, and resistance to unreliable updates.</p><h3>DLT（2013）</h3><p>Naiyan Wang and Dit-Yan Yeung at Hong Kong University of Science and Technology introduced DLT in “Learning a Deep Compact Image Representation for Visual Tracking” (NeurIPS 2013). Confronting one-shot supervision, handcrafted descriptors, and fragile online appearance models, they reframed tracking as transfer: learn generic nonlinear representations offline, then adapt them.</p><h4><strong>Stacked Denoising Autoencoder</strong></h4><p>DLT pretrains a stacked denoising autoencoder on auxiliary natural images, forcing corrupted inputs to reconstruct clean appearances through progressively compressed nonlinear layers. This denoising objective learns robust, reusable structure rather than object-specific templates. The encoder is then transferred into tracking and fine-tuned online, coupling unsupervised generic visual priors with target-specific adaptation under severely limited labeled supervision during deployment in practice.</p><h4><strong>Online Classification and Particle Filtering</strong></h4><p>During tracking, the pretrained encoder gains a sigmoid classifier separating target from background. A particle filter proposes affine-state hypotheses; network confidence supplies their observation likelihood, while low confidence triggers online fine-tuning to accommodate appearance change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQgrvfsknqxWYzHeZKLlYA.png" /></figure><p>DLT marks a transition from handcrafted tracking features toward learned representation spaces. Deep learning was not yet an end-to-end temporal predictor; instead, a pretrained nonlinear encoder became the appearance model within a classical tracking pipeline. Across ten sequences, DLT reached 85.5% average success, 7.3-pixel error, and about 15 fps, demonstrating practical robustness to illumination, occlusion, pose change, and rapid motion.</p><h3>SO-DLT（2015）</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CBKKEDt6u_xApcyx_LzWA.png" /></figure><p>HKUST and CMU researchers introduced SO-DLT in <em>Transferring Rich Feature Hierarchies for Robust Visual Tracking</em>, addressing DLT’s pretraining, unstructured classification. SO-DLT transfers an objectness-pretrained structured CNN into tracking, producing dense probability maps rather than isolated class scores. Online fine-tuning specializes generic features to the target. Two coupled models resolve the update dilemma: CNN-S aggressively follows short-term variation, whereas CNN-L updates conservatively to preserve stable identity. Their confidence-based collaboration balances rapid adaptation against accumulated drift under uncertain observations and background distraction. By separating rapid adaptation from conservative memory, SO-DLT resists deformation, occlusion, scale variation, and clutter; on OTB, AUC rises from 0.529 to 0.602, improving robustness against appearance-driven drift.</p><h3>MDNet（2015）</h3><p>Nam and Han at Seoul National University proposed <strong>“Learning Multi-Domain Convolutional Neural Networks for Visual Tracking” (CVPR 2016)</strong>, reframing tracking as transferable representation learning across heterogeneous video domains.</p><p>MDNet separates <strong>generic visual representation</strong> from <strong>sequence-specific discrimination</strong>. Convolutional layers are shared across training videos, forcing the network to encode appearance structures transferable among targets, while each video owns an independent classification branch distinguishing its target from background. This multi-domain objective prevents overfitting to particular sequences and converts tracking knowledge into a reusable feature space for unseen objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0eRGk60kK9vu9icAFlHig.png" /></figure><p>At test time, the shared representation initializes a new target-specific classifier that is <strong>online fine-tuned</strong> using samples from the current sequence. Hard negative mining repeatedly selects background candidates producing high target confidence, concentrating optimization on ambiguous distractors and sharpening the decision boundary against visually similar objects encountered during tracking.</p><p>MDNet achieved exceptional tracking accuracy and robustness, establishing deep online adaptation as a strong paradigm, but expensive fine-tuning limited speed while incorrect updates could progressively induce model drift.</p><h3>GOTURN（2016）</h3><p>Developed by Stanford’s Vision and Learning Lab, GOTURN appeared in “Learning to Track at 100 FPS with Deep Regression Networks” (ECCV 2016), replacing slow online-trained trackers through offline motion learning.</p><h4><strong>End-to-End Bounding-Box Regression</strong></h4><p>GOTURN reformulates tracking as direct bounding-box regression. Instead of scoring candidate windows or optimizing an online classifier, a feed-forward convolutional network maps paired visual crops directly to target coordinates, collapsing localization into a single inference pass and thereby replacing iterative search with learned geometric prediction conditioned on object appearance priors.</p><h4><strong>Previous-Frame Target &amp; Current-Frame Search Region</strong></h4><p>At each timestep, GOTURN receives two inputs: a crop of the target from the previous frame and a larger search region from the current frame. Separate convolutional streams encode appearance, their features are fused by fully connected layers, and regression predicts the target’s new bounding box within that search region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6Si7cheosnGwKTw3psHsQ.png" /></figure><p>This design enabled approximately 100-FPS tracking without online fine-tuning, making GOTURN attractive for latency-critical robotic and real-time vision systems. Its offline training also generalized to previously unseen object categories; however, limited explicit temporal memory and weak occlusion handling made performance vulnerable to abrupt motion, disappearance, severe deformation, and distribution shift.</p><h3>SiamFC（2016）</h3><p>Bertinetto et al. at Oxford’s Visual Geometry Group proposed “Fully-Convolutional Siamese Networks for Object Tracking” (2016), reframing tracking from continual model adaptation into learned generic similarity matching.</p><h4><strong>Siamese Shared-Weight Backbone</strong></h4><p>SiamFC employs two identical convolutional branches with strictly shared parameters, forcing exemplar and candidate regions into a common embedding space. Rather than learning object-specific classifiers online, the backbone learns a transferable similarity representation offline, where geometrically corresponding visual patterns become directly comparable through the same hierarchical feature transformation.</p><h4><strong>Exemplar, Search Image, and Cross-Correlation Response Map</strong></h4><p>A compact exemplar crop encodes the target appearance, while a larger search image represents plausible locations in the subsequent frame. Their feature tensors are cross-correlated, producing a dense response map whose spatial maxima indicate target displacement. Tracking therefore becomes localization through feature-space similarity rather than explicit proposal generation or classification.</p><h4><strong>Fully Convolutional Matching</strong></h4><p>The fully convolutional formulation makes the learned similarity function translation-equivariant: shifting the target within the search region correspondingly shifts the response peak. Because one exemplar representation can be correlated across every candidate position simultaneously, SiamFC replaces exhaustive sliding-window evaluation with a single dense computation, yielding an unusually elegant localization mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IyLUuAggGFkQIvXM3zErw.png" /></figure><p>SiamFC learns its matching function entirely offline from large-scale video pairs and requires no gradient-based adaptation during tracking. This separation enables roughly real-time operation at 86 FPS while retaining competitive accuracy. Its success established Siamese similarity learning as a foundational paradigm for later trackers, including SiamRPN and SiamMask.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9e47b7ed9f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on “Attention Is All You Need”]]></title>
            <link>https://medium.com/@john20050826/notes-on-attention-is-all-you-need-7f052ff690d2?source=rss-a590a0c11a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f052ff690d2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Jiaen]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 18:34:51 GMT</pubDate>
            <atom:updated>2026-08-15T17:41:28.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xwciovW7JAgkClYpkLpbw.png" /></figure><h3>Foreword</h3><p>The value of reading <em>Attention Is All You Need</em> lies not only in understanding the structure of the Transformer, but also in seeing how deep learning redesigned sequence modeling. Previous RNNs and LSTMs relied on temporal recurrence. Although they could process sequences, they were limited by difficulties in parallelization, excessively long paths for transmitting long-range information, and challenges in gradient learning; convolutional sequence models improved parallel computation, but still required stacking multiple layers to establish long-range relationships. The Transformer replaced recurrence with Self-Attention, allowing arbitrary positions to interact directly while substantially improving training efficiency and model scalability, thereby laying the foundation for subsequent large language models, Vision Transformers, and multimodal models.</p><p>However, the Transformer is not without limitations. Full attention has O(n²) computational and memory costs, making it significantly expensive for long sequences; autoregressive generation remains constrained by token-by-token decoding; and its weaker local inductive bias also means that it generally requires more data and training resources. The key to understanding this paper is not merely memorizing its modules, but grasping how it achieves a new balance among representational capacity, parallelization, computational cost, and structural bias.</p><h3>Time Complexity, Memory, and Parallelization Considerations</h3><p>When comparing Transformers, RNNs, and LSTMs, one cannot focus solely on the asymptotic computational complexity with respect to sequence length (N). A common statement is that Self-Attention has (O(N²)) complexity, whereas RNNs or LSTMs have (O(N)) complexity, and therefore linear models should be more efficient for long sequences. However, total computation is only one aspect of efficiency; whether the computation can be parallelized is equally important.</p><p>The hidden state of an RNN satisfies (h_t=f(h_{t-1},x_t)), so the (t)-th time step must wait for the computation of (h_{t-1}) to finish. Even though the total computation increases linearly with sequence length, the critical computational path along the sequence dimension remains (O(N)), making it impossible to process all tokens within the same sample simultaneously on a GPU. As the sequence becomes longer, training also requires storing intermediate states from more time steps for backpropagation, further increasing memory usage and limiting batch size. At this point, the model is constrained by both “the inability to parallelize within a sequence” and “reduced batching across samples,” making hardware utilization more likely to decline.</p><p>The Transformer, by contrast, removes recurrent dependencies within each layer. For a single Self-Attention layer, the Query, Key, and Value of all tokens can be computed simultaneously through matrix operations. Although the attention matrix introduces (O(N²)) computational and memory costs, these operations are highly regular and well suited to large-scale parallel processing on GPUs and TPUs. Therefore, the Transformer essentially replaces fewer operations that must be executed sequentially with more operations that can be executed in parallel.</p><p>This also explains why model efficiency should be evaluated by considering total FLOPs, sequential depth, memory access, activation storage, batchability, and hardware utilization together, rather than judging solely by (O(N)) or (O(N²)).</p><h3>Token Relationship Distance</h3><p>Although convolutional sequence models such as ConvS2S and ByteNet can compute all positions in parallel, information between two distant positions still needs to be transmitted through multiple convolutional layers. The path length in ConvS2S increases linearly with distance, whereas ByteNet reduces it to a logarithmic scale through dilated convolution; therefore, long-range dependencies may still be more difficult to learn. The Transformer’s Self-Attention allows any two positions to interact directly within a single layer, reducing the information transmission path to a constant scale.</p><p>However, this form of global aggregation also comes at a cost. The output of a single attention head is a weighted average of the values at multiple positions, so different sources, syntactic roles, or semantic relationships may be mixed into the same vector, resulting in reduced effective resolution. The purpose of Multi-Head Attention is to allow different heads to learn different attention patterns in different representation subspaces, enabling local relationships, long-range dependencies, and semantic roles to be modeled separately. In other words, multi-head attention does not eliminate weighted averaging; instead, it distributes information aggregation across multiple relational channels to reduce information entanglement within a single representation.</p><h3>Scaled Dot-Product Attention &amp; Multi-Head Attention</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfguEEGXRLH0ypZkxpboqA.png" /></figure><h4>The Physical Meaning of Q, K, and V</h4><p>The core of Attention can be understood as a process of “searching for information according to a need, and then retrieving that information.” Query, Key, and Value are not three different types of input data; rather, they are three different functional roles that the model assigns to sequence representations.</p><p>Query (Q) represents the information need of the current position, namely, “what am I looking for right now?” When the model updates the representation of a token, that token generates its own Query to search for positions in the sequence that are relevant to the current need.</p><p>Key (K) represents the features by which each position can be matched, namely, “by what features can I be found?” The Query is compared with all Keys to determine the degree of relevance between each position and the current need.</p><p>Value (V) represents the actual content provided by a position, namely, “what information should I transmit when I am attended to?” The Key is only responsible for matching, while the Value is the information that is ultimately retrieved through weighting. Although the two usually come from the same token, they serve different functions: the Key is similar to an index, while the Value is similar to the actual content pointed to by that index.</p><p>Therefore, the core logic of Attention can be summarized as follows: use the Query and Key to compute relationships, and then aggregate the Values according to the relationship weights. It should be noted that the physical meanings of Q, K, and V are not manually specified fixed grammatical rules, but representation spaces learned by the model through task training.</p><h4>How Are Q, K, and V Generated?</h4><p>Q, K, and V usually do not directly use the original token embeddings, but are generated by applying three different linear projections to the input representations:</p><p>Q = X_Q W_Q</p><p>K = X_K W_K</p><p>V = X_V W_V</p><p>where W_Q, W_K, and W_V are learnable parameters. Even if all three come from the same input X, they must pass through different projections, because the same token needs to emphasize different features when acting as an information requester, a matching index, and an information provider.</p><p>In Encoder Self-Attention, Q, K, and V all come from the same encoder hidden representation, so every input position can attend to other input positions.</p><p>In Decoder Masked Self-Attention, Q, K, and V likewise come from the decoder’s current representation, but a causal mask is added so that position t can only attend to itself and previous tokens, and cannot access future information.</p><p>In Encoder–Decoder Cross-Attention, Q comes from the decoder, while K and V come from the encoder output. Its physical meaning is that the decoder issues a query according to its current generation state, and then searches for and retrieves information from the source sequence represented by the encoder.</p><p>Therefore, the main difference between Self-Attention and Cross-Attention lies not in the computational formula, but in the data sources of Q, K, and V.</p><h4>Why Can the Physical Meaning of Q, K, and V Hold?</h4><p>The roles of Q, K, and V as “posing a need, providing an index, and providing content” do not mean that the model possesses human-like understanding, but are a functional division formed by the computational graph. The input representation X is transformed into Q, K, and V through three sets of learnable linear projections; Q and K participate only in similarity computation and determine the attention weights between positions, while V is weighted and aggregated after the weights have been determined. Therefore, operationally, Q controls “which features should be used for searching,” K controls “whether a position can be matched,” and V determines “which information is actually transmitted after matching.”</p><p>These roles are not prewritten into the vectors, but are gradually learned through backpropagation from the loss of the final task. When the model selects the wrong position or transmits ineffective information, the prediction error updates W_Q, W_K, and W_V separately, causing the query conditions, matching features, and transmitted content to move in directions that are more helpful for the task. In other words, the architecture first specifies how information flows, and training then determines what representations each channel carries.</p><p>Separating Q, K, and V also removes the constraint between “how to find information” and “what to transmit after finding it.” The same token may be matched because of its syntactic role, while the information that actually needs to be transmitted may concern number, semantics, or reference. Different projections can map the original hidden state into different functional subspaces, making attention a differentiable, input-dependent information retrieval mechanism.</p><p>Therefore, the physical meanings of Q, K, and V are real at the functional level, but this does not mean that a particular dimension has a fixed and directly interpretable human meaning. They are usually distributed and context-dependent representations. Attention succeeds precisely because its matching, weight allocation, and information aggregation are all differentiable, allowing end-to-end learning to automatically form information-routing rules that are most effective for reducing task error.</p><h4>Scaled Dot-Product Attention</h4><p>Scaled Dot-Product Attention is the underlying computational unit of a single attention head, and its formula is:</p><p>Attention(Q, K, V) = Softmax((QK^T / √d_k) + M)V</p><p>The first MatMul computes QK^T. The element q_i · k_j in the matrix represents the matching score between the i-th Query and the j-th Key. This step constructs a relationship matrix between all query positions and all positions that can be queried.</p><p>The scores are then divided by √d_k. As the Key dimension d_k increases, the numerical magnitude and variance of the vector dot products also increase, causing Softmax to easily produce an excessively sharp distribution and enter a saturated region with smaller gradients. The scaling operation controls the numerical scale of the attention logits, making training more stable.</p><p>The Mask is added before Softmax. The padding mask is used to mask PAD tokens that are added to equalize sequence lengths; the causal mask is used in an autoregressive decoder and sets the scores of future positions to extremely negative values, making their weights approach zero after Softmax.</p><p>Softmax normalizes the matching scores into attention weights, so that the weights assigned by each Query to all Keys sum to 1. These weights can be viewed as the proportions of information retrieved by the current position from different positions.</p><p>Finally, the second MatMul is performed, multiplying the attention weights by V. If the weight matrix is A, the output is A V. For a single position, the output is the weighted sum of all Values. Therefore, the first MatMul is responsible for “determining whom to attend to,” while the second MatMul is responsible for “retrieving what information from the attended positions.”</p><p>Scaled Dot-Product Attention solves the problem of information matching and aggregation within a single relationship channel.</p><h4>Multi-Head Attention</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdJIn91a2U6dRsI_RD2L7A.png" /></figure><p>A single Scaled Dot-Product Attention produces only one attention distribution and mixes the information from all attended positions into the same output vector. However, a token may need to process local syntax, long-range dependencies, reference relationships, and semantic roles at the same time. If all relationships are represented by a single attention head, different types of information can easily become entangled, reducing the effective resolution of the relationships.</p><p>Multi-Head Attention therefore projects Q, K, and V into multiple different representation subspaces. For the i-th head:</p><p>Q_i = QW_i^Q</p><p>K_i = KW_i^K</p><p>V_i = VW_i^V</p><p>Each head independently performs Scaled Dot-Product Attention:</p><p>head_i = Attention(Q_i, K_i, V_i)</p><p>Different heads can learn different matching rules and information channels. For example, some heads may favor neighboring words, while others may attend to long-range dependencies or specific syntactic relationships. However, these functions are not specified in advance, but emerge automatically from the data.</p><p>The results of all heads are concatenated along the feature dimension and then passed through the output projection W_O:</p><p>MultiHead(Q, K, V) = Concat(head_1, …, head_h)W_O</p><p>Concat preserves the information extracted by different heads, while W_O remixes the different subspaces so that multiple relationships jointly form the final output representation.</p><p>Therefore, Scaled Dot-Product Attention and Multi-Head Attention are not two mutually substitutable methods. The former is the core relationship computation within a single head, responsible for matching the Query with the Key and aggregating the Value; the latter is a complete module composed of multiple Scaled Dot-Product Attention operations in parallel, used to improve the model’s ability to represent different positions, different relationships, and different representation subspaces. The attention blocks actually placed in the encoder and decoder layers of a Transformer are usually Multi-Head Attention.</p><h4>Why Is Multi-Head Attention Needed?</h4><p>Although a single attention head can view the entire sequence at once, it has only one set of Q, K, and V projections, one attention map, and one weighted-average result. For a given position, the output is the weighted sum of all Values. Therefore, when the model simultaneously requires information about the subject, object, local modifiers, and long-range references, these different types of information are mixed into the same vector. This is precisely what the paper means by “With a single attention head, averaging inhibits this”: the weighted averaging of a single head inhibits the model’s ability to preserve multiple independent relationships simultaneously.</p><p>Multi-Head Attention allows each head to have different Q, K, and V projections, so each head can understand tokens in a different representation subspace. Some heads may favor local syntax, while others learn long-range dependencies, semantic relationships, or reference structures. The key point here is not merely “looking at different positions,” but observing the same sequence through different feature coordinate systems.</p><p>The outputs of the heads are ultimately integrated through Concat and an output projection, allowing multiple relationships to be preserved in parallel rather than being prematurely compressed into a single weighted average. Therefore, the essence of multi-head attention is to decompose complex relationship modeling into multiple low-dimensional subproblems, thereby improving representational resolution, separability, and relationship-modeling capability.</p><h3>Model Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*djqaaU9knkb9GUPTV6J8vg.png" /></figure><h3>Position-wise Feed-Forward Networks</h3><p>The Position-wise Feed-Forward Network (FFN) independently applies the same two-layer fully connected network to the representation of each token in the sequence. Its core form is:</p><p>FFN(x) = activation(xW₁ + b₁)W₂ + b₂</p><p>“Position-wise” means that different positions do not exchange information within this module; each token processes only its own current features, while all positions share the same set of parameters. Therefore, it can be viewed as a transformation applied along the feature dimension, conceptually similar to a 1×1 convolution in a CNN.</p><p>Within a Transformer block, Attention and the FFN serve different functions. Attention is responsible for information transmission and aggregation between tokens, determining which other positions each position should attend to; the FFN is responsible for nonlinear recombination, feature enhancement, and semantic transformation of the aggregated representation. The original Transformer expands the dimension from d_model to d_ff and then compresses it back to d_model, for example, 512 → 2048 → 512. This design of first increasing and then reducing the dimensionality allows the model to separate and combine features in a higher-dimensional space.</p><p>Therefore, the FFN is not an auxiliary module, but a primary nonlinear computational unit in the Transformer. It can be understood simply as follows: Attention is responsible for “where to obtain information from,” while the FFN is responsible for “how to process the information after it has been obtained.”</p><h3>Transformer Architecture, Softmax, FFN, and the Complexity Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*Y5xjh5bmRDnXsNKFBZd4QA.png" /></figure><p>The overall Transformer pipeline can be divided into three parts: the input, Transformer blocks, and the output. Input tokens first pass through an embedding layer, are multiplied by √d_model, and then have positional encoding added to them. Multiplication by √d_model is used to adjust the numerical scale of the embeddings so that the content representation is not dominated by the positional encoding.</p><p>Each encoder layer contains Multi-Head Self-Attention and a Position-wise FFN; each decoder layer contains Masked Self-Attention, Encoder–Decoder Cross-Attention, and an FFN. Therefore, the FFN is present in every layer of both the encoder and the decoder. Attention is responsible for information exchange between different tokens, while the FFN independently performs nonlinear feature transformation on the representation at each position.</p><p>There are two types of Softmax in the paper. The Attention Softmax is located after QK^T / √d_k and is used to generate attention weights over positions; the final output Softmax of the decoder is located after the vocabulary linear projection and is used to convert logits into probabilities for the next token. The two have the same mathematical form, but operate on different objects.</p><p>The paper also shares one set of weights among the encoder embedding, decoder embedding, and pre-softmax linear projection, which is known as weight tying. During input processing, the matrix is used to look up token embeddings, while during output processing, its transpose is used to project the decoder hidden state into the vocabulary space.</p><p>Table 1 compares different sequence information-exchange mechanisms rather than the complete Transformer architecture. Self-Attention has a per-layer complexity of O(n²d), but all positions can be computed in parallel, so the number of sequential operations is O(1). Any two positions can also interact directly within a single layer, so the maximum path length is O(1). Although an RNN has a complexity of O(nd²), it must compute one step at a time, so both its sequential operations and maximum path length are O(n). Convolution can be computed in parallel, but long-range information still needs to be transmitted through multiple layers. Restricted Self-Attention attends only to r neighboring positions, reducing the computational cost to O(rnd), but increasing the maximum path length to O(n/r).</p><p>The FFN is not included in the table because it is not responsible for information transmission between tokens and only performs feature transformation within each position. The primary cost of a complete Transformer block can be approximated as O(n²d + ndd_ff).</p><h3>Positional Encoding</h3><p>The Transformer does not have the temporal recurrence of an RNN, nor does it have the local convolutional ordering of a CNN. Therefore, Self-Attention alone cannot naturally distinguish the sequential positions of tokens. To preserve sequence order, the model adds positional encoding to the token embeddings, allowing each position to contain both content information and positional information:</p><p>Input = Token Embedding × √d_model + Positional Encoding</p><p>The original Transformer uses sine and cosine functions to construct positional encodings. Different dimensions use different frequencies, giving each position a unique representation and allowing the model to infer relative distances through linear relationships. Its design is as follows: even-numbered dimensions use sine, while odd-numbered dimensions use cosine. Low-frequency dimensions describe positional changes over longer distances, whereas high-frequency dimensions are more sensitive to nearby positions.</p><p>Positional Encoding itself does not change the number of tokens or directly perform information exchange. Instead, it provides the coordinate signals required for attention to determine order and distance. The original paper tested learned positional embeddings and fixed sinusoidal encodings, and the two achieved similar performance; the advantage of using a fixed form is that it can extrapolate to sequences longer than those encountered during training.</p><h3>Why Self-Attention</h3><p>The core value of Self-Attention lies in simultaneously improving long-range dependency modeling, parallelization capability, and information transmission paths. An RNN must update its hidden state sequentially, so as sequence length increases, training becomes difficult to parallelize, and long-range information must pass through multiple time steps. Although a CNN can be computed in parallel, it is constrained by its local receptive field, so two distant positions usually still require multiple stacked convolutional layers to interact.</p><p>Self-Attention allows every token to directly establish relationships with other positions in the sequence. Therefore, the maximum path length between any two positions is O(1), which is beneficial for learning long-range dependencies. All positions within the same layer can also be computed simultaneously, reducing sequential operations to O(1). The cost is that full Self-Attention must construct an n × n relationship matrix, resulting in computational and memory complexity of O(n²d).</p><p>Therefore, the design focus of Self-Attention is not simply to reduce the total amount of computation, but to exchange a larger amount of highly parallelizable computation for global information exchange, short transmission paths, and better hardware utilization. This is also an important reason why the Transformer was able to replace traditional recurrent sequence models.</p><h3>Training</h3><p>The original Transformer was primarily trained on the WMT 2014 machine translation datasets. The English–German dataset contains approximately 4.5 million sentence pairs and uses shared Byte-Pair Encoding (BPE) to construct a vocabulary of approximately 37,000 tokens; the English–French dataset contains approximately 36 million sentence pairs and uses a word-piece vocabulary of approximately 32,000 tokens. To improve batching efficiency, sentences of similar lengths are placed in the same batch, with each batch containing approximately 25,000 source tokens and 25,000 target tokens.</p><p>The model was trained using 8 NVIDIA P100 GPUs. The Base model was trained for a total of 100,000 steps, requiring approximately 12 hours; the Big model was trained for 300,000 steps, requiring approximately 3.5 days. The optimizer was Adam, with parameters β₁ = 0.9, β₂ = 0.98, and ε = 10⁻⁹. The learning rate was not fixed. Instead, it first increased linearly during the first 4,000 warmup steps, and then gradually decreased according to the inverse square root of the step number. This design prevents excessively large updates during the early stages of training while allowing more refined convergence after the model stabilizes.</p><p>For regularization, the paper uses residual dropout, applying dropout to the output of each sublayer and to the result after adding the embeddings and positional encodings; the dropout rate of the Base model is 0.1. The model also uses label smoothing, with the label smoothing coefficient set to 0.1, so that the target distribution is no longer an absolute one-hot distribution. This slightly increases perplexity, but improves accuracy and BLEU because the model does not become overly confident in a single answer. Overall, the focus of the Training section is not only the hardware and hyperparameters, but also how token-based batching, the warmup learning-rate schedule, dropout, and label smoothing allow the highly parallelized Transformer to complete training quickly and stably.</p><h3>Results</h3><p>The Transformer demonstrated performance superior to the recurrent and convolutional models of the time on the WMT 2014 machine translation tasks, while significantly reducing training costs. In English–German translation, Transformer Big achieved a BLEU score of 28.4, exceeding the previous best result, including ensembles, by more than 2 BLEU points. Even the smaller Base model outperformed existing models while requiring less training computation. For English–French translation, the Big model achieved a BLEU score of 41.0, outperforming all single models at the time, with a training cost of less than one quarter of that of the previous best model. During inference, checkpoint averaging, a beam size of 4, and a length penalty of 0.6 were used.</p><p>The model variation experiments were used to verify the importance of each component. A single attention head achieved approximately 0.9 BLEU lower than the best multi-head configuration, demonstrating that multi-head representations are indeed beneficial. However, when the number of heads becomes too large and the dimension of each head becomes too small, quality also declines. Reducing the key dimension harms performance, indicating that learning Query–Key compatibility is not a simple problem. Increasing model depth, representation dimensionality, or FFN dimensionality generally improves results, while dropout is highly important for suppressing overfitting. Fixed sinusoidal positional encodings and learned positional embeddings perform almost identically. Overall, the results demonstrate that the advantages of the Transformer arise not only from model scale, but also from the architectural design jointly formed by multi-head attention, sufficient representational capacity, and appropriate regularization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f052ff690d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision : Chapter 2]]></title>
            <link>https://medium.com/@john20050826/computer-vision-chapter-2-ae8862523e01?source=rss-a590a0c11a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae8862523e01</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Jiaen]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 15:14:25 GMT</pubDate>
            <atom:updated>2026-07-04T15:14:25.108Z</atom:updated>
            <content:encoded><![CDATA[<h3>Computer Vision : The foundational history of CNNs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kV3ALwYiIs1Ht6p-pta3Xw.jpeg" /></figure><p>Following the remarkable breakthrough of AlexNet discussed in the previous article, the emergence of ImageNet and AlexNet ignited the deep learning revolution, spurring extensive research on convolutional neural networks (CNNs). This included architectural innovations such as Inception, as well as approaches like ResNet that improved information propagation, enabling much deeper networks to be trained effectively. These diverse studies focused on increasing network depth, introducing residual connections, and addressing the vanishing gradient problem, ultimately establishing CNNs as the dominant approach for large-scale image classification. This article provides an in-depth exploration of several historically significant papers and examines the development and applications of key convolutional neural network architectures in image recognition.</p><h3>ZF-Net &amp; Visualizing CNNs</h3><p>In 2013, Matthew D. Zeiler and Rob Fergus (NYU) improved upon AlexNet and introduced ZFNet. Their model won the ILSVRC 2013 competition, and they published the research paper *Visualizing and Understanding Convolutional Networks. The name ZFNet is derived from the authors’ surnames, Zeiler and Fergus.</p><p>The most significant contribution of this work was not merely the improvement of AlexNet. Rather, it addressed the long-standing ”black box” problem of training deep convolutional neural networks (CNNs). By introducing a novel visualization technique, the researchers were able to reveal the functions of intermediate feature layers and the internal mechanisms of the classifier. This shifted CNN research toward greater interpretability, enabling researchers to clearly understand what each layer had actually learned during the training process.</p><h4>Visualization Technology:</h4><p>They proposed a visualization technique using a multilayer deconvolutional network (deconvnet). This technique was derived from Adaptive Deconvolutional Networks for Mid and High Level Feature Learning, proposed by Zeiler and Fergus in 2011, and aimed to learn interpretable mid- and high-level feature representations from images. The study continued the handcrafted feature design approach represented by SIFT and HOG in traditional computer vision. However, unlike manually defined histograms of oriented gradients, the authors employed a deconvolutional network to automatically learn features resembling edges, corners, and local structures in a data-driven manner. The model uses deconvolution and sparsity constraints to project high-level features back into the image space, enabling the learned representations to correspond to specific image structures. Consequently, it retains the interpretability of SIFT/HOG while overcoming the limitations of handcrafted design and restricted scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*rRxx62CGHZq9gP6tilGJ9g.png" /></figure><p><strong>Un-Pooling<br></strong>During forward propagation, the Max Pooling operation compresses the feature map by selecting the maximum value within a local region (e.g., 2x2) and records the positions of these maximum values (referred to as “switches”). During the reverse process of Deconvolution, Un-Pooling uses these switches to place the activation values back into their original positions, while filling the remaining positions with 0. This is not a strict inverse operation, but rather an approximate reconstruction used to upsample a low-resolution feature map back to a higher resolution.</p><p><strong>Rectification<br></strong>ZFNet (based on AlexNet) uses the ReLU activation function (f(x) = max(0, x)) in each layer to ensure that the output is non-negative. During the backward process, ReLU is likewise applied to maintain consistency, that is, max(0, x) is taken element-wise on the feature map after Un-Pooling. This step is essentially the same as the forward activation and only ensures the non-negativity of the reconstructed values, rather than performing an exact inverse transformation.</p><p><strong>Filtering / Deconvolution<br></strong>A transposed convolution operation is used, in which the trained filter weights are flipped vertically and horizontally (equivalent to transposing the filters), and then convolved with the feature map after Rectification to simulate the inverse mapping of the forward convolution. This further enlarges and refines the feature map, thereby back-projecting high-level activations into the input image space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y261bk3DXo8FbY3qkAaKDA.png" /></figure><h4>ZF-Net</h4><p>Through deconvolution visualization techniques, they examined the sensitive regions of the input image for different convolution kernels and found that AlexNet’s design used an excessively large stride and convolution kernel size in the first layer, causing detailed information to be overly compressed at an early stage. This visualization analysis enabled them to adjust the convolution kernel size and stride configuration based on experimental evidence and optimize the hyperparameter design, ultimately developing an architecture with better performance on ImageNet and achieving a Top-5 accuracy of 88.3% on ImageNet. The significance of ZFNet lies not only in its performance improvement, but also in demonstrating the research methodology of “using interpretability to provide feedback for model design,” which laid a key foundation for the subsequent improvement of deep learning architectures.</p><p><strong>CNN Visualization Effects<br></strong><a href="https://github.com/utkuozbulak/pytorch-cnn-visualizations">https://github.com/utkuozbulak/pytorch-cnn-visualizations</a> (Author : <strong>Utku Ozbulak</strong> )</p><h3>VGG-Net</h3><p>VGG-Net is a series of convolutional neural network models proposed by Simonyan &amp; Zisserman of the Oxford Visual Geometry Group. In 2014, they published the paper Very Deep Convolutional Networks for Large-Scale Image Recognition. They investigated the impact of convolutional neural network depth on the accuracy of large-scale image recognition tasks and achieved excellent performance on ImageNet in 2014. Their submitted experimental results achieved a Top-5 accuracy of 92.7%, ranking 2nd in the ILSVRC 2014 Classification competition that year, and became a classic template for deep learning architecture design. Its deepest architecture is shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Egm568GieuY7qLCNswdrpQ.png" /><figcaption>VGG 19 Architecture Diagram (Adapted from A VGG-19 Model with Transfer Learning and Image Segmentation for Classification of Tomato Leaf Disease)</figcaption></figure><p>VGGNet has many different architectures, such as VGG11, VGG13, VGG16, and VGG19, which differ in the number of network layers (the number of convolutional layers and fully connected layers). The commonly used VGGNet refers to VGG16, whose architecture uses five convolutional layers and three fully connected layers. The first two convolutional layers contain 2 basic modules, while the last three convolutional layers contain 3 basic modules, resulting in a total of 2x2 + 3x3 + 3 = 16 network layers. Compared with AlexNet, the improvement of VGG is the use of multiple consecutive 3 x 3 convolutional filter kernels to replace the larger convolutional kernels in AlexNet ( 11 x 11 、 7x 7 、 5 x 5 ).</p><p>For the given structural features, using stacked small convolution kernels is superior to using large convolution kernels, because the stacking of multiple nonlinear layers can increase the depth of the network, thereby ensuring that the model can learn more complex features, while using fewer parameters to reduce the computational complexity of the network. In terms of architecture design, using three 3x3 convolution kernels in VGG can replace one 7x7 convolution kernel, and using two 3x3 convolution kernels can replace one 5x5 convolution kernel. The advantage of doing so is that it can increase the depth of the network architecture while ensuring that the network architecture has an equivalent receptive field, thereby improving model performance to a certain extent. For example, in the practical use of this scheme that uses multiple small convolution filters to achieve an equivalent large receptive field, the stacking of three 3x3 convolution kernels with a stride of 1 can be regarded as a receptive field with a convolution kernel size of 7x7. The total number of parameters in the stacking of these three small convolution filters is 27 x C x C ( C is the number of input and output Channels), whereas directly using a 7x7 convolution kernel results in 49 x C x C parameters. Therefore, this approach can directly reduce the number of parameters and further preserve image characteristics. At the same time, the number of ReLU operations in the network is also increased, improving the model’s expressive capability and gradient flow. However, increasing the depth of the network and using parameter-intensive fully connected layers also lead to high storage and training costs, resulting in problems such as unstable training, high memory requirements, and long training time.</p><h3>Network in Network (NIN)</h3><p>In early 2014, Lin et al. proposed the novel deep network architecture NIN, which uses fewer parameters than AlexNet, enhances the model’s ability to distinguish local regions within the receptive field, and achieves higher accuracy. The authors believed that the features to be extracted are generally highly nonlinear; therefore, they introduced more complex neural networks for computation within each local receptive field and proposed the MLP convolutional layer (Mlpconv) to replace traditional filters, enabling feature extraction from local linearity to local complex nonlinearity. Mlpconv refers to replacing the original single convolutional layer with a small network contained within the local receptive field of each convolutional layer. The first layer performs a standard convolution operation, while the subsequent layers mix and weight the parameters from the previous layer, which is equivalent to a 1x1 convolution operation. The second and third 1x1 convolutional layers are used to integrate feature information across channels, while reducing the number of training parameters and implementing channel dimensionality reduction or expansion. The overall NIN architecture design is similar to AlexNet. The convolutional layer in the first layer is used for spatial feature extraction. The first Mlpconv uses an 11x11 convolution kernel, the second Mlpconv uses 5x5, and the third Mlpconv uses 3x3. NiN consists of three Mlpconv layers and one Global Average Pooling layer, with each Mlpconv followed by a Maxpooling layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4R5C_v1sPc0L7XaeY_8OZA.png" /><figcaption>Taken from the paper “Network In Network”</figcaption></figure><p>Here, NIN uses GAP instead of fully connected layers, which can significantly reduce the number of parameters while preserving the overall semantic intensity of each feature map and also avoiding the problem of overfitting. In the final convolutional layer output, each feature map represents a type of high-level feature. GAP does not connect to a fully connected layer; instead, it takes the average value of all spatial positions in each feature map. Assuming that the output size is H×W×C, GAP averages the H×W values of each channel, ultimately obtaining a 1×1×C vector that directly corresponds to the scores of C classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*Equ65Ix7117VoNRau7m6ow.png" /></figure><h3>GoogLeNet (Inception V1)</h3><p>The GoogLeNet architecture was proposed by Christian Szegedy et al. from the Google AI team in 2014. It originated from the paper Going Deeper with Convolutions and won first place in the image classification task of that year’s ImageNet competition. Based on biological neural systems and the intuition of multi-scale processing, it further introduced the Inception module to integrate feature information at different scales. GoogLeNet was designed to address issues related to power consumption and memory efficiency and to improve the utilization of computational resources within the network. According to the original paper, the number of parameters in its ILSVRC 2014 submitted model was reduced by approximately 12 times compared with AlexNet, proposed by Krizhevsky et al. in 2012, while achieving better performance on the ImageNet classification task. It achieved an ImageNet Error (top-5) of 6.67%, equivalent to a Top-5 accuracy of 93.33%, and won the ILSVRC 2014 championship.</p><h4>Inception Module</h4><p>Larger models usually imply more parameters, which makes the expanded network more prone to overfitting, especially when the number of labeled samples in the training set is limited. Another disadvantage of the uniform growth of network scale is that it leads to a sharp increase in computational resource consumption. When two convolutional layers are connected in series, any uniform increase in the number of filters will cause the computational cost to grow quadratically. In practical applications, computational resources are always limited, so the efficient allocation of computational resources should be prioritized. The paper argues that the fundamental way to solve the problem is ultimately to move from the uniform, dense connection pattern in convolutional layers toward structured local sparse connections, imitating biological neural systems. The research by Arora et al. provides mathematical theoretical support, showing that the distribution of data can inherently be represented by a very large but highly sparse deep neural network. By analyzing the correlations among the neuron outputs of the previous layer and grouping neurons with highly correlated outputs, these groups then form the connection structure of the next layer, so the optimal network topology can be constructed layer by layer, forming an efficient and reasonable network structure. However, the problem is that CPUs and GPUs are very poor at handling irregular sparse structures, and the engineering cost of sparse models is also very high, which is a fatal disadvantage in large-scale visual systems. The more regular the structure of a convolutional network is and the more it conforms to dense characteristics, the more smoothly the hardware can operate. The authors raise the core question here: whether there can be an architecture that theoretically makes greater use of sparsity while still using “dense matrix” computation in practice. In the literature on sparse matrix computation, a common technique is to divide the entire sparse matrix into multiple relatively dense submatrices, so that the sparse structure can be preserved while high-speed dense computation can still be used. This idea is very likely to be applied in the future to the automatic generation of non-uniform deep network architectures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GABU1U9D00tK0dVr28U0Lw.png" /><figcaption>Adapted from “Going Deeper with Convolutions”</figcaption></figure><p>Therefore, the main idea of the Inception architecture is how to use existing dense components to approximate and cover the optimal local sparse structure in convolutional visual networks. Convolution kernels of 1×1 / 3×3 / 5×5 are selected as local structures to capture low-level features and high-level features, and finally all these layers and their output filter banks are concatenated after this layer. However, 5×5 convolution kernels face the problem of extremely high computational cost. The authors introduce the second key idea, using 1×1 convolution kernels together with ReLU as dimensionality reduction modules, compressing before computationally expensive operations, reducing the number of channels and projecting them into a lower-dimensional space to eliminate computational bottlenecks, otherwise these bottlenecks would limit the scale of the network. This makes it possible to increase not only the depth of the network, but also its width. These Inception modules are stacked, with max-pooling interspersed between them to reduce spatial resolution. Such an architecture can greatly increase the number of channels while keeping computation manageable, and it has a theoretical multi-scale visual intuition, simultaneously extracting small-range detailed features and large-range structural features, thereby building a scalable and efficient deep network without violating hardware constraints.</p><h4>GoogLeNet Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*1m5eSvrrqrZgGPqAuFPByw.png" /></figure><p>The input is a 224×224 RGB mean-subtracted image. When only layers with parameters are counted, the network has a depth of 22 layers, or 27 layers including pooling. The authors observed that average pooling provided a slight performance improvement compared with fully connected layers, improving top-1 performance by approximately 0.6%. Considering the difficulty of gradient propagation in deep networks, Auxiliary Classifiers were introduced into the architecture to force intermediate layers to learn classifiable features, increase the gradient signal during backpropagation, and provide a regularization effect. During training, the loss consists of the main loss and two auxiliary losses, each with a weight of 0.3, while the auxiliary classifiers are not used during inference. In addition, Global Average Pooling（GAP）was introduced in the GoogLeNet architecture to replace traditional large fully connected layers. It performs global averaging on each feature channel, allowing each channel to correspond to a class score. This design greatly reduces the number of model parameters and the risk of overfitting, while reducing the model’s dependence on a fixed spatial size, enabling the network to accept input images of different sizes within a certain range. At the same time, it strengthens the correspondence between feature map channels and semantic classes, thereby improving overall generalization ability.</p><pre>class Inception_block(nn.Module):<br>    def __init__(self, in_channels, out_1x1, red_3x3, out_3x3, red_5x5, out_5x5, out_pool):<br>        super(Inception_block,self).__init__()<br>        # reduction : red , Number of channels compressed before convolution<br>        self.branch1 = conv_block(in_channels, out_1x1, kernel_size=1)<br>        self.branch2 = nn.Sequential(<br>            conv_block(in_channels, red_3x3, kernel_size=1),<br>            conv_block(red_3x3, out_3x3, kernel_size=3, padding=1)<br>        )<br>        self.branch3 = nn.Sequential(<br>            conv_block(in_channels, red_5x5, kernel_size=1),<br>            conv_block(red_5x5, out_5x5, kernel_size=5, padding=2)<br>        )<br>        self.branch4 = nn.Sequential(<br>            nn.MaxPool2d(kernel_size=3, stride=1, padding=1),<br>            conv_block(in_channels, out_pool, kernel_size=1)<br>        )<br>    def forward(self, x):<br>        branch1 = self.branch1(x)<br>        branch2 = self.branch2(x)<br>        branch3 = self.branch3(x)<br>        branch4 = self.branch4(x)<br>        outputs = [branch1, branch2, branch3, branch4]<br>        return torch.cat(outputs, 1)</pre><h3>Batch Normalization</h3><p>After pioneering the Inception module, the GoogLeNet team began considering how to optimize the network architecture to make training more stable. GoogLeNet combines convolutions of multiple different scales in parallel through the Inception module, improving performance while substantially reducing the number of parameters and computational cost, successfully demonstrating the advantages of deep networks with a wide architecture. However, as the network became deeper and more modules were stacked, instability during training still remained, particularly because the input distributions of each layer continued to change throughout training, limiting the model’s convergence speed and making it highly sensitive to the learning rate and initialization. To address the instability of deep network training, the Google team proposed the batch normalization mechanism in the paper Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift and fully integrated it into the Inception-based GoogLeNet architecture, also known as BN-Inception. Batch Normalization standardizes the distributions of intermediate features over each mini-batch, reducing internal covariate shift during training, enabling the model to use larger learning rates and accelerate convergence, while reducing dependence on initialization and strong regularization techniques, making it an important foundation for deep network training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*ESXpD7viGfJsnfDrDuXdbA.png" /></figure><h3>Inception V2/V3</h3><p>Following the emergence of the Inception module, the VGG model, and their variants in 2014, GoogLeNet’s architectural design and optimization concepts were able to substantially reduce the number of parameters in the entire network architecture while achieving very strong learning and generalization capabilities. This made it possible to use Inception networks in big data scenarios, enabling large amounts of data to be processed at a reasonable cost, or in scenarios where memory or computational capacity itself is limited. However, the complexity of the Inception architecture makes network modification more difficult. If the architecture is simply scaled up, most of its computational advantages may be immediately lost, making it difficult to maintain network efficiency when applying it to new domains. In the study “Rethinking the Inception Architecture for Computer Vision” published in 2015 by Christian Szegedy et al. from the Google AI team, the new Inception V2/V3 network architectures were proposed, together with several general principles and optimization ideas. These principles and ideas have been shown to be highly useful for scaling convolutional networks efficiently. These principles are not limited to Inception-type networks, but the general structure of Inception-style building modules is sufficiently flexible. Because Inception modules make extensive use of dimensionality reduction and parallel structures, they can reduce the impact of structural changes on neighboring components and can incorporate these constraints more naturally.</p><ol><li>Avoid premature appearance of the characterization bottleneck<br>In a feedforward network, information flows from the input layer to the output layer. If the intermediate layers compress information excessively, a bottleneck will form and limit performance. Ideally, the representation dimensionality should decrease gradually and smoothly as the number of layers increases, rather than shrinking abruptly. Although dimensionality cannot fully represent the amount of information, it can serve as a rough reference.</li><li>High-dimensional representations are easier to process locally.<br>In convolutional networks, increasing the number of channels in each block can produce more disentangled feature representations, making the network easier to learn and accelerating the training process.</li><li>First reduce dimensions, then aggregate spatially.<br>Before performing convolution over a larger region, such as 3×3, the feature dimensionality can first be reduced, usually without a significant loss of representational capability. Because adjacent features are highly correlated, the information loss caused by dimensionality reduction is limited, while learning efficiency can be improved.</li><li>Balance the width and depth of the network.<br>Optimal performance is achieved by increasing both the network width (the number of filters in each layer) and depth (the number of network layers). Under fixed computational resources, the resources should be distributed evenly between width and depth rather than increasing only one of them.</li></ol><h4>Inception V2</h4><p>At the architectural level, Inception V2 further strengthens computational efficiency and representational capability within the BN-Inception architecture. First, drawing on the design philosophy of the VGG network, it replaces the original 5×5 convolution with two 3×3 convolutions, which not only reduces the number of parameters and computational cost, but also increases the number of nonlinear layers and improves feature abstraction capability. This convolution factorization concept became an important design principle for subsequent Inception series. In addition, traditional convolutional neural networks usually reduce the spatial resolution of feature maps through pooling operations. To avoid a representational bottleneck ( representational bottleneck ), the number of filter channels is usually expanded before performing max pooling or average pooling, but this brings an extremely large computational cost burden, with a complexity of approximately 2*d²⋅k². Another possible approach is to use a stride=2 convolution to replace the original convolution-plus-pooling process, reducing the computational cost to one quarter of the original, with the complexity expressed as (d/2)² * 2k. However, this causes a representational bottleneck and reduces the expressive capability of the network. Therefore, Inception V2 redesigned the downsampling module and proposed another improved method called Efficient Grid Size Reduction, making the dimensionality reduction process itself a learnable multi-branch structure. During downsampling, V2 simultaneously introduces a stride=2 3×3 convolution C branch and a stride=2 pooling (MaxPooling) P branch, and finally concatenates the outputs of each branch along the channel dimension. This design allows the model to retain discriminative features learned through convolution while reducing spatial resolution, avoiding the information loss caused by single-path compression, and making the feature representation more diverse and stable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*snP-sKdbNkqjnPcXGFMygA.png" /><figcaption>Adapt from “ Rethinking the Inception Architecture for Computer Vision “</figcaption></figure><h4>Inception V3</h4><p>From Inception V2, it is known that decomposing a large convolution kernel into multiple 3x3 convolution kernels can reduce computational cost. Based on this idea, further consideration was given to whether it could be decomposed into even smaller convolutions. After conducting experiments, they proposed improving the network architecture using the Spatial Factorization into Asymmetric Convolutions technique. Theoretically, any n×n convolution can be factorized into a 1×n convolution layer followed by an n×1 convolution layer, and as n increases, the proportion of computational savings becomes more significant. If a 3x3 convolution layer is factorized into 1x3 and 3x1 convolution layers, the computational cost can be reduced by 33%; however, if it is factorized into two 2x2 convolution layers, the computational cost can only be reduced by 11%. At the same time, the experiments found that asymmetric convolutions are not suitable for convolutional layers in the early stages, but perform better on feature maps with sizes ranging from 12 to 20. In particular, using a combination of 1×7 + 7×1 convolutions on medium-sized 17x17 feature maps in the intermediate layers can achieve very good results at this stage. In addition, based on the network design principle that higher-dimensional features are easier to process and beneficial for training, the study introduced a structure that increases the network width in the 8x8 convolutional layer to generate high-dimensional features. Generating high-dimensional sparse representations is the most critical aspect, and the proportion of local processing through 1 × 1 convolutions is used to increase relative spatial aggregation. Furthermore, in each Inception module of Inception V3, in addition to multiple convolution branches, an Average Pooling branch is also retained (usually followed by a 1×1 convolution layer). The purpose of this branch is not merely dimensionality reduction, but to provide a smoother method of feature aggregation, allowing information within a region to be integrated in an averaged form and avoiding the information bias caused by relying solely on the maximum response value. By concatenating the outputs of the convolution branches and the average pooling branch along the channel dimension, the model can simultaneously preserve strong features and the overall semantic distribution, making the feature representation more stable and diverse. It is worth noting that Max Pooling is used only in the Reduction modules that perform spatial size reduction to strengthen salient features, whereas Average Pooling is primarily used within the Inception modules to preserve more background and semantic information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqTL0reKxDIKmxX61vqKew.png" /><figcaption>Adapt from “ Rethinking the Inception Architecture for Computer Vision ”</figcaption></figure><p>V3 further refined the factorization approach into 1×n + n×1 asymmetric convolutions and incorporated several training techniques (Auxiliary Classifiers, Label Smoothing Regularization, and the RMSprop optimizer) to further improve CNN training methods, thereby achieving more stable convergence, generalization, and accuracy.</p><p><strong>Auxiliary Classifiers Improvements </strong>( BN-auxiliary )<strong><br></strong>The GoogLeNet literature introduced the concept of auxiliary classifiers to improve the convergence and gradient propagation problems of deep networks. However, experiments showed that whether they were included during the early stages of training had limited impact on the convergence speed, with similar learning curves; models with side branches achieved slightly higher accuracy in the later stages, but removing the lower-level branch did not affect the final performance, indicating that auxiliary classifiers may not necessarily strengthen low-level feature learning. Overall, auxiliary classifiers are more likely to serve a regularization function. When Batch Normalization or dropout was added to the side branches, the main classifier performed better; adding Batch Normalization to the auxiliary classifier at the 17×17 feature map could improve the ImageNet Top-1 accuracy by approximately 0.4%.</p><p><strong>Label Smoothing Regularization (LSR)</strong><br>In addition, the paper introduced Label Smoothing as a regularization strategy. Its core approach is to replace the original one-hot target distribution, in which the correct class is assigned 1 and all others are assigned 0, with a smoother probability distribution. For example, the correct class is assigned 1−ε, while ε is evenly distributed among the remaining classes. This approach prevents the model from becoming overly confident in a single class, reduces the risk of overfitting, and improves model calibration. Experimental results showed that Label Smoothing consistently improves the model’s generalization performance on ImageNet.</p><p><strong>RMSprop Optimizer Recommendation</strong><br>The authors recommend using RMSprop as the primary optimizer to improve the training stability of large models. By scaling the gradients through an exponential moving average of the squared gradients, it can automatically adjust the learning rate for each parameter, reduce oscillations, and accelerate convergence. Compared with traditional SGD, RMSprop is easier to tune for the high-dimensional and structurally complex Inception v3, particularly when combined with Batch Normalization and large-batch training, where it can significantly improve convergence quality and enhance final accuracy.</p><p><strong>Inception V3 Network Architecture<br></strong>In the design of the Inception network architecture, the Inception modules maintain the feature map size for feature extraction, while the Reduction modules are responsible for downsampling and reducing the feature map size. By maintaining the feature map size, the network can repeatedly observe details at high resolution and fully extract features, preventing small objects or detailed information from disappearing too quickly. Features are extracted multiple times at the same scale until they have been sufficiently transformed, after which dedicated Reduction modules are used to reduce the size. Under a fixed computational cost, this forms a clear multi-scale hierarchical structure that maximizes representational capability. When the feature map sizes differ, the appropriate convolution factorization strategies also differ. For ImageNet, the InceptionV3 architecture designs three types of Inception modules, each adopting a different structure, while Efficient Grid Size Reduction is used to reduce the feature map size. The input size is also changed to 299 x 299 and divided into three spatial stages for feature extraction. Module A: 35×35 Feature Map Size. At this stage, the spatial size is still large, and large kernels are computationally expensive. Therefore, small 3 x 3 kernels are mainly used, with 1×1, 3×3, and two stacked 3×3 convolutions being suitable, while increasing representation richness. Module B: 17×17 Feature Map Size stage. Asymmetric convolutions are most effective on medium-sized grids, so this stage is specialized with extensive 1×7 + 7×1 factorization. Module C: 8×8 Feature Map Size stage. At this point, the spatial size is already small, and the computational cost is low, allowing the number of channels to be substantially increased to generate high-dimensional sparse representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kt8XUWGFoCOL6Rjbjt00HQ.png" /><figcaption>InceptionV3 Architecture Diagram</figcaption></figure><h3>Highway Network</h3><p>As convolutional neural networks continued to deepen, researchers gradually realized that although depth itself can improve representational capacity, it also makes the training process more fragile: information and gradients can no longer naturally pass through multiple layers, and networks often stagnate during optimization or even exhibit worse training performance after additional layers are introduced. Srivastava et al. proposed Highway Networks in 2015, with the core objective of addressing this problem: allowing information to flow smoothly across multiple network layers like traveling on a “highway,” while using a gating mechanism to learn when to preserve the input and when to perform transformations. This idea enabled extremely deep feedforward networks to be trained directly using standard SGD. In preliminary experiments, the authors even indicated that networks with more than 1000 layers would not stagnate at the beginning of training.</p><p>The key to the Highway Network does not lie in simply adding a skip connection, but in making the question of “whether to pass through” itself a learnable problem. For an input x to a layer, its output can be written as</p><pre>y = H(x,W_H) ⊙ T(x,W_T) + x ⊙ (1−T(x,WT_))</pre><p>where H(x) is a standard nonlinear transformation, T(x) is the transform gate, and 1−T(x) corresponds to the carry gate. This design allows the same layer to switch smoothly between a “traditional nonlinear layer” and “directly passing through the input”; when the gate tends toward 0, the layer approximates an identity mapping, and the input is preserved almost unchanged; when the gate tends toward 1, the layer behaves more like a standard convolutional / fully connected layer for feature transformation. In other words, the essence of the Highway Network is to return control over information flow and gradient flow to the model itself to learn.</p><p>From an optimization perspective, one of the key reasons this structure is effective lies in the gate initialization strategy. The authors explicitly recommend initializing the bias of the transform gate to a negative value, such as -1, -2, or -3, so that the model initially favors carry behavior during the early stage of training, meaning that information is first allowed to pass through more easily, and the model then gradually learns where transformations are needed. This approach was clearly inspired by the idea of LSTM gate initialization: protecting information pathways at the beginning of learning, and then allowing the model to slowly determine which parts are worth modifying. For convolutional Highway layers, the authors also maintained the same receptive field and zero-padding so that the spatial dimensions of the block state and gate feature maps remained consistent; if the representation dimensionality needed to be changed, standard layers could first be used for processing, followed by stacked Highway blocks.</p><p>From an architectural perspective, the true importance of the Highway Network lies in the fact that it was the first to systematically express the idea that a deep network does not necessarily need every layer to forcibly rewrite the representation. It allows many layers to preserve input information and perform selective transformations only when necessary. Therefore, the trained network does not drastically rewrite the representation at every layer, but instead behaves more like an information channel that progressively filters and adjusts information. Subsequent research also pointed out that Highway and Residual networks can be understood from the same perspective of layer-by-layer estimation and correction; under this framework, both allow multiple blocks to collaboratively estimate representations at the same level, except that Highway uses explicit gating to determine the proportion that passes through, whereas Residual further simplifies this idea into an identity shortcut.</p><p><strong>Model</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63U16u0pm4HUoXKPCMwI3A.png" /></figure><p>The experimental focus of Highway Networks was primarily to demonstrate that “increasing depth no longer necessarily leads to training difficulties,” rather than simply pursuing the highest possible accuracy on a single dataset. The authors first conducted preliminary experiments on MNIST, where a 10-layer Highway network achieved 99.43% test accuracy with 39K parameters and 99.55% with 151K parameters, making its performance comparable to methods such as Maxout and DSN at the time; more importantly, these models could be trained directly using SGD without requiring two-stage hint-based training with a teacher network. In the original paper, the Highway network achieved 67.76% accuracy on CIFAR-100, with an average of 67.61 ± 0.15 over five runs, clearly outperforming Maxout at 61.42%, dasNet at 66.22%, NiN at 64.32%, DSN at 65.43%, and All-CNN at 66.29%. This demonstrates that the gate-based skip mechanism can also effectively maintain information flow on more complex datasets, preventing deep networks from losing trainability during optimization. In the optimization experiments, the authors observed that plain networks became increasingly difficult to train as depth increased, with the training error even deteriorating significantly; in contrast, Highway networks maintained strong optimization performance even when deepened to 50 or 100 layers, and their convergence speed was significantly faster than that of plain networks.</p><h3>ResNet</h3><h4>Deep Network Degradation Issues</h4><p>Previous research on ZF-Net verified the hierarchical structure in which low-, mid-, and high-level features are formed in deep networks, while research on VGG Net proposed and verified that the hierarchy of features can become richer by stacking more layers ( depth ). The deeper the model, the richer and more abstract the feature hierarchies it can learn. Both the Inception and VGG architectures demonstrated that depth is crucial to the performance of neural networks. However, given the importance of depth, a problem consequently arises: building a better network is not as simple as stacking more layers. When attempting to stack deeper networks, the problems of vanishing gradients and exploding gradients emerge, obstructing the convergence of learning from the outset. Although this problem has been largely addressed through Batch Normalization, allowing networks with dozens of layers to begin converging and thereby enabling backpropagation with stochastic gradient descent. As deeper networks begin to converge, another problem is exposed: as network depth increases, accuracy becomes saturated and then rapidly degrades. This degradation is not caused by overfitting, and adding more layers to a model with an appropriate depth leads to higher training error. This was fully verified through their experiments on the CIFAR-10 dataset, in which 20-layer and 56-layer plain networks were trained separately, with the deeper network exhibiting higher training error as well as greater test error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wyv86q5Ogk7Fu2JVw3wqEw.png" /><figcaption>Adapted from the paper “Deep Residual Learning for Image Recognition”, 2015</figcaption></figure><h4>Residual Learning</h4><p>In their experiments, this paper considers a shallower architecture and its deeper counterpart, prompting us to consider a key thought experiment. Suppose we have already trained a shallower network, and now we want to construct a deeper network. The method is simple: directly stack additional layers after the original network. In theory, we can make these newly added layers fully learn an “identity mapping”, meaning that their outputs are equal to their inputs, while directly copying the weights of the preceding shallower network. Through this “constructed solution”, it can be guaranteed that this deeper network can achieve at least the same training error as the shallower network, and theoretically it should not perform worse. However, extensive experiments have shown that existing optimizers have difficulty finding this constructed solution, or cannot converge within a reasonable amount of time to a solution comparable to or better than the constructed solution. This indicates that existing optimization methods face fundamental difficulties when handling extremely deep networks. To thoroughly address this degradation problem, they proposed an entirely new deep residual learning framework. Its core idea is that traditional stacked layers are expected to directly learn an ideal underlying mapping, denoted as H(x) . However, in extremely deep networks, directly learning H(x) becomes very difficult. Therefore, the authors boldly changed the learning objective, no longer forcing the stacked layers to directly fit H(x) , but instead allowing them to fit a residual mapping ( residual mapping ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAntSbkWPUm93WjofhYebA.png" /></figure><p>The authors assume that learning the residual function F(x) is easier than directly learning the original mapping H(x), especially when the optimal solution is close to an identity mapping, making F(x) approach 0 is far simpler than making a stack of nonlinear layers fit an identity function. This F(x)+x structure can be easily implemented through <strong>shortcut connections</strong>, which skip one or more consecutive convolutional layers and directly add the input to the output of a subsequent layer. In the design of ResNet, these shortcut connections adopt the simplest identity mapping, which introduces no additional parameters and no additional computational cost.</p><p>The basic unit ( building block ) of ResNet is defined as y = F(x,{Wi}) + x, where F is usually a two-layer or three-layer convolutional structure followed by ReLU. When the input and output channel dimensions are different, a linear projection shortcut connection y=F(x,{Wi})+Wsx is used to match the dimensions (Ws is a 1×1 convolution). The paper further points out that the identity shortcut is sufficient to solve the degradation problem. Although projection shortcuts can bring slight additional gains, they are not necessary; excessive use instead increases model complexity. Therefore, in practical design, projection is used only when the dimensions do not match, while the identity shortcut is retained in all other cases. To control computational cost and construct extremely deep networks ( more than 50 layers ), ResNet introduces the bottleneck building block, replacing the two-layer structure with a three-layer structure consisting of 1×1 dimensionality reduction, 3×3 convolution, and 1×1 dimensionality expansion. This design allows the intermediate 3×3 layer to maintain a smaller number of channels, significantly reducing overall FLOPs while still effectively learning residuals. ResNet-50/101/152 are all based on this architecture, among which the computational cost of the 152-layer ResNet is still lower than that of VGG-19, yet it achieves a substantial lead on ImageNet.</p><h4>ResNet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maeDNTJw86rAqQbrvEUQ-Q.png" /><figcaption>ResNet 18 Architecture Diagram</figcaption></figure><p>In ImageNet training and testing, the 34-layer plain net exhibited higher training and validation errors than the 18-layer plain net, clearly demonstrating the degradation phenomenon; meanwhile, the corresponding 34-layer ResNet not only completely eliminated degradation, but also improved top-1 accuracy by approximately 2.8% compared with the 18-layer ResNet. When the depth was further increased to 152 layers, ResNet continued to benefit from increased depth, achieving a single-model top-5 validation error of 4.49%, and after ensembling, it achieved a top-5 error rate of 3.57% on the ILSVRC 2015 test set, winning first place in the classification task. Similar phenomena were also reproduced on CIFAR-10: the training error of the plain net increased as depth increased, whereas ResNet could stably train networks with more than 100 layers, and even when explored up to 1202 layers, no obvious optimization difficulties were observed. These results strongly demonstrate that the residual learning framework effectively removes the optimization obstacles caused by depth, making deeper is better a reality once again.</p><h3>Inception-v4 &amp; Inception-ResNet</h3><p>In 2016, Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, and Alex Alemi continued the Inception series’ research on efficient convolutional architectures and proposed Inception-v4 and Inception-ResNet. The problem addressed by this study was no longer merely how to design more efficient Inception modules, but rather to further investigate whether the two most successful convolutional neural network development paths at the time could be integrated: one was the multi-branch structure, convolution factorization, and computational resource allocation represented by Inception; the other was residual learning and identity shortcut connections proposed by ResNet.</p><p>Inception and ResNet appear to be built on different architectural philosophies. Inception projects input features into multiple transformation branches with different scales and dimensions, and then concatenates the outputs of each branch along the channel dimension, allowing a single module to simultaneously process local textures, larger receptive fields, and cross-channel information; ResNet, by contrast, does not deliberately increase branch heterogeneity, but instead establishes direct information paths that can span multiple layers through the residual form (F(x)+x), so that the network only needs to learn the correction relative to the input. The former focuses on how to allocate computation efficiently within a single module, while the latter focuses on how to stably transmit information and gradients across multiple modules. The core significance of Inception-ResNet is precisely to place these two mechanisms in the roles of “feature transformation” and “information transmission,” respectively, with the Inception branches responsible for learning complex transformations and the identity shortcut responsible for maintaining the optimizability of deep networks.</p><h4>Inception-v4</h4><p>Inception-v3 had already established the design principle of selecting different convolutional structures according to feature map scale, using small convolutions, asymmetric convolutions, and high-dimensional feature representations at the 35×35, 17×17, and 8×8 stages, respectively. Inception-v4 did not propose any new convolution factorization methods, but instead reorganized the design experience accumulated over several generations of Inception into a deeper, wider, and highly regularized network architecture, reducing the instances in earlier models where modules were adjusted for specific positions.</p><p>Its primary update is first reflected in the input Stem. Compared with rapidly reducing resolution through single-path convolution or pooling, Inception-v4 designs the early downsampling stage as a multi-branch structure, using stride convolution and pooling in parallel, and then concatenating the outputs along the channel dimension. This design continues the idea of Efficient Grid Size Reduction, allowing the network to expand the number of channels and the variety of features while compressing the spatial dimensions, thereby reducing the risk of premature information loss and the formation of representational bottlenecks in the early stages.</p><p>After completing the Stem, the network sequentially stacks 4 Inception-A modules, Reduction-A, 7 Inception-B modules, Reduction-B, and 3 Inception-C modules, corresponding to the three feature stages of 35×35, 17×17, and 8×8, respectively. Inception-A continues to stack 3×3 convolutions to construct local features; Inception-B uses asymmetric 1×7 and 7×1 convolutions to enlarge the receptive field while controlling computational cost; Inception-C, at the low-resolution stage, splits some convolutions into parallel 1×3 and 3×1 paths, increasing the diversity of output channels and directional features. Reduction-A and Reduction-B are responsible for scale transitions between stages, simultaneously employing stride convolution and Max Pooling branches, so that the downsampling process combines learnable feature extraction with the preservation of salient responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*VgDvPH0nh5sjqjdakvpoBg.png" /></figure><p>Finally, the network uses Global Average Pooling to aggregate spatial features, followed by Dropout and Softmax to complete classification. Compared with Inception-v3, the main improvement of Inception-v4 does not come from a single new operation, but from expanding the channel capacity and number of modules at each stage, and reorganizing the overall network with unified Stem, Inception, and Reduction structures, making the architecture easier to analyze, implement, and extend.</p><p>The importance of Inception-v4 lies in advancing the Inception series from the continuous addition of local techniques to the systematic design of the overall architecture. It demonstrates that even without adding residual connections, a pure Inception network can still further improve representational capacity and classification performance through more regular module configurations, smoother scale transitions, and the overall allocation of depth, width, and computational resources. It can also be regarded as the mature version of the Inception approach: rather than emphasizing new convolutional forms, it integrates multi-scale processing, convolution factorization, channel projection, and efficient downsampling into a complete and consistent architecture.</p><h4>Inception-ResNet</h4><p>The main update of Inception-ResNet is the integration of Inception’s multi-branch feature transformations into ResNet’s residual learning framework. The original Inception module concatenates the outputs of different convolution branches along the channel dimension and directly uses them as the input to the next layer; Inception-ResNet instead adds a 1×1 convolution after branch concatenation to reintegrate the information from each branch and project the number of channels back to the same dimension as the input, before adding it to the identity shortcut. In this way, the Inception module no longer needs to reconstruct the complete feature representation, but only needs to learn feature corrections relative to the input.</p><p>This design preserves Inception’s multi-scale and convolution factorization capabilities while introducing ResNet’s direct information pathway. Complex spatial and channel transformations are concentrated in the multi-branch residual path, while the original input is transmitted along the shortcut, allowing the network to maintain a more stable gradient flow even after increasing the number of modules and channel capacity. Compared with a pure Inception architecture, the most apparent advantage of Inception-ResNet is first reflected in training convergence speed, rather than simply relying on a larger model capacity to improve accuracy.</p><p>The paper proposes two versions, Inception-ResNet-v1 and Inception-ResNet-v2. The model scale and computational cost of v1 are closer to those of Inception-v3; v2 adopts a wider channel configuration and higher overall capacity, with a scale roughly corresponding to Inception-v4, and is also the main version with better performance. Inception-ResNet-v2 is sequentially composed of the Stem, Inception-ResNet-A, Reduction-A, Inception-ResNet-B, Reduction-B, and Inception-ResNet-C, which process feature maps of 35×35, 17×17, and 8×8, respectively. Each stage continues to follow the convolution factorization principles of Inception-v3/v4, with the main difference being that each module is redefined as a residual transformation unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*m_ebho-OPxmoyzSNmRm12Q.png" /></figure><p>However, directly adding residual connections to extremely wide Inception modules also introduces new training instability problems. When the residual branch contains a large number of channels and multiple high-capacity paths, its output may cause excessive disturbance to the main path, leading to rapid growth in activation values and even causing the model to suddenly fail in the later stages of training. To address this, the authors first scale down the residual output by a fixed proportion before adding it to the shortcut, a technique referred to as residual scaling. This makes each module closer to an identity mapping in the early stages of training, preventing immature residual features from excessively rewriting the backbone information and thereby improving the stability of extremely wide residual networks.</p><p>The importance of Inception-ResNet lies in demonstrating that Inception and ResNet are not opposing architectural approaches. Inception is responsible for improving feature diversity and computational efficiency within a single module, while the residual connection is responsible for maintaining information and gradient transmission between modules. The two respectively address representational capacity and optimization stability, allowing deep networks to simultaneously possess more complex transformation structures and a main path that is easier to train, while also becoming an important design paradigm for subsequent hybrid CNN architectures.</p><h3>ResNet-v2</h3><p>In 2016, Kaiming He et al. further examined the residual units of ResNet in Identity Mappings in Deep Residual Networks and proposed the pre-activation architecture commonly referred to as ResNet-v2. Although the original ResNet used identity shortcuts to establish cross-layer information pathways, the output after the residual branch and shortcut were added still passed through ReLU, causing the features and gradients along the main path to be continuously affected by nonlinear transformations between each block. When the network depth increased to hundreds or even thousands of layers, these seemingly minor disturbances gradually weakened the direct transmission capability that residual connections were originally intended to provide.</p><p>ResNet-v2 changes the operation order within the residual unit from Conv–Batch Normalization–ReLU to Batch Normalization–ReLU–Conv, meaning that normalization and activation are performed before convolution. More importantly, after the residual branch and shortcut are added together, the result no longer immediately passes through ReLU but is instead directly fed into the next block, forming a more complete identity path across multiple residual units. Batch Normalization and ReLU act only on the features about to enter the residual branch and no longer modify the representations already accumulated along the main path.</p><p>This adjustment does not change the basic form of residual learning, but it clearly distinguishes the functions of the two paths: the shortcut is responsible for transmitting information and gradients without obstruction, while the residual branch is responsible for learning the necessary feature corrections. Experiments show that pre-activation can improve the convergence and generalization of extremely deep networks, allowing a 1001-layer ResNet to still be trained stably. The importance of ResNet-v2 lies in its indication that the core of residual networks is not merely the addition of skip connections, but rather keeping the main path as close as possible to a pure identity mapping while concentrating normalization, nonlinearity, and complex transformations in the residual branch. This design also became an important foundation for subsequent Wide ResNet, ResNeXt, and many deep residual architectures.</p><h3>Wide ResNet (WRN)</h3><p>After ResNet demonstrated that residual connections could effectively support the training of networks with dozens or even hundreds of layers, subsequent research naturally shifted its focus to the question of whether “deeper is necessarily better.” Zagoruyko and Komodakis proposed Wide Residual Networks in 2016, raising an important reconsideration of ResNet’s depth-expansion approach: although the original ResNet could be extended to more than 1000 layers, each slight improvement in accuracy often required multiplying the number of layers, resulting in problems such as longer training time, insufficient feature reuse, and reduced computational efficiency. The core idea of WRN is therefore not to continue increasing depth, but to “reduce depth and increase width,” that is, to increase the number of convolutional channels in the residual block and use the widening factor k to control the width of the feature map at each layer, enabling the model to retain sufficient representational capacity with fewer layers.</p><p>Experimental results show that this design does not simply trade more parameters for better performance, but reveals that the depth-to-width ratio in the ResNet architecture is not necessarily optimal: for example, WRN-40–4 has only 40 layers and approximately 8.9M parameters, yet already outperforms the 1001-layer pre-activation ResNet with approximately 10.2M parameters on CIFAR-10 and CIFAR-100; meanwhile, the representative WRN-28–10, despite having only 28 layers and approximately 36.5M parameters, achieves a 4.00% test error on CIFAR-10 and a 19.25% test error on CIFAR-100, outperforming ResNet-1001’s 4.92% and 22.71%, respectively, while using approximately 36 times fewer layers than the 1001-layer network. These results indicate that, after residual architectures have resolved the optimization difficulties of deep networks, the bottleneck of model performance is no longer determined solely by depth; width is likewise a critical dimension affecting feature representation capacity, training efficiency, and generalization ability. WRN can therefore be regarded as an important architectural reflection following ResNet: it preserves the optimization advantages of residual learning, but shifts the scaling direction from “deeper” to “wider,” influencing many subsequent models to consider the balance among depth, width, and computational budget in their design, while also providing an early experiential foundation for later architecture design approaches centered on multidimensional scaling, such as EfficientNet and RegNet.</p><h3>Xception</h3><p>Xception was proposed by François Chollet in 2017, and its name can be understood as Extreme Inception, meaning that it pushes the idea of “splitting feature processing into multiple branches” in the Inception architecture to a more extreme form. Chollet proposed an important reinterpretation of Inception: standard convolution learns spatial correlations and channel correlations simultaneously, whereas Inception attempts to process features from different scales and different channel projections separately through multiple 1×1, 3×3, and 5×5 branches; Xception further assumes that the “inter-channel relationships” and “spatial relationships” in convolutional features can be almost completely decoupled, and therefore replaces the Inception module with depthwise separable convolution.</p><p>Its operation can be divided into two steps: first, depthwise convolution independently performs spatial convolution on each channel, meaning that each channel is responsible only for learning the local spatial structure within its own feature map and does not mix with other channels; next, pointwise convolution, namely 1×1 convolution, performs cross-channel linear projection and information fusion, reconstructing semantic combinations among different channels. In other words, the core of Xception is not simply to “split convolution into smaller parts,” but to explicitly decompose the convolution operation into two stages: “intra-channel spatial feature extraction” and “inter-channel semantic integration,” forming an architectural assumption of “channel-wise independence + cross-channel projection.” Compared with standard convolution, this design greatly reduces computational cost and makes the feature processing structure more regular; compared with Inception, it no longer manually designs multi-scale towers, but instead treats each channel as an extremely separated branch and then uniformly integrates them through 1×1 convolution.</p><p>The overall Xception architecture is formed by linearly stacking depthwise separable convolutions and combining them with residual connections to stabilize deep training, and can therefore be viewed as a fusion of Inception’s efficient decomposition idea and ResNet’s residual optimization idea. In ImageNet single-model, single-crop experiments, Xception achieved Top-1 / Top-5 accuracies of 79.0% / 94.5%, respectively, slightly higher than Inception V3’s 78.2% / 94.1%; on the larger-scale JFT dataset, Xception achieved an approximately 4.3% relative improvement over Inception V3 on the FastEval14k MAP@100 metric, while the two models had similar parameter counts, indicating that the improvement mainly came from more efficient parameter utilization rather than simply increasing model capacity. The importance of Xception also lies in establishing depthwise separable convolution as a feasible and effective core operator in large-scale vision models. Subsequent lightweight and high-efficiency models such as MobileNet, ShuffleNet, and EfficientNet all continued this basic design logic of “first performing intra-channel spatial convolution, then performing cross-channel mixing,” making it a key foundation of modern mobile, edge-device, and efficient CNN architectures.</p><h3>ResNeXt</h3><p>After ResNet demonstrated that residual connections could support extremely deep networks, model scaling generally focused on two directions: increasing network depth or increasing the number of channels in each layer. However, simply increasing depth raises serial computation and training time, while directly increasing width can cause the number of parameters and computational cost to grow rapidly. In 2016, Saining Xie et al. proposed ResNeXt, introducing a third architectural dimension beyond depth and width, cardinality, which represents the number of parallel transformation paths within a residual block.</p><p>The core structure of ResNeXt can be summarized as split–transform–aggregate. The input features are first distributed into multiple low-dimensional subspaces, each branch performs the same form of feature transformation, and the results of all branches are then aggregated before being added to the identity shortcut. This multi-branch form shares a similar intuition with Inception, but the two differ in their design approach. Inception processes features at different scales through heterogeneous branches such as 1×1, 3×3, 5×5, or pooling, so each module often requires manual design; ResNeXt, by contrast, deliberately makes all branches use the same topology and only adjusts the number of branches and the channel width of each individual branch, allowing the overall architecture to be stacked as regularly as ResNet.</p><p>A typical ResNeXt bottleneck still adopts a three-layer structure consisting of 1×1, 3×3, and 1×1 convolutions. The first 1×1 convolution performs channel projection, while the intermediate 3×3 convolution uses grouped convolution, dividing the feature channels into multiple groups and applying convolution to each group separately. Finally, another 1×1 convolution integrates the outputs from the different groups. From an architectural perspective, each group can be regarded as an independent transformation branch; from an engineering implementation perspective, these branches can be combined into a single regular grouped convolution, eliminating the need to construct a large number of physically separate network paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFRxSM0NpHxWi5vZwxZCWA.png" /></figure><p>For example, in ResNeXt-50 32×4d, 32 indicates a cardinality of 32, while 4d indicates that the bottleneck width of each group is 4. This naming convention simultaneously describes the number of parallel transformations and the capacity of each individual transformation. Cardinality is not equivalent to conventional network width: increasing width typically enlarges the number of channels in a single convolution, allowing all features to be processed jointly within the same high-dimensional space; increasing cardinality, by contrast, creates more relatively independent low-dimensional transformations, enabling the model to learn complementary residual features across different subspaces.</p><p>The original study compared the effects of increasing depth, increasing channel width, and increasing cardinality while controlling the number of parameters and computational cost, and the results showed that increasing cardinality generally produced more consistent performance gains. This indicates that model capacity depends not only on how deep the network is or how large the feature dimensionality is, but also on how the transformation paths are organized. Multiple low-dimensional branches can learn different feature combinations separately and then aggregate them within the residual unit, often using parameters more efficiently than concentrating all computation in a single path.</p><p>ResNeXt also retains the optimization advantages of ResNet. The multi-branch transformations are ultimately integrated into a residual term and added to the identity shortcut, allowing the overall network to directly adopt ResNet’s stage configuration, training procedure, and downstream visual task design. Its main modification is concentrated in the intermediate 3×3 convolution of the bottleneck, enabling ResNeXt to increase the diversity of feature transformations without significantly increasing architectural complexity.</p><p>Grouped convolution had already appeared in AlexNet, but at the time it was mainly used to distribute the model across multiple GPUs, making it an engineering choice imposed by hardware limitations. ResNeXt was the first to explicitly elevate the number of groups to a model design parameter and use cardinality to explain its impact on representational capacity. From then on, grouped convolution was no longer merely a technique for reducing computational cost, but became an important operator for controlling channel connectivity patterns and constructing multi-path features.</p><p>The architectural significance of ResNeXt lies in transforming Inception’s multi-branch concept into a simpler, more regular, and more easily scalable residual module. Rather than relying on manually designed combinations of convolutions with different kernel sizes, it creates feature diversity through a large number of homogeneous transformations, extending the problem of CNN scaling beyond the traditional dimensions of depth and width to the number of transformation paths and the organization of channels. Subsequent architectures such as ShuffleNet, ResNeSt, and various efficient convolutional networks continued the use of grouped convolution, branch aggregation, and cross-group information exchange, making cardinality an essential scaling dimension in modern CNN architectures</p><h3>Conclusion</h3><p>Looking back at convolutional neural network research during this period, it can be observed that the core thinking behind visual models was no longer simply about increasing the number of parameters or stacking more convolutional layers, but had begun to systematically address three questions: how models should extract features across more scales and higher dimensions, how information and gradients could be transmitted stably through extremely deep networks, and how limited computational resources should be allocated effectively.</p><p>VGG established depth as an important factor for improving representational capacity; Inception began to explore width, multi-scale branches, and convolutional factorization, enabling models to obtain richer features at a lower cost; ResNet then shifted the research focus toward information flow and optimizability, demonstrating that the key to a network lies not only in whether it can construct complex transformations, but also in whether it preserves a stable main pathway. Subsequent architectures, including Inception-ResNet, Wide ResNet, Xception, and ResNeXt, gradually integrated these ideas and began to jointly adjust depth, width, the number of branches, channel relationships, and computational cost.</p><p>Therefore, what truly emerged during this period was not a single fixed optimal architecture, but a more mature perspective on model design: the performance of visual models depends on how features are decomposed, transformed, aggregated, and transmitted. CNNs also gradually evolved from early models that simply stacked convolutional layers into complete systems that must simultaneously consider representational capacity, optimization stability, and hardware efficiency, laying the foundation for subsequent lightweight networks, neural architecture search, and next-generation visual models.</p><h4>Implementation Code GitHub</h4><p><a href="https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/%40Models">https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/%40Models</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae8862523e01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision :  Chapter 1]]></title>
            <link>https://medium.com/@john20050826/computer-vision-chapter-1-03399423e184?source=rss-a590a0c11a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/03399423e184</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Jiaen]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 16:46:55 GMT</pubDate>
            <atom:updated>2026-07-27T12:00:30.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xegcy1_cnMR3mx3CwEvJvQ.jpeg" /></figure><h3>Computer Vision : Introduction to CNN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ig3vwZcxKf4y_MW3vY3rHw.jpeg" /></figure><p>In today’s era of AI technology, automated applications such as advanced driver-assistance systems, OCR text recognition, and object or crop analysis are all supported by powerful intelligent systems capable of seeing and understanding image content. This is the core concept of the field of computer vision: enabling machines to acquire or understand information from images or multidimensional data. One of the mainstream technologies in visual recognition is the Convolutional Neural Network ( CNN ). The development of this deep learning model is the result of the long-term evolution of image processing and biological neural network theories. It extracts abstract features from images and then uses these features to identify objects, recognize text, and even reconstruct images. One of the major characteristics of CNN is “convolution,” which extracts features from an image and then passes them to the next convolutional layer for further feature extraction. Through this layer-by-layer learning approach, CNN performs exceptionally well in various image recognition tasks. This article will guide you through the core concepts of CNN, explain how it operates, trace the evolution of this technology, and provide a detailed explanation of what convolution specifically is and how machines are able to learn from and understand images.</p><h3>Convolution</h3><p>The mathematical definition of the convolution operation is to multiply the function f ( x ) by g ( u — x ), and then perform an integration over x across the entire domain. Here, x may represent time, space, or frequency, depending on the application domain, including time, frequency, or space. The result of the convolution operation is a function of a new variable u, whose domain will be the same as that of the original variable. The calculation formula is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kezHuWoxZmDmzu27YmQ11Q.png" /></figure><p>The core purpose of using convolution is typically to describe the response of a Linear Time-Invariant (LTI) system. When an input signal f(x) acts on the system, what is its overall response? In the convolution operation described above, f(x) represents the input signal of the system, while the function g defines the system’s response function. This g function is a fixed pattern function, and the final output represents the accumulation of all past system outputs. For example, in signals and systems, convolution is defined as the operation between the system input signal f ( x ) and the impulse response function g ( t ) of a unit impulse. Therefore, this operation expresses that, to determine the system output at time unit u, one integrates f ( x ) g ( u — x ) over all x. Here, g(u — x) represents the response of the system at time u when an impulse is applied at time x.</p><p>In digital signal processing, image processing, or discrete systems, the convolution integral is transformed into a discrete summation and is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDlAgbAk5CChvsDl0n-ejg.png" /></figure><p>x [ k ] is the sample value at the k-th point in the discrete input sequence, while h [ n — k ] is the system response from the moment the sample is applied at the k-th point until the n-th sampling instant. Therefore, it corresponds to g ( t ), where t = n — k. In this sense, it describes how one function is influenced by another function. This approach is based on the idea that an input signal can be represented as a weighted combination of a series of impulses ( superposition principle ). Any arbitrary signal input x[ k ] can be expressed as a combination of many unit impulses δ [ n−k ]. Through the summation of these products, both the strength of the input signal and the way the system responds to each input are represented.</p><p>In my view, the significance of convolution in digital signal processing or image processing is that we attempt to extract the desired information response from a chaotic and unstable input X by applying a specific tool or template ( kernel / impulse response ) to it. Here, the “LTI system” can be imagined as a stable and predictable signal-processing tool, while the input x[n] represents an arbitrary and potentially noisy source of data.</p><p>Conceptually, the response functions used in these convolution operations are regarded as a Linear Time-Invariant System ( LTI system ), which possesses the properties of linearity and time invariance. The behavior of the system is determined by a fixed kernel h[n], and it applies the same processing logic to all inputs. Furthermore, a time-shifted input produces an equally time-shifted output. To some extent, once the system’s response to the most basic input is known, its response to any arbitrarily complex input can be calculated.</p><p>To provide a more intuitive understanding of the explanation above, let us illustrate it with a simple and intuitive example:</p><blockquote>Imagine that it is New Year’s Eve, and many fireworks are being launched. We would like to calculate how much smoke remains in the air after the fireworks event has ended. In this problem, we can define the unit of time as minutes and perform the calculation in a discrete manner.</blockquote><blockquote>First, let us assume that when a firework explodes in the sky, it produces an amount X of smoke in the air. However, over time, this smoke gradually dissipates, decreasing in quantity minute by minute. We define this reduction of smoke over time as a function representing the remaining percentage of smoke. We call it the Smoke Function:</blockquote><blockquote>S ( 0 ) = 1 , S ( 1 ) = 0.86 , S ( 2 ) = 0.63 , S ( 3 ) = 0.45 , S ( 4 ) = 0.2 , S ( 5 ) = 0</blockquote><blockquote>S ( t ) is a response function. It describes how the amount of smoke produced by a firework gradually decreases and dissipates after t seconds.</blockquote><blockquote>Next, we define another function called the Fireworks Function, F ( t ). It represents how many fireworks are launched during each minute interval. For example, if 5 fireworks are launched during minute 1, then it is represented as f ( 1 ) = 5. When we calculate the situation at minute 3, the smoke produced by the fireworks launched at minute 1 will have decayed to only F ( 1 ) * S ( 3–1 ) of its original amount:</blockquote><blockquote>5 * 0.63</blockquote><blockquote>As a demonstration, let the F function be:</blockquote><blockquote>F ( t ) = [ 3 , 5 , 2 , 3 , 2 , 1 ]</blockquote><blockquote>where the index represents the n-th minute.</blockquote><blockquote>Therefore, this problem can be expressed using discrete convolution to determine the amount of smoke in the air at minute T. Using convolution to calculate the smoke concentration in the air, if we want to compute the amount at minute 2, it can be written as:</blockquote><blockquote>F ( 2 ) * S ( 2–2 ) + F ( 1 ) * S ( 2–1 ) + F ( 0 ) * S ( 2–0 )</blockquote><blockquote>Then, given the Smoke function above, if we want to calculate the total amount of smoke in the air, the visualized representation would be as follows:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37ubqPM1xaZcIeEUm-LAnA.jpeg" /></figure><pre>h = [ 1 , 0.86 , 0.63 , 0.45 , 0.2 ]<br>x = [ 3 , 5 , 2 , 3 , 2 , 1 ] <br>y = np.convolve(x, h , mode=&#39;same&#39;) # Convolution Computation</pre><p>It can be observed that when t = 5, the calculation uses S ( 0 ) for multiplication, while the value from the previous minute is multiplied by S ( 1 ), and so on. As a result, the two functions appear in reverse order. On the time axis, the point on the far right is the most recent point entering the system because it occurs latest in time. Conversely, the point on the far left is the earliest point entering the system. Therefore, convolution can be interpreted as flipping x from left to right before applying it to the g function.</p><p>For this reason, the convolution process can also be viewed in a second way. It can be understood as using a Sliding Window algorithm that gradually moves across the entire time domain, starting from 0 and ending at T. This process generates a new function of length T, which describes the total amount of smoke present in the atmospheric system at each time t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*oKgjzQAksm3oiF-VWGyeGg.png" /></figure><p>This convolution operation essentially defines how other points influence the current point. The output function is defined on the same parameter domain as the input, such as time or space. It can be viewed as a weighting matrix composed of the neighboring points that are relevant to the current point. In the fireworks example, the parameter domain is time, so the output is influenced only by past moments. However, if the problem were defined such that future points along the time axis could also affect the current point, then the structure of this window would be different.</p><p>From a geometric perspective, we only need to design the parameters of this window. In a two-dimensional space, if we wish to calculate the total influence exerted on each position by the surrounding neighboring points, we can use two-dimensional convolution. The input matrix is transformed through a specific influence rule ( kernel ) to produce an output distribution function after convolution. The kernel represents how the points within a certain neighborhood affect the current point. Therefore, the kernel rule can be explicitly defined as a matrix, and the two-dimensional discrete convolution can be expressed as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAxIDvxY7KNCg53huUEhtA.png" /></figure><p>This expression represents the computation of convolution in a two-dimensional discrete space, making it directly applicable to two-dimensional image processing. An input image can be regarded as a two-dimensional signal. By sliding a kernel / filter across local regions of the image and performing an inner-product comparison, a feature map describing structural similarity can be generated.</p><p>As mentioned earlier, complex functions can be decomposed through an LTI system. In this context, an image can be viewed as a complex and irregular input function. By applying and stacking convolution operations with simple feature kernels, meaningful image processing can be achieved. Furthermore, due to the property of translation invariance, detected features are not lost when objects shift their positions within the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgaLulxmoICHANK21NCdiA.gif" /></figure><p>Although the mathematical expression already fully describes the operation in a two-dimensional space, let us revisit the fireworks example discussed earlier. There, the original mathematical definition of convolution could be interpreted as a reversed sliding-window accumulation operation. This naturally raises a question: when transforming two-dimensional signal processing into a sliding-window computation, is it also necessary to perform this reversal? Or, more fundamentally, does such a reversal carry any meaningful significance?</p><p>Following this line of thought, once we move into two-dimensional image operations, the original mathematical definition of convolution is no longer applied in exactly the same way. One possible reason is that image processing is generally more concerned with geometric interpretation than with system-response interpretation. Another reason is that many image-processing kernels are symmetric by design. Furthermore, implementations such as those found in OpenCV are often closer to the concept of cross-correlation. Cross-correlation was originally developed as a measure of similarity and therefore performs sliding alignment without requiring kernel reversal.</p><p>In practice, almost every other aspect of the computation remains identical to convolution. This may be because image processing places greater emphasis on geometric and visual interpretation, or simply because the terminology has become an accepted convention over time.</p><p><strong>Reference :</strong><br><a href="https://www.youtube.com/watch?v=KuXjwB4LzSA">But what is a convolution?</a><strong><br></strong><a href="https://www.analog.com/media/en/technical-documentation/dsp-book/dsp_book_ch6.pdf">The Scientist and Engineer’s Guide to Digital Signal Processing<br>Convolution</a><strong><br></strong><a href="https://www.youtube.com/watch?v=QmcoPYUfbJ8">What is convolution? This is the easiest way to understand</a><strong><br></strong><a href="https://en.wikipedia.org/wiki/Cross-correlation">Cross-correlation</a></p><h3>Convolutional Image Operations and Feature Extraction</h3><p>In computer science, image data is treated as a two-dimensional function for processing. In image-processing applications, convolution becomes a fundamental filtering operation. By applying a sliding-window operation between an image and a kernel ( convolution kernel ), a transformed image is produced. Convolution calculates the weighted influence of surrounding pixels on the current pixel and, after summation, uses the result as the new pixel value. In this way, convolution can be regarded as a simplified form of matrix multiplication.</p><p>With the development of digital computing and imaging technologies, convolution became widely used in the field of image processing and evolved into a practical filtering tool known as a Filter. A Filter refers to an operation that passes, modifies, or suppresses specific frequency components within an image. It can be used to extract image features such as edges, textures, and shapes, and in digital image processing is commonly referred to as a spatial filter. By designing different convolution kernels, different feature-extraction effects can be achieved. For example, the Sobel filter is primarily used for detecting edge directions, while the Gaussian filter is used for image smoothing and noise reduction. Traditional image-processing methods relied on these manually designed convolution filters to extract low-level features, which were then combined with Feature Descriptors and machine-learning techniques to perform image classification and recognition tasks.</p><h4>1. Preprocessing</h4><p>There are two common types of convolution filters used for preprocessing: Smoothing Filters and Sharpening Filters. These are used to make images cleaner, clearer, and easier to analyze.</p><p>Smoothing Filters reduce noise and fine details in an image by applying low-pass filtering techniques. By reducing the impact of small pixel-value variations, images become easier to analyze. Another purpose of smoothing is to eliminate false contours that arise due to insufficient grayscale levels. Common examples include the Box/Mean Filter, Gaussian Filter, Bilateral Filter, and Median Filter.</p><p>Sharpening, on the other hand, is used to emphasize abrupt changes in image intensity. Based on the principle of high-pass filtering, it suppresses low-frequency components while enhancing textures and edges, thereby improving feature quality. One of the most fundamental approaches is the Laplacian operator, which is based on the sum of second-order derivatives and measures the curvature of intensity changes between a pixel and its neighboring pixels to achieve a sharpening effect.</p><h4>2. Edge Detection</h4><p>Edges in an image arise from abrupt changes in intensity values within a digital image. They usually correspond to object contours, texture transitions, or shape boundaries, making them one of the most important discriminative features in an image.</p><p>The purpose of edge detection is to highlight regions with strong intensity variations while suppressing flat background areas, thereby providing more precise structural information for subsequent image analysis and recognition tasks. This allows a computer to focus on the most informative parts of an image.</p><p>A common way to measure changes in a signal is through differential derivatives. In two-dimensional images, edge detection is performed by designing gradient operators with two directional derivative components. The peaks of the first-order derivative correspond directly to image edges, making them effective indicators for edge detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2G9HkctP5cm4r0sft83UVQ.png" /></figure><p>Since the early days of computer vision and computational geometry, the field’s pioneer Lawrence Roberts, in his 1963 paper <strong><em>MACHINE PERCEPTION OF THREE-DIMENSIONAL SOLIDS</em></strong>, proposed that the perception of solid objects could be treated as a process based on three-dimensional transformations and natural laws. He argued that information such as an object’s shape, position, and orientation in space should be considered, and conducted experiments on the analysis of line-drawing images. In this paper, he introduced a method for abstracting real images into boundaries and contour lines — the Roberts Cross Operator.</p><p>The Roberts Cross operator is a first-order derivative-based edge-detection convolution operator and represents the first proposal to use convolution methods for detecting edge contours. It served as the starting point for constructing computer vision systems capable of reconstructing 3D objects from 2D images, allowing computers to understand image structures and features.</p><p>According to Roberts, he experimented with many different methods of performing differential operations on images. From these experiments, he concluded that the choice of operator was critically important. The generated edges should be clear, background noise should be minimized as much as possible, and the strength of the detected edges should correspond closely to human perception. Ultimately, he selected diagonal differencing, where diagonal differences approximate image gradients, because this approach best satisfied the three perceptual principles he proposed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cAEOcs0o_HedNBqh0ScSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qqyJtAKfvovKHrC1GdoAQ.png" /></figure><p>As image noise and practical computational challenges became more apparent, researchers found that although the Roberts Cross operator was conceptually simple, it was highly sensitive to noise. As a result, more robust operators began to emerge. The Sobel Operator ( 1968 ) introduced weighted averaging in the vertical direction, providing improved edge smoothing performance. The Prewitt Operator ( 1970 ) incorporated a broader weighting scheme across neighboring horizontal and vertical pixels. Later, the Canny edge detector ( 1986 ) achieved high-precision edge detection through a multi-stage processing pipeline.</p><p>As edge detection matured, researchers moved beyond simple edge extraction and developed more discriminative structural features. Corner detection methods, such as Harris-Stephens ( 1988 ), build upon horizontal and vertical gradients obtained from operators like Sobel and Prewitt. By constructing a local autocorrelation matrix, they identify points where strong intensity variations occur in all directions simultaneously. Blob detection methods, such as LoG ( Laplacian of Gaussian ) and DoG ( Difference of Gaussians ), utilize multi-scale Gaussian smoothing combined with second-order derivatives to locate regions corresponding to local intensity extrema.</p><p>Both categories of methods rely heavily on convolution operations to extract gradient information or higher-order derivative responses. From the perspectives of corners and blobs respectively, they enable the extraction of richer and more diverse image features, providing more informative representations for subsequent computer vision tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOjxxoRWskszWhiXpCVj4g.png" /></figure><h4>3. Gabor Filter</h4><p>The Gabor filter is named after Dennis Gabor. It was originally developed as a signal-processing analysis method and was later extended to two dimensions by Gösta Granlund through the introduction of a reference orientation. It has since been widely applied in image-processing tasks such as texture analysis and mid-level feature extraction. Compared with the edge-detection and corner-detection methods discussed earlier, Gabor filters are capable of extracting more complex patterns, including textures, local shapes, and orientation-dependent features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IS0X57lv0U25usTOjQATw.png" /></figure><p>A Gabor Filter is a convolution filter composed of a Gaussian function component and a sinusoidal component. The Gaussian function provides locality and weighting, while the sinusoidal component provides orientation and frequency characteristics. In its original form, the sinusoidal term is written as exp(i(2πfx′+ϕ)). In practical applications, however, only the real part, namely the cosine term, is often used for filtering. Therefore, the sinusoidal function is sometimes written as cos(2πfx′+ϕ).</p><p>The input variable g (x, y) represents the pixel coordinates of the image. λ denotes the wavelength of the sine component, θ controls the orientation, and ψ represents the phase offset, which determines the starting point of the waveform and influences symmetry and response direction. The standard deviation of the Gaussian function determines the size of the receptive field, while γ is the spatial aspect ratio that controls the elliptical shape of the Gaussian envelope.</p><p>After substituting all parameters, the Gabor value is computed for every (x, y) position until all entries of the matrix have been filled, thereby generating a kernel. As a result, it can be seen that a large number of parameters are available to control the characteristics of the filter, making it possible to generate a wide variety of filter combinations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtEDTCu9ikBDNhOrXwpCJQ.png" /></figure><p><strong>Reference :<br></strong><a href="https://theswissbay.ch/pdf/Gentoomen%20Library/Artificial%20Intelligence/Computer%20Vision/Feature%20Extraction%20in%20Computer%20Vision%20and%20Image%20Processing%20-%20Mark%20S.%20Nixon.pdf">Feature Extraction and Image Processing</a><strong><br></strong><a href="https://zbigatron.com/the-early-history-of-computer-vision/">the-early-history-of-computer-vision</a><strong><br></strong><a href="https://dspace.mit.edu/bitstream/handle/1721.1/11589/33959125-MIT.pdf">MACHINE PERCEPTION OF THREE-DIMENSIONAL SOLIDS</a><strong><br></strong><a href="https://blog.roboflow.com/edge-detection/">edge-detection</a><strong><br></strong><a href="https://youtube.com/playlist?list=PLHae9ggVvqPgyRQQOtENr6hK0m1UquGaG&amp;si=WAxjZmbrP6BoEQTR">Introductory python tutorials for image processing</a></p><h3>Image Recognition Based on Convolution Filter Feature Extraction</h3><p>After introducing the use of Convolution Filters for feature extraction, where manually designed convolution kernels or feature extractors are used to generate feature maps and extract meaningful information from complex images, it is worth noting that convolution is only one of many early feature-extraction approaches. Other manually designed feature descriptors, such as LBP ( Local Binary Pattern, 1994 ), SIFT ( 1999 ), and HOG ( 2005 ), were also developed to improve recognition performance on more complex image-analysis tasks.</p><p>However, this article focuses primarily on the application of convolution. In the following experiment, an image-recognition approach based mainly on Gabor filters and Sobel edge detection is adopted. The method first generates feature maps through filtering operations. Statistical measurements such as the mean, standard deviation, and energy are then computed from the extracted feature maps. These numerical values are used as feature inputs for a machine-learning model. After training, the model can perform classification and prediction tasks.</p><p>This approach is particularly suitable for scenarios involving a small number of images, limited computational resources, and traditional machine-learning workflows.</p><p>Case Study Dataset : <a href="https://www.kaggle.com/datasets/ankit1743/skyview-an-aerial-landscape-dataset"><em>https://www.kaggle.com/datasets/ankit1743/skyview-an-aerial-landscape-dataset</em></a></p><pre>def extract_features(image):<br>    features = []<br>    # Preprocessing<br>    image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))<br>    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br>    gray = cv2.equalizeHist(gray)  # Histogram Equalization<br><br>    gamma = 0.5<br>    psi = 0<br>    # Gabor filters<br>    for theta in [0, np.pi/4, np.pi/2, 3*np.pi/4]:<br>        for sigma in [1, 2, 3]:<br>            for lamda in [np.pi/4, np.pi/2]:<br>                kernel = cv2.getGaborKernel((9, 9), sigma, theta, lamda, gamma, psi, ktype=cv2.CV_32F)<br>                filtered = cv2.filter2D(gray, cv2.CV_32F, kernel)<br>                # Common statistical characteristics<br>                features.append(filtered.mean())<br>                features.append(filtered.std()) <br>                features.append(np.sum(filtered ** 2))        # Energy<br>                features.append(skew(filtered.ravel()))       # Skewness<br>                features.append(kurtosis(filtered.ravel()))   # Kurtosis<br><br>    # Sobel edge<br>    sobel_img = sobel(gray)<br>    features.append(sobel_img.mean())<br>    features.append(sobel_img.std())<br>    features.append(np.sum(sobel_img ** 2))<br><br>    return np.array(features, dtype=np.float32)</pre><p>The Sobel filter from skimage.filters and the Gabor Filter function from OpenCV can be used to generate multiple different Gabor Filters and produce corresponding feature maps. In the program API, cv2.getGaborKernel() is called, and parameters such as kernel_size, sigma, theta, lamda, gamma, and psi are set respectively to generate the corresponding Gabor convolution kernels. These kernels are then applied through cv2.filter2D to produce convolution-processed feature maps.</p><p>Next, statistical measurements such as skewness, kurtosis, mean, standard deviation, and energy are computed from the feature maps. These values are returned as a numerical feature vector. Each Gabor filter extracts 5 features, so the Gabor component provides a total of 24 filters × 5 features = 120-dimensional features. A Sobel Filter is then applied once as well. This combined feature vector represents the image and is used as the feature input for a machine-learning model.</p><p>The feature vector can be fed into models such as Random Forest, LGBM, XGBM, or other machine-learning models for training and prediction. For images with clear textures and distinct boundaries, Gabor/Sobel features are beneficial for recognition. However, when texture variation is large, noise is high, or the visual patterns are easily confused, the effectiveness of this approach may be reduced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQx-EWdX_EHLW9LWYBSscw.png" /></figure><p>Code: <a href="https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/ExperimentalSeries/GaborFeatureML"><em>https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/ExperimentalSeries/GaborFeatureML</em></a></p><h3>Neural Network and Deep Learning</h3><p>Throughout the history of artificial intelligence, two major schools of thought emerged. One believed that AI should be based on rule-based reasoning and logical computation, while the other argued that the key was first to understand how “learning” itself works. This latter perspective proposed mimicking the way humans think and how the brain learns, a viewpoint that later became known as connectionism.</p><p>To understand artificial neural networks and deep learning, we must begin with a machine-learning model known as the Perceptron. Proposed by Frank Rosenblatt in July 1958 at the Cornell Aeronautical Laboratory, the Perceptron was a simple classifier designed to imitate the behavior of biological neurons based on Hebbian theory. It is also considered one of the earliest artificial neural network models.</p><p>The Perceptron was regarded as the first machine capable of generating original ideas. It operates by multiplying an input feature vector by a corresponding set of weights and then activating one of two possible classes or states. The model is able to adjust itself through learning so that it can make more reasonable predictions in the future. Multiple perceptron units can learn independently, with each unit specializing in recognizing different categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86Zn4qVjHgeZramVCNArjg.png" /></figure><p>Through the following learning rules, the perceptron can adjust its weights based on the difference between the input X<em>i</em> and the target output <em>t</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nF6lA9qe3Y8RXv1aixikHA.png" /></figure><p>At the time, this model was celebrated as a machine capable of perceiving, recognizing, remembering, and responding in a manner resembling human thought. Its potential astonished researchers and generated tremendous enthusiasm. However, this excitement encountered a major setback in 1969.</p><p>In that year, Marvin Minsky and Seymour Papert published the book <strong><em>Perceptrons</em></strong>, in which they highlighted significant limitations of the perceptron model. Although they noted that multilayer perceptrons might potentially overcome these limitations, there was no effective training method available at the time for adjusting the weights of multilayer networks.</p><p>As a result, interest in neural-network research declined sharply, contributing to the first AI winter. Unfortunately, Rosenblatt did not live to see the eventual revival of neural networks and deep learning, passing away in 1971.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*Wg55RWKo7P2pGZzruNxeeQ.png" /></figure><p>To overcome the limitations of the perceptron, Paul Werbos, through a series of research papers published between 1974 and 1981, proposed propagating the gradient of the error backward from the output layer and using the Chain Rule to efficiently compute the gradients of every parameter in a multilayer network. These gradients could then be used to update the weights of a Multilayer Perceptron (MLP), a method that became known as the Backpropagation algorithm.</p><p>In 1986, David E. Rumelhart, Geoffrey Hinton, and Ronald J. Williams published the landmark paper <strong><em>Learning representations by back-propagating errors</em></strong>, which combined differentiable nonlinear activation functions, multilayer perceptrons, and the backpropagation algorithm. Through experimental demonstrations, the paper effectively highlighted the importance of this approach and brought multilayer perceptrons and backpropagation into mainstream attention.</p><p>However, this renewed enthusiasm lasted only for a limited period. From around 1985 until the end of the twentieth century, neural-network research continued to develop quietly within a few specialized fields. Although backpropagation could theoretically train deep networks, in practice it was only effective for relatively shallow architectures. Training deeper networks suffered from vanishing and exploding gradients, extremely slow convergence, and a lack of sufficient computational resources, technical infrastructure, and large-scale application scenarios required for deep learning.</p><p>A major breakthrough was achieved by Geoffrey Hinton in 2006, when he formally introduced the concept of “deep learning.” He emphasized the ability of neural networks to learn multiple layers of increasingly abstract representations. Hinton proposed stacking multiple Restricted Boltzmann Machines (RBMs) to learn hierarchical features layer by layer, followed by fine-tuning using backpropagation.</p><p>As deep-learning technologies advanced rapidly between 2006 and 2012, improvements in MLP architectures, activation functions, training techniques, and computing hardware transformed neural networks into the foundation of modern deep learning systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Ix813HFhQWLn5lm3PrJV7A.png" /></figure><p>How, then, can a multilayer artificial neural network learn?</p><p>The first step is to define a loss ( error ) function, which measures the difference between the predicted output and the true label. Suppose we construct a Multilayer Perceptron (MLP). After performing predictions through the forward-pass network on many samples, the outputs can be evaluated collectively using a loss function. For regression tasks, Mean Squared Error (MSE) can be used to compute the average squared difference between predicted and actual values. For classification tasks, Cross Entropy can be used, measuring the difference between the probability distribution predicted by the model and the distribution represented by the true labels.</p><p>The objective is to minimize the loss so that the machine can optimize itself and learn. This can be achieved by adjusting parameters, allowing the model to learn a function that fits the data and makes predictions. Therefore, our goal is to reduce the loss as much as possible, which is essentially an optimization problem.</p><p>For example, in basic machine-learning models, Linear Regression seeks to optimize the intercept and slope, while Logistic Regression seeks to optimize the shape of the decision curve. In general, many machine-learning models can be viewed as problems of parameter optimization. Gradient Descent provides a universal optimization framework that can be applied across these different models.</p><p>The gradient ∂L/∂w represents how much the loss L changes when the weight parameter w increases by a small amount. We would like to use this information to optimize a Multilayer Perceptron. In an MLP, each perceptron neuron consists of two parts: a linear combination component, z = w^T⋅ x + b and a nonlinear activation function, a = σ(z). To simplify the discussion, we can first focus on the linear combination component alone:</p><p>ŷ = w^T ⋅ x + b</p><p>In other words, we apply gradient descent to a linear regression model. Using the Chain Rule, the following derivation can be performed to calculate the parameter updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6_3GrJByzGfjHKXt377Fw.jpeg" /></figure><p>After deriving the partial derivatives, it can be observed that the gradient itself does not require squaring and therefore retains directional information. Since the term is expressed as ŷ — y, a positive value indicates that increasing the parameter would increase the loss, while a negative value indicates that the loss would decrease. Therefore, when using the gradient as the basis for parameter updates, a negative sign must be applied so that the optimization moves in the direction that reduces the loss.</p><p>If the gradient value itself were used directly as the update step size, the adjustment could easily become too large. For this reason, it is typically multiplied by a small Learning Rate. The magnitude of the weight update is therefore determined by the gradient. When the gradient is large, the parameters change significantly; as the optimization approaches the bottom of a valley, that is, near a local minimum, the gradient becomes smaller and the update steps become correspondingly slower.</p><p>If a neural network consists of only a single layer, it is essentially very similar to Linear Regression. However, modern neural networks divide each layer into a linear transformation and an activation function, and multiple layers are connected together. Suppose we slightly adjust a parameter w in layer L and then observe how this change affects the loss across a large dataset. Since an entire neural network may contain thousands or even millions of parameters, computing these effects independently for every parameter would be computationally infeasible.</p><p>Hinton’s approach was to first perform a forward pass through the network and compute the final loss. Then, starting from the output layer, the gradients are propagated backward layer by layer, calculating the gradient of every weight until reaching the first layer. This allows the gradients of all parameters to be computed efficiently using a dynamic-programming-like approach without repeatedly recalculating the same intermediate quantities.</p><p>At this point, one might ask why gradients can be computed through backward propagation. The answer lies in the Chain Rule from calculus. The underlying principle is the same as that used in gradient descent, but in a multilayer perceptron, changing a single weight affects many subsequent computations throughout the network.</p><p>For example, when adjusting a weight w{i,j}^(L) in layer L, the resulting linear output z_i changes. This causes the activation output a_i^(L) of the i-th neuron to change as well. That change then affects the linear combinations z^(L+1) of all neurons in layer L + 1. The entire influence chain corresponds to the quantity ∂Loss / ∂z_i^(L), which is commonly abbreviated as δ^L.</p><p>When the complete influence process is written mathematically, it can be seen that calculating δ^L requires computing k terms of ∂Loss/∂z_k^(L+1). These quantities are precisely the δ values of the next layer. Therefore, a recursive relationship exists between the δ values of adjacent layers. Because of this recursive structure, gradient computation can begin at the output layer, where the derivatives are easiest to calculate, and then be propagated backward through the network. Once all weight gradients have been computed, Gradient Descent can be applied to optimize the parameters and reduce the loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fh45I2P68lvpvYMoa-gbEA.jpeg" /></figure><p><strong>Reference :<br></strong><a href="https://news.cornell.edu/stories/2019/09/professors-perceptron-paved-way-ai-60-years-too-soon">Professor’s perceptron paved the way for AI — 60 years too soon</a><br><a href="https://arxiv.org/abs/1404.7828">Deep Learning in Neural Networks: An Overview</a><br><a href="https://youtu.be/sDv4f4s2SB8?si=aEv9SedIrg-GzG3a">Gradient Descent, Step-by-Step</a> <a href="https://gwern.net/doc/ai/nn/1986-rumelhart-2.pdf">Learning representations by backpropagating errors</a><br><a href="https://www.youtube.com/watch?v=PdGgbsM9vrc&amp;list=LL&amp;index=10">台大資訊 人工智慧導論 FAI 4.2 : Backpropagation</a></p><h3>Inspired by Biovisualization</h3><p>The cerebral cortex of modern mammals is the gray-matter structure located on the outer layer of the brain, and a substantial portion of it is dedicated to visual processing. Beginning in the 1950s, David Hubel and Torsten Wiesel conducted pioneering research into mammalian vision, investigating how the cerebral cortex processes visual information.</p><p>According to their paper <strong><em>RECEPTIVE FIELDS OF SINGLE NEURONES IN THE CAT’S STRIATE CORTEX</em></strong> (1959), Hubel and Wiesel focused on the responses of individual neurons within the primary visual cortex of cats to visual stimuli. In their experiments, they recorded neural signals produced by individual neurons while cats were presented with various visual patterns, using specialized instruments to capture the responses.</p><p>They discovered that certain neurons responded most strongly to specific and relatively simple line edges. These neurons were later referred to as <strong><em>simple neurons</em></strong> ( simple cells ). Experimental results showed that a particular neuron would respond preferentially to a line with a specific orientation. When groups of neurons collectively respond to different orientations, the visual system becomes capable of distinguishing edge features across the full 360-degree range of orientations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*4kzDzZQlyj4L3MZPLut1Kg.png" /></figure><p>In the figure above, different simple neurons emit signals at different firing frequencies depending on the orientation of the line stimulus. Some orientations produce almost no neural response at all, while others generate much stronger firing frequencies.</p><p>Note: A receptive field refers to the region in which an appropriate stimulus can trigger a response from a particular neuron.</p><p>Visual information is processed by being progressively integrated along neural pathways to detect increasingly sophisticated features. Through the operation of neural circuits, basic signals are transformed into useful and often more complex information, enabling the brain to interpret visual stimuli.</p><p>The next stage involves these simple neurons, which detect lines and edge orientations, transmitting their signals to a large population of cells known as <strong><em>complex neurons</em></strong> ( complex cells ). Each complex neuron receives inputs that have already been processed by multiple simple neurons in the previous layer. Complex neurons combine lines of different orientations into more sophisticated geometric structures such as corners, curves, and other shapes. They reorganize and integrate this information into increasingly complex visual representations, which are then passed through successive layers of processing. Through multiple stages of transformation and recombination, the visual system gradually constructs richer and more abstract visual information.</p><p>Inspired by the observations of Hubel and Wiesel and their hierarchical model of visual cells, Kunihiko Fukushima introduced the <strong><em>Neocognitron</em></strong> in 1979, a hierarchical multilayer architecture in the field of artificial intelligence. The Neocognitron was applied to handwritten Japanese character recognition and other pattern-recognition tasks and later became a major source of inspiration for Convolutional Neural Networks.</p><p>The Neocognitron achieved pattern recognition by identifying geometric similarities within images and learned features in an unsupervised manner. The first layer extracted simple geometric features directly from the image, while higher layers combined the features detected by previous layers to form larger and more abstract shapes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2q4NY5Da3W8_a_mZ1ilSvw.jpeg" /></figure><p>Within this architecture, two alternating types of layers were designed: the S-cell ( Simple Cell ) layer and the C-cell ( Complex Cell ) layer.</p><p>Each S-cell layer contains many S-cells responsible for detecting specific local features within an image, such as edges, corners, and curves. The C-cell layer receives outputs from multiple neighboring S-cells. It performs local weighted integration and nonlinear processing on the outputs of the S-plane, providing positional tolerance and introducing translation invariance, allowing the network to correctly recognize features even when their positions vary slightly.</p><p>This alternating S-C stacking structure progressively combines low-level features into higher-level features, ultimately forming a complete representation of a pattern.</p><p>Only the input synapses of S-cells are plastic and can be modified during learning. Within the same layer, neurons are grouped according to their “preferred stimulus features” into subgroups known as <strong><em>cell-planes</em></strong>. Each position within a cell-plane consists of the response value of a particular feature detector at that location. The collection of responses produced after S-cell computation is referred to as an <strong><em>S-plane</em></strong>. Multiple Simple Cells therefore generate multiple S-planes.</p><p>The input of each cell is derived from a receptive region in the previous layer, while the connection topology and receptive fields are predefined and fixed. During learning, only the weights of the S-cells are updated. As the network depth increases, the receptive field of each individual cell becomes larger. Through repeated stages of aggregation and feature combination, increasingly abstract representations are formed.</p><p>At the top of the hierarchy, a recognition layer or an external classifier is added above the highest feature-extraction layer. At this stage, the receptive field covers the entire input image, allowing the final recognition and classification process to be performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyBfX_Nr6tajrpV8sQt6jw.png" /></figure><p>The computational mechanism of an S-cell is conceptually similar to a convolution-based image operation. Its response is calculated using the equation shown above. Through this operation, the output of the S-cell located at coordinate n in the k-th S-plane of layer ℓ is produced as a nonnegative real number.</p><p>The function φ performs a thresholding operation that clips negative values. The selectivity parameter r multiplies the ratio between the total excitatory input and the inhibitory operation. The constant term 1 in the denominator provides a baseline value, ensuring that the fraction remains stable even when no input is present.</p><p>The excitatory term,<strong> ∑ ∑ aℓ (⋅) uc ℓ−1 (⋅)</strong> represents the weighted summation of outputs from all relevant C-planes in the previous layer at their corresponding positions. This component measures how well the current input pattern matches the learned feature template.</p><p>The denominator corresponds to the operation of inhibitory cells and serves as a normalization mechanism. The parameter <strong><em>bℓ(kℓ) </em></strong>represents the inhibitory weight associated with the S-cell. The term <strong><em>uv ℓ−1 (n) </em></strong>is derived from the local energy or average activity indicator produced by the corresponding V-cell in the previous layer. It is computed using an RMS-type ( root-mean-square ) operation, which is similar to calculating local energy or the length of a vector.</p><p>After this normalization process, half-wave rectification and selectivity scaling are applied. The combination of V-cells and inhibitory terms provides an important advantage: it suppresses background activity or high-energy but poorly structured interference. As a result, the S-cell evaluates whether a pattern matches its template relative to the surrounding local background, enabling robust feature detection while maintaining tolerance to shifts and deformations.</p><p>When the selectivity parameter rℓ is small, the neuron becomes more tolerant to distortions and deformations, although its response strength is weaker. Conversely, when rℓ is large, only stimuli that closely match the stored template can produce a strong response. Therefore, an S-cell generates a positive output only when the excitatory input is sufficiently large relative to the local energy level. The parameter r ultimately controls the sensitivity and strictness of the neuron’s response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*3u3JF5S6z8rMBgHhs2lzUA.gif" /></figure><p>All S-cells within the same S-plane observe receptive fields of the same size at different spatial locations. Therefore, an S-plane represents the response distribution of a particular feature across different positions in the image. Each C-plane then corresponds to a specific S-plane and performs local integration on its outputs, ensuring that small positional shifts of the same feature do not cause the response to disappear.</p><p>How, then, are these features learned? The Neocognitron employs an unsupervised competitive-learning mechanism. For a given position n, the outputs us of all S-planes at that location are first computed. The S-plane producing the largest response becomes the winner, and only that S-plane updates its weights while all others remain unchanged. This winner-take-all strategy prevents multiple planes from learning duplicate features.</p><p>The weight-update rule follows a Hebbian-like learning principle. When an S-plane wins the competition, the local input pattern it observes is incorporated into the feature template through a weighted averaging process. The resulting weights are then constrained through nonnegativity and normalization operations, helping to maintain stable and interpretable feature templates.</p><p>Training is performed hierarchically. First, the S1 layer is trained until all S-planes converge. The learned S1 layer is then fixed, and the transformed representations produced through the S1 → C1 pathway become the input for training S2. The same process is repeated layer by layer. In the architecture, the first S-cell layer uses 5×5 receptive fields, while subsequent S-layers use 5×5×24 receptive fields. For the C-cells, the first two layers use 5×5 integration regions, whereas the final layer uses a 2×2 region.</p><p>The Neocognitron demonstrated the ability to recognize patterns despite translation, deformation, and partial occlusion, capabilities that were extremely difficult to achieve using the hand-crafted feature extraction and classifier approaches common at the time. It introduced the concepts of hierarchical feature extraction and local invariance, while also presenting a new perspective in which learned features could replace the labor-intensive process of manual feature engineering. The architecture exhibited strong tolerance to translation and rotation, although it remained sensitive to noise and generally required large amounts of training data to achieve good generalization performance.</p><h3>First Convolution Neural Network : LeNet</h3><h4>LeNet-1</h4><p>The earliest origins of CNNs can be traced to research led by Yann LeCun and his collaborators in 1989, particularly the paper <strong>Backpropagation Applied to Handwritten Zip Code Recognition</strong>. The central idea was that by designing a network architecture that incorporates an appropriate amount of prior knowledge about the task, it is possible to achieve good generalization on complex problems. Constraints derived from the problem domain can significantly improve the generalization ability of a learning network.</p><p>Their approach employed a single network to learn the entire recognition process, from normalized character images to the final classification output. One of the key design principles emphasized in the paper was to minimize the number of free parameters in the neural network while avoiding excessive reductions in computational capacity. Applying this principle increases the likelihood of correct generalization because it leads to a specialized network architecture with lower entropy, reduced internal information complexity, and a lower Vapnik-Chervonenkis (VC) dimension. Such a design encourages the neural network to process complex image-recognition tasks effectively while reducing the risk of overfitting.</p><p>The authors applied the backpropagation algorithm to a practical problem: recognizing handwritten digits extracted from United States postal mail. Unlike previous approaches, the neural network accepted images directly as input rather than relying on precomputed feature vectors.</p><p>Earlier methods typically involved a feature-engineering stage in which hand-crafted features were designed and extracted before being passed to a machine-learning algorithm. The goal of this work was to overcome the limitations of manually selecting features and instead allow the neural network to learn useful representations directly from raw images.</p><p>For the Zip Code recognition task, the original digit images varied in size but were typically around 40 × 60 pixels. A linear transformation was applied to normalize each image into a 16 × 16 pixel representation. The resulting images were not binary but contained multiple grayscale levels because varying numbers of original pixels could contribute to a given pixel in the normalized image. The grayscale values of each image were then scaled and shifted so that they fell within the range of −1 to 1.</p><p>The remainder of the recognition process was performed entirely by a multilayer neural network. All network connections were adaptive, although strongly constrained, and the entire system was trained using backpropagation. Previous research in visual pattern recognition had already demonstrated that performance improved when local features, such as edges and corners, were extracted first and then progressively combined into higher-level features representing shapes, symbols, or digits. This hierarchical recognition principle, progressing from simple features to increasingly complex representations, ultimately became one of the fundamental ideas underlying modern Convolutional Neural Networks.</p><blockquote>“Such knowledge can be easily built into the network by forcing the hidden units to combine only local sources of information.”</blockquote><p>Knowledge can be embedded directly into a neural network through architectural design. One such approach is to constrain hidden-layer units so that they receive input only from local regions of an image rather than from the entire image. In other words, each neuron does not observe the whole image but instead processes only a small portion of it, such as a local corner or patch.</p><p>This design mimics the concept of a local receptive field in the human visual system. By restricting neurons to local regions, the network is encouraged to learn meaningful local patterns such as edges, corners, and simple shapes before combining them into more complex representations at deeper layers.</p><blockquote>“Distinctive features of an object can appear at various locations on the input image. Therefore it seems judicious to have a set of feature detectors that can detect a particular.”</blockquote><p>A particular feature of an object may appear anywhere within an image. The key idea proposed here is to design a set of feature detectors capable of searching for the same feature throughout the entire image. This is precisely the core concept behind small convolution kernels combined with a sliding-window algorithm.</p><p>Such an approach not only enables the detection of similar features regardless of their location but also greatly reduces the number of parameters that must be learned. At the same time, it helps preserve translation invariance. The result is what is commonly referred to as a <strong>Feature Map</strong> — a feature representation generated by scanning the image with the same set of feature detectors.</p><p>Through <strong>Weight Sharing</strong>, a neural network can detect the same feature at any location within the input image, reflecting the translation-invariant properties of the architecture. Multiple neurons share the same set of weight parameters across different spatial locations. Since a convolution kernel consists of a fixed set of parameters, only this relatively small number of parameters needs to be trained.</p><blockquote>“Weight sharing not only greatly reduces the number of free parameters in the network but also can express information about the geometry and topology of the task.”</blockquote><p>The significance of this strategy extends beyond merely reducing the number of parameters that need to be trained. More importantly, it enables the network to capture the geometric and spatial structure inherent in the input data. The resulting feature map serves as a representation indicating where a particular feature appears within the image, effectively providing a spatial response map of that feature’s presence and distribution.</p><p><strong>Architectural prototype:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*XSJwj2oydzvdgVyBpfzfMA.png" /></figure><h4>LeNet Develope</h4><p>Subsequent research and improvements led to the publication of LeNet-2 in 1990 in <strong><em>Handwritten Zip Code Recognition with Multilayer Networks</em></strong>. In 1990, it achieved a digit recognition rate of 92%, a substitution rate of 1%, and a rejection rate of 7% on ZIP code digit recognition provided by the United States Postal Service. LeNet-2 and LeNet-3 introduced deeper hierarchies and more complex design choices, gradually increasing network capacity while still retaining the core idea of learning hierarchical feature representations. The real breakthrough came with LeNet-4 in 1994. Yann LeCun led the creation of the <strong><em>MNIST (National Institute of Standards and Technology database)</em></strong> dataset, and the original LeNet was no longer sufficient to handle such a large amount of data. Therefore, LeNet-4 was designed to adapt to larger databases and improve generalization capability. In 1998, it was further optimized and released as LeNet-5.</p><h4>LeNet-5</h4><p>After 10 years of research and refinement, Yann LeCun and Yoshua Bengio, among others, published <strong><em>Gradient-Based Learning Applied to Document Recognition</em></strong> in 1998. It can be regarded as the earliest CNN to be widely applied, and the paper has accumulated more than 70,000 citations to date. The design philosophy of LeNet was to rely on more automated learning and reduce manually designed heuristic rules in order to build better pattern recognition systems. One of the major problems with traditional methods was that recognition accuracy depended heavily on whether the designer could devise an appropriate set of features. The paper discussed the technological evolution in recent years, highlighting three key shifts: the widespread availability of high-speed hardware, the availability of large datasets, and learning algorithms capable of handling high-dimensional inputs. CNN addressed these challenges through weight sharing and local receptive fields, automatically achieving translation invariance. In addition, convolution kernels preserve the topological structure of images, allowing the network to exploit local correlations between neighboring pixels, effectively capture local features, and progressively combine them into higher-level representations.</p><p><strong>LeNet-5 Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pm1e0Xb3McOV_SO1rxYgsg.png" /></figure><p>The first layer (C1) is a convolutional layer with 6 learnable convolution kernels. Each kernel is configured as 5 × 5 with a stride of 1 and no padding, producing 6 corresponding feature maps. The size of each feature map is 28 × 28, with a total of 156 trainable parameters.</p><p>The second layer (S2) performs subsampling. Average pooling is applied to the feature maps using a 2 × 2 averaging kernel with a stride of 2, ensuring that receptive fields do not overlap. The outputs then pass through a Sigmoid or Tanh activation function, reducing the feature map size to 14 × 14. The S2 layer contains a total of 12 trainable parameters.</p><p>The third layer (C3) is a convolutional layer with 16 convolution kernels of size 5 × 5, stride 1, and no padding. In LeNet, the first six feature maps are defined as being computed from three consecutive feature maps from S2, the next six from four consecutive feature maps from S2, three from four non-consecutive feature maps, and the final one from all six feature maps. Each pixel in an output feature map is obtained by summing the convolution results from the corresponding input feature maps. The C3 layer contains a total of 1,516 trainable parameters.</p><p>The fourth layer (S4) is a subsampling layer with the same parameter configuration as the second layer (S2). After activation, it generates 16 feature maps, each with a size of 5 × 5, and contains 32 trainable parameters.</p><p>The fifth layer (C5) is a convolutional layer with 120 convolution kernels corresponding to 120 output feature maps. The kernel size is 5 × 5, and each kernel is fully connected.</p><p>The sixth layer (F6) is an MLP fully connected layer containing 84 units, which connect to the MLP output layer. Since this implementation demonstrates the MNIST handwritten digit recognition system, the output consists of 10 values corresponding to the probabilities of each class.</p><p>For the loss function design, mean squared error (MSE) was used. Although simple, it has shortcomings in classification tasks, including the lack of competition between classes and the potential for network parameter collapse. The paper proposed an approach similar to softmax combined with cross-entropy, using logarithmic posterior probabilities to increase the score of the correct class while suppressing incorrect classes, thereby enhancing classification discriminability.</p><p>Finally, the appendix introduced several important training techniques. The activation function employed a Tanh variant that approximates Sigmoid. Weight initialization adopted an appropriate strategy specifically designed for shared parameters. For optimization, a stochastic version of the Levenberg–Marquardt algorithm was used, which converged faster than standard SGD. These details ensured that LeNet-5 could be trained effectively on the computational resources available at the time, using CPUs without GPUs.</p><pre>class LeNet5(nn.Module):<br>    def __init__(self):<br>        super(LeNet5, self).__init__()<br>        self.conv1 = nn.Conv2d(1 ,6  , kernel_size=5, stride=1, padding=0) # C1<br>        self.conv2 = nn.Conv2d(6 ,16 , kernel_size=5, stride=1, padding=0) # C3<br>        self.conv3 = nn.Conv2d(16,120, kernel_size=5, stride=1, padding=0) # C5<br>        self.fc1 = nn.Linear(120, 84)  # F6<br>        self.fc2 = nn.Linear(84, 10)   # Output layer<br>        self.tanh = nn.Tanh()<br>        self.pool = nn.AvgPool2d(kernel_size=2, stride=2)<br>    def forward(self, x):<br>            x = self.tanh(self.conv1(x)) # C1 : Convolution + Activation<br>            x = self.tanh(self.pool(x))  # S2 : Subsampling + Activation<br>            x = self.tanh(self.conv2(x)) # C3 : Convolution + Activation<br>            x = self.tanh(self.pool(x))  # S4 : Subsampling + Activation<br>            x = self.tanh(self.conv3(x)) # C5 : Convolution<br>            x = x.view(x.size(0), -1)  <br>            x = self.tanh(self.fc1(x))   # F6 : MLP Linear Fully Connect<br>            x = self.fc2(x)              # Output layer<br>            return x</pre><p><a href="https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/ExperimentalSeries/LeNet_MNIST"><em>https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/ExperimentalSeries/LeNet_MNIST</em></a></p><p>The model described in the paper was reconstructed and implemented using code. The implementation was carried out with PyTorch, but unlike the original paper, the CNN was implemented using modern deep learning framework packages. One difference from the literature is that modern convolutional layers are designed to be fully connected, while the parameters of pooling layers are not adjusted through learning. Using current GPU resources, training LeNet to recognize MNIST can be completed quickly within a few minutes. After 10 training epochs, the experimental result on the MNIST test dataset achieved an accuracy of 98.76%.</p><p>At the time, they tested many methods. The paper showed the raw error rates of these classifiers on a 10,000-sample test set. Among them, Boosted LeNet-4 trained with artificially distorted data augmentation performed the best, with an error rate of 0.7%. This was followed by LeNet-5 with artificially distorted data augmentation, which had an error rate of 0.8%, while the standard LeNet-5 achieved 0.95%. In addition, the traditional method V-SVM poly 9 combined with artificially distorted data augmentation reached 0.8%, producing results close to those of CNN.</p><p>The paper also demonstrated the successful application of CNN technology in real-world scenarios and OCR, and introduced the concept of gradient-based learning for model optimization. For multilayer or multimodule systems, in order to extend from single-character recognition to the recognition of words and sentences in documents, the concept of combining multiple modules to reduce the overall error rate was introduced. When processing variable-length objects, such as handwritten words, directed graphs must be manipulated. The paper presented a concept called Graph Transformer Network (GTN), which can train the entire multimodule system to minimize global error. LeNet-5 served as a trainable classifier module integrated into the GTN and connected with other models. The entire system architecture included region localization, region segmentation, character recognition modules, contextual post-processing modules, and graph transformation modules. The parameters of all modules were optimized simultaneously using Backpropagation and Gradient Descent.</p><p><strong>Appendix: Formula for Calculating CNN Feature Map Size</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nzlAHeS1_lO0ZDaWieqxA.png" /></figure><h3>Developments in the Early 21st Century</h3><p>The success of LeNet was achieved on small datasets and low-resolution images such as MNIST. It was successfully applied to limited domains including handwritten digit recognition and postal systems. However, when dealing with more realistic data, such as color images and datasets containing hundreds of categories, neural networks needed to become deeper and wider, causing the number of parameters to increase dramatically. At that time, CPUs were unable to efficiently handle the training of deep CNNs, making large-scale CNN training impractical.</p><p>Deep neural networks also faced challenges such as vanishing gradients, overfitting, and training instability, which made training deep models extremely difficult in practice. Consequently, the mainstream approach in academia still favored handcrafted features such as SIFT (1999) and HOG (2005) combined with Support Vector Machines (SVMs), since these methods were easier to train and produced stable performance on the relatively small datasets available at the time.</p><p>In 2006, Geoffrey Hinton proposed the Deep Belief Network (DBN), constructed by stacking Restricted Boltzmann Machines (RBMs), and formally introduced the concept of deep learning, reigniting interest in deep neural network research. Andrew Y. Ng and his colleagues later proposed Convolutional Deep Belief Networks (2009), bringing unsupervised learning into convolutional architectures while emphasizing translation invariance and scalability. Even more significant developments occurred between 2010 and 2012, when researchers adopted improved activation functions and initialization strategies. Bordes and Bengio demonstrated the strong practical performance of Deep Sparse Rectifier Networks. The introduction of ReLU alleviated the vanishing gradient problem and introduced sparsity, making it feasible to train deep networks directly from random initialization. Following the release of CUDA, researchers began moving matrix computations onto GPUs, greatly accelerating training efficiency. At the same time, large-scale datasets and benchmarks such as CIFAR and ImageNet became available. Since the core strength of deep learning lies in representation learning, which requires abundant variation in data, these large datasets enabled the advantages of deep learning to emerge more clearly.</p><h4>GPU Acceleration of Training</h4><p>Today, GPUs have become indispensable tools in deep learning. Their architecture and computational capabilities make them particularly well suited for the highly parallel nature of neural network training. GPU parallelism is achieved by aggregating large numbers of input feature vectors and weight vectors, transforming multiple inner-product operations into matrix operations that can be executed efficiently. GPUs are designed with a large number of processing cores capable of performing many operations simultaneously, allowing neural networks to achieve high throughput and efficient parallel processing.</p><p>The history of GPU-accelerated neural network training can be traced back to 2004, when Kyoung-Su Oh and Keechul Jung trained a three-layer feedforward network on an ATI Radeon 9700 Pro graphics card and achieved a 20-fold speedup. In 2005, researchers from Microsoft Research and Stanford University, led by Patrice Y. Simard, experimented with training a two-layer feedforward network on ATI and Nvidia GPUs.</p><p>In 2006, Kumar Chellapilla and colleagues conducted the first study applying GPUs to CNN training, achieving a training speed approximately four times faster than an equivalent CPU implementation. In 2009, another Stanford University team led by Andrew Ng trained a Deep Belief Network using 30 Nvidia GTX 280 GPUs, achieving roughly a 70-fold speedup and proposing one of the first CUDA-based approaches for training deep neural networks.</p><p>By 2011, researchers at IDSIA implemented GPU-accelerated deep CNN training with DanNet, achieving training speeds approximately 60 times faster than CPUs. The model also achieved superhuman performance in visual recognition competitions, representing one of the earliest successful applications of CNNs on GPUs. The major turning point that officially sparked the deep learning revolution came in 2012, when Geoffrey Hinton’s team introduced a deep CNN known as AlexNet. Trained using two NVIDIA GTX 580 GPUs, AlexNet dramatically outperformed competing methods on the ImageNet dataset and demonstrated the transformative potential of deep learning for large-scale visual recognition.</p><h3>Deep Convolution Neural Network : AlexNet</h3><p>A convolutional neural network called AlexNet originated from the 2012 paper ImageNet Classification with Deep Convolutional Neural Networks by Alex Krizhevsky, Ilya Sutskever, and Professor Geoffrey E. Hinton from the University of Toronto. This research trained a large-scale deep convolutional neural network for image classification. In the ImageNet LSVRC-2010 competition, it achieved top-1 and top-5 error rates of 37.5% and 17.0%, respectively. A variant model introduced for ILSVRC-2012 further achieved a Top-5 test error rate of 15.3% (equivalent to 84.7% Top-5 accuracy). Its performance greatly surpassed that of the second-place model at the time, delivering remarkable results. This milestone advancement demonstrated the extraordinary visual recognition capabilities that computers could achieve.</p><h4><strong>ImageNet</strong></h4><p>Computer vision research had reached a bottleneck, with researchers investing tremendous effort into designing handcrafted features and algorithms. In 2007, Professor Fei-Fei Li of Princeton University questioned whether the fundamental challenge lay in the models themselves or in the input data. She challenged the prevailing paradigm and proposed that computers should learn by analyzing different images and the similarities among their relationships. Her vision was to inject massive and diverse visual datasets into machines for training, fundamentally transforming the landscape of computer vision and artificial intelligence.</p><p>Achieving this goal required enormous effort in image annotation. Through Amazon Mechanical Turk, approximately 49,000 annotators from 167 countries participated in screening and labeling more than 160 million candidate images. By 2009, the team published a paper describing this comprehensive database containing 3.2 million images. The dataset later expanded to approximately 14 million high-quality images, each annotated three times, spanning more than 20,000 categories.</p><p>In 2009, Fei-Fei Li also collaborated with the PASCAL Visual Object Classes (VOC) Challenge. This collaboration contributed to the launch of the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) in 2010. The ILSVRC competition used a subset of ImageNet, selecting 1,000 categories with approximately 1,000 to 1,300 images per category. The challenge included both image classification across 1,000 categories and object localization tasks, establishing a large-scale benchmark that would drive rapid progress in computer vision research.</p><h4>Model Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*F4WVczXSYnnzV9mL.png" /></figure><p>The architecture of AlexNet can be broadly divided into three parts. The first part is feature extraction, which uses convolution and pooling operations. The network contains a total of five convolutional layers, some of which are followed by max-pooling layers. Max-pooling selects the maximum value within a pooling window while discarding all other values. The first two layers also incorporate Local Response Normalization (LRN), which simulates biological neural inhibition effects and improves generalization performance.</p><p>The second part consists of fully connected layers. AlexNet includes three fully connected layers, with the first two containing 4,096 neurons each, and the final layer being a 1,000-dimensional softmax classifier.</p><p>The third part comprises several key design choices that strengthened the training process. For activation functions, AlexNet replaced sigmoid and tanh with the ReLU nonlinear activation function, which converges faster and alleviates the vanishing gradient problem. Training was performed using two NVIDIA GTX 580 GPUs, with the model partitioned across both GPUs for parallel computation. The kernels in the second, fourth, and fifth convolutional layers were connected only to feature maps residing on the same GPU in the previous layer, while the kernels in the third convolutional layer were connected to all feature maps from the second layer. Dropout was introduced in the fully connected layers, randomly disabling a subset of neurons during training to reduce overfitting. Data augmentation techniques, including random cropping and horizontal flipping, were also applied to improve the model’s generalization capability.</p><p>Max-pooling: A uniform configuration of kernel size = 3 × 3 and stride = 2 was used. AlexNet adopted overlapping pooling, which helped reduce error rates and mitigate overfitting.</p><p>First Convolutional Layer: Uses 96 convolution kernels of size 11 × 11 to perform convolutional filtering on a 224 × 224 × 3 input image, with a stride of 4 pixels. ReLU activation is applied, followed by Max-pooling and Response Normalization.</p><p>Second Convolutional Layer: Uses 256 convolution kernels of size 5 × 5 to perform convolutional filtering on a 55 × 55 × 96 input, with a stride of 1 and padding of 2. ReLU activation is applied, followed by Max-pooling and Response Normalization.</p><p>Third Convolutional Layer: Uses 384 convolution kernels of size 3 × 3 to perform convolutional filtering on a 27 × 27 × 256 input, with a stride of 1 and padding of 1. ReLU activation is applied.</p><p>Fourth Convolutional Layer: Uses 384 convolution kernels of size 3 × 3 to perform convolutional filtering on a 13 × 13 × 384 input, with a stride of 1 and padding of 1. ReLU activation is applied.</p><p>Fifth Convolutional Layer: Uses 256 convolution kernels of size 3 × 3 to perform convolutional filtering on a 13 × 13 × 384 input, with a stride of 1 and padding of 1. ReLU activation is applied, followed by Max-pooling.</p><p>Fully Connected Layers: AlexNet contains three fully connected layers. The first two layers each have 4,096 neurons and use ReLU activation functions. Dropout with a probability of 0.5 is applied to these layers. The final layer is a 1,000-dimensional softmax classifier.</p><h4>Rectified Linear Unit</h4><p>Next, we discuss a very important component: the design of activation functions. In the past, the standard approach was to use Sigmoid or Tanh functions, both of which resemble S-shaped activation functions. However, in terms of gradient descent training time, these saturating nonlinear functions are significantly slower than non-saturating nonlinear functions. When the input to Sigmoid or Tanh becomes very large or very small, the gradient approaches zero, making it difficult for deep neural networks to learn effectively. The ReLU activation function is defined as: f(x) = max(0, x). When the input x is less than 0, the output is 0. This means that many neurons remain inactive for certain inputs, introducing sparsity into the network. At the same time, ReLU is computationally simple and highly efficient. In the experiments reported by the authors, under the same network architecture, models using ReLU converged nearly six times faster than those using Tanh, substantially reducing the overall training time.</p><h4>Multi-GPU Training</h4><p>At the time, the NVIDIA GTX 580 GPU had only 3 GB of memory, which was insufficient to accommodate the entire large-scale network. Therefore, the researchers distributed the network across two GPUs. GPUs were particularly well suited for cross-GPU parallelization, as they could directly read from and write to each other’s memory without passing data through host memory.</p><p>At the same time, communication between GPUs was restricted to specific layers, reducing the overhead associated with data exchange. The pattern of selective connections was determined through cross-validation to achieve an optimal balance between communication costs and computational efficiency.</p><p>This approach reduced the top-1 and top-5 error rates by 1.7% and 1.2%, respectively. Furthermore, the training time of the dual-GPU network was slightly shorter than that of the single-GPU network.</p><h4>Local Response Normalization</h4><p>Because ReLU itself is non-saturating, it does not require input normalization to prevent the vanishing gradient problem. However, the authors found that introducing Local Response Normalization (LRN) helped improve the model’s generalization ability.</p><p>LRN was inspired by the concept of lateral inhibition in biological neurons, creating competition among neurons. If a particular neuron produces a strong activation, it suppresses the activity of neighboring neurons, making feature extraction more selective. At the same spatial position (x, y), the responses of neighboring convolution kernels are normalized together. For example, when the parameter n is set to 5, the output of the i-th feature map at a given location is normalized using its own activation along with the activations from the two preceding and two following feature maps, for a total of five feature maps.</p><p>This mechanism encourages neurons with strong responses to stand out while reducing the influence of weaker neighboring responses, thereby enhancing feature discrimination and improving generalization performance.</p><p>However, modern CNN architectures no longer use this normalization approach, and it has largely become obsolete outside of early networks such as AlexNet. It has been replaced by Batch Normalization (BN), which normalizes all feature maps within an entire layer simultaneously. Batch Normalization is computationally more efficient, stabilizes training, accelerates convergence, and generally provides better performance in deep neural networks.</p><h4>Data Enhancement</h4><p>In the study, the authors proposed two methods to combat overfitting.</p><p>The first method was data augmentation through image translations and horizontal reflections. From each original image of size 256 × 256, a random 224 × 224 crop was extracted, and its horizontally flipped version was also used for training. Theoretically, this increased the effective size of the training dataset by a factor of 2,048. This approach enabled the model to learn invariance to object position and orientation, thereby improving its generalization ability.</p><p>The second method was color intensity perturbation. Principal Component Analysis (PCA) was applied to the RGB pixel values across the entire training set to model the principal variations in color distribution. This technique approximately captured an important characteristic of natural images: the identity of an object remains unchanged despite variations in illumination intensity and color. During training, random perturbations were added along the principal components of the RGB values, creating realistic color variations in the input images.</p><p>This color augmentation strategy further improved the model’s robustness to lighting and color changes and reduced the Top-1 error rate by more than 1%.</p><h4>Dropout</h4><p>During training, each hidden neuron was randomly dropped with a probability of 50%. A dropped neuron did not participate in either the forward pass or the backpropagation process. As a result, every time a training sample was presented, the network effectively formed a different random subnetwork. Although these subnetworks varied from iteration to iteration, they all shared the same set of weights.</p><p>This mechanism prevents neurons from developing excessive co-dependencies, forcing each neuron to learn more robust and generalizable features independently. As a consequence, Dropout acts as an effective regularization technique that reduces overfitting and improves the model’s ability to generalize to unseen data.</p><p>In the early era of large neural networks, Dropout played a particularly important role. However, in modern deep learning architectures, it is used much less frequently or has nearly disappeared in many computer vision models. This is largely because Batch Normalization helps stabilize training and provides a regularization effect that reduces overfitting. In addition, modern network architectures and large-scale datasets naturally mitigate some of the overfitting issues that were common in earlier models. Since Dropout also slightly increases training time and computational cost, its use can become expensive in very large networks, making it less attractive compared with other regularization techniques.</p><h4>Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*sGSOuAz5ACDF4zwc.png" /></figure><p>The success of AlexNet was not only due to its breakthrough in image classification accuracy at the time, but also because it demonstrated the powerful capability of deep Convolutional Neural Networks (CNNs) for large-scale image recognition. Through techniques such as multiple convolutional layers, ReLU activation, Dropout, and data augmentation, it was able to automatically learn useful features from millions of images and even distinguish subtle differences.</p><h3>Conclusion</h3><p>The creator of the perceptron, Frank Rosenblatt, envisioned showing objects to a machine and having it recognize those objects. Sixty years later, we finally achieved that goal. He was on the right path; it simply needed to be repeated a million times. At the time, researchers did not yet know how to train multilayer networks, but in retrospect, his algorithm remains the foundation of how we train deep neural networks today.</p><p>Modern deep learning also owes much to the efforts of pioneering researchers such as Geoffrey Hinton and Yann LeCun. From the Neocognitron and the first CNN, LeNet, to the emergence of AlexNet in 2012, this journey involved numerous technological breakthroughs and advances in AI algorithms and models. AlexNet can be regarded as a starting point for modern deep learning and computer vision. After its success, an enormous amount of research on deep learning and CNNs began to emerge.</p><p>Researchers continuously proposed deeper and more sophisticated network architectures, such as VGG, GoogLeNet, and ResNet. At the same time, a variety of convolution techniques and training methods were developed, enabling CNNs to achieve remarkable success not only in image classification, but also in object detection, semantic segmentation, generative models, and many other domains.</p><p>Subsequent discussions will further explore the details and principles of the more advanced CNN models that followed AlexNet, introduce major research milestones in deep learning and artificial intelligence, provide a deeper understanding of modern computer vision AI, and present an overview of its widespread applications across various industries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03399423e184" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision : Chapter 1  (Traditional Chinese)]]></title>
            <link>https://medium.com/@john20050826/computer-vision-chapter-1-traditional-chinese-c2c742f9b7c1?source=rss-a590a0c11a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2c742f9b7c1</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Jiaen]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 16:45:24 GMT</pubDate>
            <atom:updated>2026-06-20T16:45:24.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xegcy1_cnMR3mx3CwEvJvQ.jpeg" /></figure><h3>Computer Vision : Introduction to CNN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ig3vwZcxKf4y_MW3vY3rHw.jpeg" /></figure><p>在現今AI 科技時代，自動輔助駕駛、 OCR 文本辨識又或是物品作物分析等等自動化應用，這些應用的背後，都有一個強大的智能系統能夠看懂理解影像內容，這便是電腦視覺這個領域核心理念，機器能夠從圖像或者多維資料中取得或理解資訊，當中的視覺辨識主流技術，卷積神經網絡 ( Convolutional Neural Networks, CNN ），此種深度學習模型的發展是基於影像處理與生物神經網路理論長期演進的結果，從圖像中提取出抽象的特徵，再用這些特徵來判斷物體、辨識文字，甚至重建影像，而 CNN 的一大特點即為「卷積」，能夠從圖像中萃取特徵，再送到下一個卷積層做進一步的特徵萃取，憑藉這種層層深入的學習方式，CNN 在各種影像識別任務中都表現優異，本文將帶你拆解 CNN 的核心概念，了解它是如何運作的，追溯這項技術的演化脈絡，並詳細的說明卷積具體是甚麼以及機器是如何能夠學習並理解影像的。</p><h3>Convolution</h3><p>卷積 (Convolution) 運算在數學上的定義為 指將函數<em> f ( x ) </em>與 <em>g ( u — x )</em> 相乘，並對<em> x</em> 在全域上進行積分運算。 其中<em> x </em>可表示時間、空間或頻率等，視應用領域而定，包括時間、頻率或空間，卷積運算的結果會得到一個關於新變量 <em>u </em>的函數，這個函數的定義域會與原來的變量相同，計算公式如下 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kezHuWoxZmDmzu27YmQ11Q.png" /></figure><p>通常使用卷積的核心目的是描述線性時不變系統（LTI）的響應，輸入信號 f(x) 作用於系統時，它的總體反應是什麼？對於上述的卷積運算 f(x) 代表系統的輸入信號，g 函數則是定義了一個系統的響應函數，此 g 函數將是固定的一套模式函數，最終就會輸出所有過去累積下來的系統輸出。舉個例子 ，在信號與系統中，卷積定義為系統輸入信號<em> f ( x )</em> 對單位脈衝的衝激響應的函數 g ( t ) 所以此運算表達，當要想知道第 u 單位時間系統輸出，就對所有 x 進行<em> f ( x ) g ( u — x ) </em>的積分 ， 其中可見 <em>g(u — x) </em>當脈衝在時間 x 作用時，系統在時刻 u 的響應。</p><p>而在數位訊號、圖像處理或離散系統中，卷積積分轉為離散求和，定義為：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDlAgbAk5CChvsDl0n-ejg.png" /></figure><p>x [ k ] 離散輸入的序列中第 k 點樣本值，h [ n — k ] 是在第 k 個點取樣作用後到第 n 個取樣時刻的系統響應，所以對應 g ( t ) , t = n — k 。因此，在這裡它描述了一個函數如何被另一個函數所影響，這樣的作法思想認為輸入訊號可以表示成一系列脈衝的加權組合 ( superposition principle )，任意的訊號輸入 x[ k ] 可以表示成許多個單位脈衝 δ [ n−k ] 的組合，而透過這樣乘積後加總表現出其輸入訊號的強度與系統如何對每個輸入反應。在這裡我認為，卷積在數位訊號處理或圖像處理中代表的意義便是，我們試圖在混亂不穩定的輸入 X 中，通過使用某種特定工具或模板 ( kernel / 脈衝響應 ) 來對其試驗，找出我們想要的資訊反應，在這裡可以將「LTI 系統」想像成是一種穩定、可以預測的訊號處理工具，而輸入 x[n] 則是任意、可能雜亂的資料來源。</p><p>概念上來說，這些卷積運算中的響應函數被視為一種 Linear Time-invariant System ( LTI 系統 ) ，其具備線性性質 + 時不變性，系統的行為由一個固定的 kernel h[n] 決定，且它對所有輸入都是一樣的處理邏輯，並且它對時間平移的輸入有相同時間平移的輸出，某種程度上當知道系統對最基本輸入的反應，就能計算對任意複雜輸入的反應。</p><p>為了更直觀理解上式說明，以下來用一個直觀案例說明一下 :</p><blockquote>想像一下現在是除夕夜，有很多的煙火在釋放，我們想要在一天放煙火的活動結束後，計算清楚放煙火結束後的時刻空氣中目前存在有多少煙霧量，在此問題，我們可以定義時間單位為分鐘，以離散方式計算。首先，我們可以先假定放一個煙火到空中爆炸後產生 X 量的煙霧在空氣當中，但是他會著時間，每分鐘逐步消散減少其量，我們把這個煙霧會隨單位時間而減少的情況，定義為一個函數 ，為剩餘百分比。稱其為 Smoke Function : <strong>S ( 0 ) = 1 , S ( 1 ) = 0.86 , S ( 2 ) = 0.63 , S ( 3 ) = 0.45 , S ( 4 ) = 0.2 , S ( 5 ) = 0</strong> S ( t ) 為一個響應函數 ，當燃放一個煙火所產生的量並在 t 秒後會逐漸減少消散， 接著我們會有另一個函數 叫他 Fireworks Function , F ( t ) 他表示了我們每一分鐘時段分別燃放多少個煙火，當我們在第 1 分鐘放了5個煙火就表示成 f ( 1 ) = 5 ，那當我們算到第 3 分鐘時， 原先在第1分鐘放的煙火所產生煙霧量現在只剩 F ( 1 ) * S ( 3–1 ) 的煙霧量 : 5 * 0.63 。<br>示範情況 F 函數等於 F ( t ) = [ 3 , 5 , 2 , 3 , 2 , 1] ， Index 代表 第 n 分鐘 。 所以這個問題我們就可以用離散的卷積表示來求出在第 T 分鐘時刻時空氣中的煙霧量。使用卷積運算來計算看看空氣中煙霧量，求第 2 分鐘的話，就會寫成 F ( 2 ) * S ( 2–2 ) + F ( 1 ) * S ( 2–1 ) + F ( 0 ) * S ( 2–0 ) ，那麼以下 ，Smoke 函數為 ，如果要算 的空氣中煙霧總量，視覺化呈現下來就會如下：</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37ubqPM1xaZcIeEUm-LAnA.jpeg" /></figure><pre>h = [ 1 , 0.86 , 0.63 , 0.45 , 0.2 ]<br>x = [ 3 , 5 , 2 , 3 , 2 , 1 ] <br>y = np.convolve(x, h , mode=&#39;same&#39;) # Convolution Computation</pre><p>會發現當到 t = 5 時 ，會代入 S ( 0 )並相乘，而前一分鐘則要乘上 S ( 1 )，以此類推，會發現兩者函數是反過來的，在時間軸上最右邊的點是最晚進去系統的點，因為最右邊的點最晚發生。而最左邊的點是最早進入系統的點，所以可以將卷積寫成將 x 左右翻轉進入 g 函數 。也因此可以用第二種方式來看這個卷積運算過程，也有是通過 <em>Sliding Window </em>算法逐步滑過整個時間域，從 0 開始到 T 結束，就會產生 T 大小的新函數，就會是一個函數描述在時間 t 時空中的煙霧系統存量。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*hsd-YTaksmnJSUJxP4-ejg.png" /></figure><p>這樣的卷積運算其實就是規範了其他的點是如何對現在這個點產生影響的，輸出函數與輸入在同一參數域 ( 如時間或空間 ) 上定義，他是由現在所關注的這些點所構成的一個權重矩陣，因為在煙火這個例子中所用的是時間，他的輸出只受過去時間影響，但假如今天問題包含時間軸向後的未來也會對現在的點產生影響，那這個窗口就會變得不一樣了。</p><p>從幾何的角度來說，我們可以只設計那個窗口的參數就可以了， 在二維空間中若希望計算的是每個位置受到周圍一圈點對現在點的總影響，就可以用二維卷積顯示輸入矩陣，經過某種影響規則 ( kernel ) 之後的輸出卷積轉換後分布函數，其 kernel 就表示了範圍內的點對當前點造成了甚麼樣的影響，那麼就可以把 Kernel 規則定義以矩陣出來，二維離散卷積表達如下 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAxIDvxY7KNCg53huUEhtA.png" /></figure><p>那麼這個運算式就會是二維離散空間卷積的計算方式，就可以應用在二維圖像處理上了 ，輸入的圖像可以類比為一種二維訊號，在局部範圍內將影像與 kernel / filter 做滑動內積比較的方式，就會產生出結構相似性的偵測圖，前面提到說複雜的函數可以透過 LTI 系統分解，圖像在此就像是紊亂的輸入函數，而通過堆疊簡單特徵卷積可以進行圖像的處理，也因其平移不變性，特徵不會因物體移動而遺失。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgaLulxmoICHANK21NCdiA.gif" /></figure><p>儘管運算式已經完整地將其在二維空間上運算表現清楚了，回顧先前說明 煙火案例時，可以將原始數學卷積定義改成反轉後的滑動窗口加總運算，那是否意味著將二維訊號處理轉變成滑動窗口的計算時需要進行反轉呢 ? 或是說這樣的反轉有意義嗎 ? 順著這樣的疑惑，當我們來到了二維的圖像操作時，原始卷積的數學定義已經不太一樣了，其原因可能是圖像處理多關注幾何意義，而非系統響應意義，或是有些圖像處理設計上其 Kernel 是對稱的，而在像是 OpenCV 中運算的寫法更像是名為cross-correlation的概念，其原用於測量相似度，但不需反轉地滑動對齊，基本上來說其他計算皆與卷積沒有差別，可能是因為更注重幾何視覺意義，也可能是早已約定俗成的命名方式。</p><p><strong>Reference :</strong><br><a href="https://www.youtube.com/watch?v=KuXjwB4LzSA">But what is a convolution?</a><strong><br></strong><a href="https://www.analog.com/media/en/technical-documentation/dsp-book/dsp_book_ch6.pdf">The Scientist and Engineer’s Guide to Digital Signal Processing<br>Convolution</a><strong><br></strong><a href="https://www.youtube.com/watch?v=QmcoPYUfbJ8">What is convolution? This is the easiest way to understand</a><strong><br></strong><a href="https://en.wikipedia.org/wiki/Cross-correlation">Cross-correlation</a><strong><br></strong><a href="https://www.youtube.com/watch?v=D641Ucd_xuw">从“卷积”、到“图像卷积操作”、再到“卷积神经网络”，“卷积”意义的3次改变</a><br><a href="https://liam.page/2017/07/27/convolutions-and-convolution-neural-network/">谈谈离散卷积和卷积神经网络</a></p><h3>卷積圖像操作與特徵提取</h3><p>在電腦科學中，圖像這樣的資料被視為二維的函數進行處理，在影像處理的應用上，卷積則成為一種基本的過濾操作，透過將一張影像與一個 kernel（卷積核）滑動窗口進行運算，產生變換後的另一幅影像；利用卷積計算範圍內各個點對當前像素點的加權影響，經過加總後，作為新的像素值，以此做矩陣乘法即卷積的簡化。</p><p>隨著數位計算與影像科技的發展，卷積開始廣泛應用於圖像處理領域，成為實際運作於影像上的「濾波器 ( Filter )」工具，Filter 指的是通過、修改或拒絕影像中指定的頻率成分，可以用來提取邊緣、紋理、形狀等圖像特徵，在數位影像處理中稱為空域濾波器。透過設計不同的卷積核，達到各自的特徵提取效果，例如Sobel 濾波器主要用於偵測邊緣方向，而 <em>Gaussian</em> 濾波器則用於圖像的平滑與去雜訊，依賴這些手工設計的卷積濾波器來進行低階特徵提取，然後再結合Feature Descriptor與機器學習完成圖像分類與辨識的任務。</p><h4>1. Preprocessing</h4><p>卷積的Filter有兩種常用於前處理，Smoothing與Sharpening Filter ，用於讓圖像更乾淨、更清晰、更有辦法辨識，Smoothing Filter 透過應用低通濾波器來減少影像中雜訊和精細細節的技術，減少像素值細微變化的影響使其更易於分析，另一個用途是消除因灰階級數不足而出現的假輪廓，常見 Box/Mean Filter 、 <em>Gaussian Filter、Bilateral filter、Median filter</em> 。 銳化則處理用以強調影像中亮度的突變處，用高頻濾波器的原理抑制低頻，強化圖像中紋理和邊緣，增強特徵品質，最為基礎的Laplacian拉普拉斯算子基於二階導數總和測量圖像中某點與周圍鄰居變化的曲率來達到銳化效果。</p><h4>2. Edge Detection</h4><p>圖像中的邊緣元素是由於數位影像中的亮度數值的急劇變化所顯現的，通常對應到物體的輪廓、紋理轉折或形狀邊界，是影像中最關鍵的區別性特徵之一，邊緣檢測的目的，就是凸顯變化強烈的區域，同時弱化平坦背景，為後續的圖像分析與辨識提供更精準的結構線索，使電腦聚焦於影像中最有資訊價值的部分，而關注訊號中的變化量的方法便是使用微分導數，在二維圖像上通過設計兩分量的導數梯度計算，而一階導數的尖峰正好對應影像的邊緣。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2G9HkctP5cm4r0sft83UVQ.png" /></figure><p>自電腦視覺與計算幾何領域開創之初，開創者 <em>Lawrence Roberts</em> 在1963年發表的論文 <em>MACHINE PERCEPTION OF THREE-DIMENSIONAL SOLIDS</em>，認為對固體物體的感知是一個可以基於三維變換和自然規律的過程，應該考慮物體在空間中的形狀、位置、方向等資訊，對線條畫圖像進行分析實驗，在論文中提出一種方法把實際影像抽象為邊界與輪廓線 — <strong>Robert Cross Operator</strong> 。</p><p>Roberts Cross 基於一階微分的邊緣檢測卷積算子，也正是首次提出用卷積方法偵測邊緣輪廓，作為構建電腦視覺系統、從 2D 還原 3D 物體的起點，使電腦能夠理解圖像的結構或特徵，根據Roberts的說法，他嘗試過很多不同的圖像上進行微分運算的方法，總結提出觀點，認為正確的選擇運算子非常關鍵，生成的邊緣應該清晰，背景噪音應該盡可能少，邊緣的強度應該盡可能接近人類的感知，最終他選擇對角線上的差分，對角差分近似梯度，符合他提出的三個人類感知原則。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cAEOcs0o_HedNBqh0ScSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qqyJtAKfvovKHrC1GdoAQ.png" /></figure><p>隨著影像噪聲與運算實用性的挑戰，研究者發現 Robert Cross 雖然概念簡單，但對噪聲敏感，因此開始設計更穩定的算子，Sobel Operator ( 1968 ) 則在垂直方向加入加權平均，有更好的邊緣平滑效果，Prewitt Operator ( 1970 ) 加入更多水平/垂直像素的權重計算，Canny ( 1986 ) 實現高精度邊緣檢測。而在邊緣檢測步入成熟後，研究者進一步開發了更具鑑別力的結構特徵，角點偵測 ( 如 Harris-Stephens, 1988 ) 就是在水平與垂直梯度 (Sobel/Prewitt）基礎上，用局部自相關矩陣找出在所有方向上都出現強變化的轉折點；斑點偵測（如 LoG , DoG ）則以多尺度高斯模糊 ＋ 二階導數，標記出局部亮度極值區域。這兩類方法都依賴卷積運算提取梯度或多階導數響應，它們分別從角落與斑塊層面，可以從圖像提取更多樣的特徵。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOjxxoRWskszWhiXpCVj4g.png" /></figure><h4>3. Gabor Filter</h4><p>Gabor 濾波器以Dennis Gabor命名，原先為訊號處理分析方法，後由 Gösta Granlund透過添加參考方向推廣到二維，用於紋理分析、中層特徵擷取等影像處理應用，相比於前面提及的邊緣檢測、角點檢測，Gabor 提取更複雜的模式，如紋理、局部形狀或方向性特徵。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1IS0X57lv0U25usTOjQATw.png" /></figure><p>Gabor Filter 是一個卷積 Filter 其組合了高斯函數元件與正弦曲線，高斯函數提供局部性與權重，正弦波項提供方向性與頻率特性，在這裡原本正弦項寫作 exp(i(2πfx′+ϕ)) 而實際應用中，我們常常只取實部即 cos 項來進行濾波，因此也有其他地方將正弦函數寫成 cos (2πfx′+ϕ)，輸入參數 g (x, y) 為圖片 pixel 座標，λ 代表 Sine Component 波長，θ 控制方向，ψ 相位偏移控制波形的起點控制對稱性與響應方向，高斯函數的標準差代表感受野大小，γ 為空間長寬比用來控制高斯函數產生的橢圓形狀。代入所有參數後對每個(x, y)計算 Gabor 值直到矩陣數值被填完就產生一個 Kernel 了，所以可以看到有很多的參數來控制這個 Filter 是甚麼樣，就可以產生大量的 Filter 組合。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtEDTCu9ikBDNhOrXwpCJQ.png" /></figure><p><strong>Reference :<br></strong><a href="https://theswissbay.ch/pdf/Gentoomen%20Library/Artificial%20Intelligence/Computer%20Vision/Feature%20Extraction%20in%20Computer%20Vision%20and%20Image%20Processing%20-%20Mark%20S.%20Nixon.pdf">Feature Extraction and Image Processing</a><strong><br></strong><a href="https://zbigatron.com/the-early-history-of-computer-vision/">the-early-history-of-computer-vision</a><strong><br></strong><a href="https://dspace.mit.edu/bitstream/handle/1721.1/11589/33959125-MIT.pdf">MACHINE PERCEPTION OF THREE-DIMENSIONAL SOLIDS</a><strong><br></strong><a href="https://blog.roboflow.com/edge-detection/">edge-detection</a><strong><br></strong><a href="https://youtube.com/playlist?list=PLHae9ggVvqPgyRQQOtENr6hK0m1UquGaG&amp;si=WAxjZmbrP6BoEQTR">Introductory python tutorials for image processing</a></p><h4>基於 Convolution Filter 特徵提取圖像辨識</h4><p>介紹完前面基於 Convolution Filter 來做特徵提取的方式，通過人工設計卷積核或特徵提取器來輸出特徵圖，來從複雜的影像中提取特徵，除了卷積之外還有很多早期特徵提取的方式，像是LBP (Local Binary Pattern , 1994 )、SIFT ( 1999 )、HOG ( 2005 ) 等人工設計的特徵描述子，也更能在複雜圖像問題上進行識別。不過這次主要介紹卷積的應用，在這裡實驗結合 Gabor 濾波器、Sobel 邊緣檢測 為主的圖像識別方法，通過生成特徵圖，並再提取出的特徵圖上計算統計量 (平均值、標準差、能量），將這些數值作為機器學習模型的特徵輸入，訓練模型後進行分類預測，這樣的做法適用於少量圖片、低算力與傳統機器學習場景。 案例 Dataset : <a href="https://www.kaggle.com/datasets/ankit1743/skyview-an-aerial-landscape-dataset"><em>https://www.kaggle.com/datasets/ankit1743/skyview-an-aerial-landscape-dataset</em></a>。</p><pre>def extract_features(image):<br>    features = []<br>    # Preprocessing<br>    image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))<br>    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)<br>    gray = cv2.equalizeHist(gray)  # Histogram Equalization<br><br>    gamma = 0.5<br>    psi = 0<br>    # Gabor filters<br>    for theta in [0, np.pi/4, np.pi/2, 3*np.pi/4]:<br>        for sigma in [1, 2, 3]:<br>            for lamda in [np.pi/4, np.pi/2]:<br>                kernel = cv2.getGaborKernel((9, 9), sigma, theta, lamda, gamma, psi, ktype=cv2.CV_32F)<br>                filtered = cv2.filter2D(gray, cv2.CV_32F, kernel)<br>                # Common statistical characteristics<br>                features.append(filtered.mean())<br>                features.append(filtered.std()) <br>                features.append(np.sum(filtered ** 2))        # Energy<br>                features.append(skew(filtered.ravel()))       # Skewness<br>                features.append(kurtosis(filtered.ravel()))   # Kurtosis<br><br>    # Sobel edge<br>    sobel_img = sobel(gray)<br>    features.append(sobel_img.mean())<br>    features.append(sobel_img.std())<br>    features.append(np.sum(sobel_img ** 2))<br><br>    return np.array(features, dtype=np.float32)</pre><p>可以使用 skimage.filters 的 Sobel 與 OpenCV的 Gabor Filter 函式生產多種不同的Gabor FIlter 生成特徵圖，程式PAI 呼叫 cv2.getGaborKernel() ，並分別設定 kernel_size、sigma、theta、 lamda、gamma、psi 參數產生對應的 Gabor 卷積核，通過 cv2.filter2D 運算後產生卷積圖像處理後的特徵圖，再對特徵圖像計算偏度、峰度、平均值、標準差與能量值，將此回傳一組數值的特徵向量，每個 Gabor filter 提取 5 個特徵，Gabor 部分提供共 24 filters × 5 features = 120 維特徵，跟一個 Sobel Filter 提取一次，再將這組特徵向量代表此圖片的特徵輸入，輸入到機器學習模型內，像是可以使用 隨機森林模型 、LGBM 、XGBM或其他模型，紋理明顯、邊界清楚的圖像 Gabor/Sobel 有利於辨識，紋理變化大、雜訊多，若容易混淆則效果沒那麼好。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQx-EWdX_EHLW9LWYBSscw.png" /></figure><p><strong>完整程式碼 :</strong> <a href="https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/ExperimentalSeries/GaborFeatureML"><em>https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/ExperimentalSeries/GaborFeatureML</em></a></p><h3>Neural Network and Deep Learning</h3><p>人工智慧史中出現兩學派，一派認為 AI 基於規則推理、邏輯演算，另一派認為應該先明白”學習”是如何工作的，提出模仿人類思考與大腦學習的方式，後稱為連結主義，關於類神經網路與深度學習，要從一種機器學習模型說起， Perceptron ，是 1958年7月於康奈爾航空實驗室由 Frank Rosenblatt 提出的一種模仿生物神經元行為 ( Hebbian 理論 ) 而設計的簡單分類器，它也是最早的人工神經網路模型之一，感知器被認為是第一台能夠產生原創想法的機器，將輸入特徵向量乘上對應的權重值，然後激活到對應兩類項或狀態，它會進行自我調整，以便在下次做出更合理的預測，多個感知機單元彼此獨立地學習辨認不同的類別。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86Zn4qVjHgeZramVCNArjg.png" /></figure><p>透過以下的學習規則，感知機可以根據輸入 X<em>i </em>以及目標輸出 t 之間的差異，自我調整權重：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nF6lA9qe3Y8RXv1aixikHA.png" /></figure><p>這個模型在當時時代被譽為夠像人類思維一樣感知、識別、記憶和回應的機器，它的潛力令眾人驚嘆，然而，這股熱潮在 1969 年遭遇重大挫折 ，於1969年 Marvin Minsky &amp; Seymour Papert 出版”Perceptrons” 一書指出感知機的嚴重局限性，儘管當時提到多層感知器可能解決這個問題，但當時尚未有有效的訓練方法來調整多層網路的權重，然而 Rosenblatt 沒能撐過人工智慧的寒冬，於1971年離世。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*Wg55RWKo7P2pGZzruNxeeQ.png" /></figure><p>為了解決感知器的局限性，Paul Werbos 在 1974 年 ~ 1981 年的研究論文，提出利用誤差的梯度從輸出層反向傳回，利用鏈式法則（Chain Rule）來高效計算多層網路中每個參數的梯度，進而更新多層感知器（MLP）的權重，稱為 Backpropagation 算法，1986 年，David E. Rumelhart、Geoffrey Hinton 與 Ronald J. Williams 發表的經典論文 <em>“Learning representations by back-propagating errors”</em> ，將可微非線性激活函數與多層感知機、反向傳播演算法結合，透過實驗有效展示其重要性，才讓多層感知機與反向傳播真正進入主流視野。然而，這樣的熱潮只維持了一段時期，從 1985 開始直到20世紀末，神經網路研究僅在少數領域默默發展，Backpropagation 雖然理論上可以訓練深層網路，但只能訓練淺層的網路層，實務上會梯度消失/爆炸且收斂極慢，在當時它不具備訓練深層網路的硬體、技術條件與規模應用場景。Geoffrey Hinton 在 2006 年取得了一項重要進展，正式提出”深度學習”的技術理念，強調疊加多層抽象表徵學習的能力，並提出使用 Restricted Boltzmann Machines（RBMs）多層疊起來學習特徵，然後再用 backpropagation 做微調，隨著 2006–2012 年深度學習技術突飛猛進，MLP 網路模型的優化、激活函數、訓練技巧、硬體進步，才成為了現代深度學習神經網路。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Ix813HFhQWLn5lm3PrJV7A.png" /></figure><p>那要如何使多層的人工神經網路可以學習呢 ? 首先會先定義一個損失/誤差函數，用以計算預測結果與真實 Label 之間的差值，假設我們組建了一個多層感知機，當使用這個前向傳遞的網路後，此時我們將很多筆的資料對其進行預測後使用統一進行Loss Function計算，回歸任務可以使用MSE，計算預測值與真實值之間的平均平方差，分類任務則可以使用 Cross Entropy 交叉熵，即模型預測的概率分佈與真實標籤的分佈之間的差異。</p><p>目標是要損失變小 ，讓機器能夠自我優化與學習，我們便可以通過嘗試調整參數的方式來使機器學出一個函式擬和進行預測，所以這裡我們希望將 Loss 盡可能的降低也就是優化，像是在基礎的機器學習模型中，Linear Regression 要優化截距與斜率、Logistic 中想要優化曲線，諸如此類的機器學習模型都是參數上的優化調整，而 Gradient Descent 則可以是一個通用涵蓋全部的優化器概念，梯度 ∂L/∂w 表示當權種 w 上升一點點，會導致 Loss 上升多少 ，我們希望可以使用這樣的一個方法來優化多層感知機，在 MLP 人工神經網路中 ，每一個感知機神經元，分成一個 線性組合 部份 z = w^T⋅ x + b 與一個 非線性激活函數 a=σ(z) ， 為了簡化可以先關注線性組合為例 ŷ = w^T ⋅ x + b ，也就是將梯度下降用到線性回歸模型，所以基於 Chain Rule 可以做以下這樣推導來計算出更新參數數值。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6_3GrJByzGfjHKXt377Fw.jpeg" /></figure><p>然後因為在偏微分推導後可以發現本身不用做平方所以帶有方向性由於是 ŷ — y 所以代表計算結果數值若是正的 Loss 會變大，反之變小，所以在以梯度的數值作為更新變化數時是要加上一個負號，而如果直接拿梯度的數值大小作為更新步數的話可能又會太大，因此通常會乘上一個小於0的Learning Rate ，可以觀察到權重更新的步數大小是由梯度決定的，因此當在梯度大時他會調動很大，越接近谷底也就是接近 local minima 的時候就會走得慢。</p><p>若我們的神經網路只有一層的話其實就跟 Linear Regression 的差不多是一樣的，但現在這個網路每層分成了線性函數與激活函數，並且現在的神經網路有兩層或更多層互相連接，當微微調動第 L 層中其中一個感知機的參數 w 時，然後測試在大量的資料中會如何影響 Loss， 但因為整個網路有很上千上萬個參數要調整，這樣計算量將會非常龐大，因此 Hinton 的做法是通過將一次前向傳播後計算出最後的 Loss ，把梯度的計算結果，從最後一層開始計算，計算每一層權重的梯度，傳到第一層，這樣可以用動態規劃演算法的方式快速計算每一個權重的梯度，而不需要反覆計算。到這裡可能會想，為甚麼可以反向傳遞來計算權重梯度，這是利用微積分的 Chain Rule ，其實原理跟前面的梯度下降是一樣的，但在多層感知機需要考慮調整一個 w 後面會影響到往後很多函式部分，調整了在第 L 層的權重 w{i,j}^(L) ，輸出線性運算結果 z_i 後，第 i 個感知機激活函數輸出 a_i ^(L) 就會改變，接著這就會影響到第 L +1 層所有感知機中線性組合的計算結果 z^(L+1) ，這樣的整個過程就是MLP中的 ∂Loss / ∂z_i^(L)下面推導縮寫成 δ^L ，可以看到將上面說的整個影響過程寫成計算式時，想要計算 δ^L 需要算出 k 個 ∂Loss/∂z_k^(L+1) ，而它就是這邊的δ^L 往後下一層的 δ ，有一個遞迴關係，所以計算梯度時，就可以從最後一層比較好算的地方開始反向傳播與計算出權重的梯度，把所有的權重梯度都算完，再來用梯度下降來進行最佳化。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fh45I2P68lvpvYMoa-gbEA.jpeg" /></figure><p><strong>Reference :<br></strong><a href="https://news.cornell.edu/stories/2019/09/professors-perceptron-paved-way-ai-60-years-too-soon">Professor’s perceptron paved the way for AI — 60 years too soon</a><br><a href="https://arxiv.org/abs/1404.7828">Deep Learning in Neural Networks: An Overview</a><br><a href="https://youtu.be/sDv4f4s2SB8?si=aEv9SedIrg-GzG3a">Gradient Descent, Step-by-Step</a> <a href="https://gwern.net/doc/ai/nn/1986-rumelhart-2.pdf">Learning representations by backpropagating errors</a><br><a href="https://www.youtube.com/watch?v=PdGgbsM9vrc&amp;list=LL&amp;index=10">台大資訊 人工智慧導論 FAI 4.2 : Backpropagation</a></p><h3>生物視覺啟發</h3><p>現今哺乳動物的大腦皮質 ( cerebral cortex ) 位於大腦外側皮質的灰質構造，其中很大一部分都與視覺有關，於 1950 開始，David Hubel 與 Torsten Wiesel 研究哺乳類生物的視覺，研究包括動物的大腦皮質是如何處理視覺訊息的，參考自 RECEPTIVE FIELDS OF SINGLE NEURONES IN THE CAT’S STRIATE CORTEX, 1959 Hubel &amp; Wiesel 論文 ，該研究關注貓的初級視覺皮質中單一神經元對於視覺訊息的反應，他們記錄了觀察一系列貓在看見各種圖像時簡單神經元產生的訊號並由儀器紀錄，其中他們發現該特定觀察的神經元僅對於特定的且簡單的直線邊緣最為敏感，取名為簡單神經元 ( simple neuron )，測試結果中特定神經元對於特定的傾斜角度會產生反應，當群集的神經元都各自應對不同角度便可分辨360度角度特徵。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*4kzDzZQlyj4L3MZPLut1Kg.png" /></figure><p>上圖，根據不同的傾斜角度，個個簡單神經元會釋放頻率的訊號，有些角度完全沒有訊號產生，其中也有些其況會產生較明顯的頻率訊號反映。註： Receptive field 指的是這個位置里適當的刺激能夠引起該神經元反應的區域。</p><p>沿著神經通路依次整合信息來檢測新的特徵，所有神經迴路作用它們將基本訊號轉換成有用的、通常是複雜的訊息，使能夠理解視覺訊息，接下來，這些偵測直線與邊緣傾斜角度的簡單神經元會將訊號傳給一大群稱為 複雜神經元 ( complex neurons ) 的細胞，每一個神經元收到的都是被前一層數個簡單神經元處理的訊號，複雜神經元將不同角度直線組合起來，變成幾何圖形的角或是弧線等各種形狀，複雜神經元消化重組這些資訊，成為更複雜的視覺訊號一層一層的傳遞，經過數層的轉換重組變成更複雜的樣貌與視覺資訊。</p><p>受 Hubel 和 Wiesel 的觀察與視覺細胞的級聯模型而啟發， 到人工智慧領域，福島邦彦 Kunihiko Fukushima 於 1979 年提出的一種分層的多層 Neocognitron ，它被用於日文手寫字元辨識和其他模式辨識任務，並成為卷積神經網路的靈感來源，它透過基於幾何相似性識別模式來實現，非監督方式學習特徵，第一層直接從影像提取簡單幾何特徵，更高層從前一層特徵組合出更大或更抽象的形狀。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2q4NY5Da3W8_a_mZ1ilSvw.jpeg" /></figure><p>該架構中，設計了兩種交錯的層，S-cell（Simple cell 層），每一層中會有很多的 S-cell ，負責偵測影像中特定的局部特徵（如邊緣、角、曲線等），C-cell（Complex cell 層），接收多個鄰近 S-cell 的輸出，C-cell 對 S-plane 做局部加權整合與非線性，提供位置容忍，引入平移不變性，讓網路能在特徵位置稍有變動時仍正確識別，這種 S-C 交替堆疊 的結構，逐層將低階特徵組合成高階特徵，最終形成完整的模式表示，只有 S-cell 的輸入突觸具有可塑性並可被修改，在同一層中，神經元會依照”最佳刺激特徵”被分成子群，稱為 cell-plane，每個位置由一個特徵偵測器在該位置的響應值組成，經由 S-Cell 活動計算後的cell-plane 亦稱為 S-Plane，多個 Simple Cell 便會產生多組 S-Plane。每個 cell 的輸入來自前一層的反應區域，而連接拓撲與感受野是事先固定，S-cell 的權重值在學習中更新，隨著層數加深，單個 cell 的感受野變大，多次匯聚後在頂層之上增設識別層或外接分類器，其感受野覆蓋整張輸入影像，最後進行辨識。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyBfX_Nr6tajrpV8sQt6jw.png" /></figure><p>S-Cell 的運算方法，其類似於卷積圖像操作，並以上面這個運算式計算響應，該運算操作使ℓ 層第 k 個 S-plane 中、座標 n 的 S-cell 輸出為非負實數，φ 把負值截掉，selectivity 參數 r 乘以 興奮（excitatory）總和除以抑制 ( inhibitory )操作，算式中常數 1 提供基準值，確保在無輸入時分式有穩定值，興奮總和 ∑ ∑ aℓ (⋅) uc ℓ−1 (⋅) ， 把上一層所有 relevant C-planes 的對應位置輸出 ，分母部分代表抑制細胞操作可以用來歸一化 ，bℓ(kℓ) 為 S-cell 的抑制權重 uv ℓ−1 (n)，由上一層對應V-cell輸出的局部能量或平均活動指標，用 r.m.s.-type 計算，類似局部能量或向量長度，再做半波整流與選擇性縮放，V-cell + 抑制項優勢是抑制背景或高能量但「不成形」的干擾，使偵測相對於局部背景是否符合模板，達成特徵檢出與對位移與變形的容忍，當 rℓ很小時對變形容忍度高但響應弱，很大時只有極接近模板的刺激才會觸發強烈響應，只有當興奮輸入相對於局部能量夠大時，S-cell 才會有正的輸出，同時 r 決定響應的靈敏與嚴格度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*3u3JF5S6z8rMBgHhs2lzUA.gif" /></figure><p>同一個 S-plane 上的所有 S-cell 在不同位置看同樣大小的感受野，所以一個 S-plane 就代表同一種特徵在各位置的響應分佈，接著每個 C-plane 對應一個 S-plane，對其輸出做局部整合，讓同一特徵在附近位置的偏移不會讓反應消失。那特徵要如何學習出來呢? 這裡使用的是無監督競爭學習，對於位置n，先算出該位置所有 S-plane 的輸出us，輸出最大的那個 S-plane 是勝者，只有它更新權重，其他不動，避免多個平面學到重複的特徵。權重更新使用 Hebbian-like，把勝出時看到的局部輸入往模板裡加權平均融合，之後會做非負與歸一化，保持模板穩定、可解釋，訓練是分層進行先把 S1 學好，所有 S-plane 都收斂，再固定 S1，讓輸入經 S1→C1 變成較穩定的圖，再用它來學 S2，以此類推，整個架構，S 細胞在第一層是 5x5 的，但其餘 S 層都是 5x5x24 的 ，對於 C 細胞，前兩層是 5x5 的，最後一層是 2x2 的。</p><p>Neocognitron 展示它能處理平移、變形、局部遮擋仍能辨識的能力，這在當時的手工特徵 + 分類器等方法中是很難做到的，提出了層級式特徵提取 + 區域不變性，並且提出新的視角透過機器學習特徵取代當時機器學習費力耗時的手工特徵工程，並且對旋轉和平移有良好容忍度，但對雜訊敏感，需要大量資料才能泛化良好。</p><h3>First Convolution Neural Network : LeNet</h3><h4>LeNet-1</h4><p>最早的CNN起源自Yann LeCun 為首團隊於1989 的研究，<strong>Backpropagation Applied to Handwritten Zip Code Recognition </strong>，透過設計一個包含一定數量關於任務的先驗知識的網路架構，可以獲得對複雜任務的良好泛化，提供來自任務領域的約束，可以大大增強學習網路的泛化能力，單一網路學習整個辨識操作，從字元的標準化影像到最終的分類。其中提到的基本設計原則是盡量減少神經網絡中的自由參數數量，但又不能過度減少其計算能力。這個原則的應用可以增加正確泛化的機率，因為它會導致一個具有特化架構的網絡，這種架構有著較低的熵，系統內信息量的減少，和較低的Vapnik-Chervonenkis維度，這樣的設計使得神經網絡更傾向於有效地處理複雜的圖像辨識任務，而不至於陷入過度擬合 ( overfitting ) 的情況。</p><p>他們將 反向傳播演算法 ( backpropagation ) 應用到一個實際的問題上 ，辨識從美國郵件中取得的手寫數字，這次的神經網絡是直接接受「影像」作為輸入，而不是先經過處理後產生的「特徵向量」。早期的做法通常會經過 特徵工程 的處理過程，人工設計和提取特徵向量，讓機器學習演算法處理這些特徵。此篇論文便是要突破這種人工選特徵的限制，讓神經網絡自己從原始圖像中學出有用的特徵。在 Zip Codes 任務上，數位影像的尺寸各不相同，但通常約為 40 x 60 像素。然後套用線性變換，使影像適合 16 x 16 像素的影像。產生的影像不是二值影像，而是具有多個灰階，因為原始影像中可能存在數量不定的像素落入目標影像中的給定像素。每個影像的灰階都經過縮放和平移，使其落在 -1 到 1 的範圍內。</p><p>識別的其餘部分完全由多層網路完成，網路中的所有連接都是自適應的，儘管受到嚴格約束，並使用反向傳播進行訓練。先前傳統視覺模式辨識的研究就發現，先萃取局部特徵 ( 如邊緣、角落 ) ，再組合成更高層的特徵 ( 如圖形或數字形狀 ) ，效果會比較好，這就是從簡單到複雜的層次辨識思想，也就是後來 CNN 的基礎。</p><blockquote>“Such knowledge can be easily built into the network by forcing the hidden units to combine only local sources of information.”</blockquote><p>知識可以直接被嵌入神經網絡中是透過方法，限制隱藏層單元只能接收影像的「局部區域」作為輸入，不是每個神經元都看到整張圖片，而是只看它那一小塊，像是圖片的一個小角落，就模仿了人類視覺系統的局部感受野 (receptive field)。</p><blockquote>“Distinctive features of an object can appear at various locations on the input image. Therefore it seems judicious to have a set of feature detectors that can detect a particular.”</blockquote><p>物體的特徵可能出現在圖像中任何位置，這裡提出最好的作法是設計一組特徵偵測器，能在圖片各處都去尋找同樣的特徵，這也就是小卷積核配合滑動窗口算法的核心思想，這樣不但能找出各處的同類特徵，也大幅減少參數數量，同時保持位移不變性，也就是會產生所謂的 Feature Map ，圖片經由同一組特徵偵測器掃描後產生的特徵圖。</p><p>透過 Weight Sharing，可以讓神經網絡在輸入影像的任何位置都能偵測到相同的特徵，反映其中架構的 translation invariance 之特性，多個神經元之間的連線會共用同一組權重參數，卷積核是一組固定的參數，因此只需訓練這些少量參數。</p><blockquote>“Weight sharing not only greatly reduces the number of free parameters in the network but also can express information about the geometry and topology of the task.”</blockquote><p>該策略的重點不僅在減少欲訓練的參數，它還可以捕捉輸入資料中的幾何與空間結構，整個所產生的 feature map 亦是代表了這個特徵在哪裡出現的一張反映圖像。</p><p><strong>架構雛形 ：</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*XSJwj2oydzvdgVyBpfzfMA.png" /></figure><h4>LeNet Develope</h4><p>後續的研究與改進，LeNet 2 發表於 1990 年 Handwritten zip code recognition with multilayer networks , 1990 在美國郵政局提供的郵遞區號數位辨識率為 92%，替換率為 1%，拒絕率為 7%，LeNet-2 和 LeNet-3 引入了更深的層級和更複雜的設計選擇，逐步提升了網路容量，同時仍保留了學習分層特徵表示的核心思想。真正的突破來自 1994 年版 LeNet-4 ，Yann LeCun 主導建立 MNIST ( National Institute of Standards and Technology database ) 資料庫 ，而原先的LeNet 並不足夠面對這樣的大量數據，因此 LeNet-4 旨在適應更大的資料庫與泛化能力提升，1998時又再更優化而發布了 LeNet-5。</p><h4>LeNet-5</h4><p>經過10年的研究改進，Yann LeCun 與 Yoshua Bengio 等人於 1998 年發表Gradient Based Learning Applied to Document Recognition，可以說是最早被廣泛應用的CNN，論文至今已有 7 萬引用數，LeNet 的設計希望依靠更多的自動化學習、減少手工設計的啟發式規則，可以構建更好的模式識別系統，傳統方法的一個主要問題是，識別準確度很大程度取決於設計者能否想出合適的特徵集，論文中提到近些年中技術演進背景，關鍵轉變是高速硬體普及、可用的大型資料集、能處理高維輸入的學習演算法。CNN的解決方式使用權重共享與局部感受野，自動獲得平移不變性，並且本身卷積核保持了圖像拓譜，能夠參考鄰近像素之間的局部相關性，有效捕捉局部特徵，並逐步組合成更高階的特徵。</p><p><strong>LeNet -5 的架構</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pm1e0Xb3McOV_SO1rxYgsg.png" /></figure><p>第一層 ( C1 ) 是卷積層，具有 6 個可學習的卷積核，每個卷積核設為 5 × 5，stride 為 1 ，無 padding，輸出產生 6 張對應的特徵圖，特徵圖的大小為 28 × 28，156 個可訓練參數。<br>第二層 ( S2 ) 則進行一個 Subsampling 子採樣，對特徵圖做平均池化操作，操作用的平均卷積核大小為 2 × 2，stride 為 2，使其感受野互不重疊，並通過 Sigmoid 或 Tanh 激活函數，下降到 14 × 14 大小的特徵圖，S2 層共有 12 個可訓練參數。<br>第三層 ( C3 ) 卷積層，具有 16 個卷積核，核大小 5 × 5，stride 為 1 ，無 padding，LeNet 這裡將前六個特徵圖規定計算為由來自 S2 的連續 3 個特徵圖，接下來 6 個為 S2 的連續 4 個特徵圖，3 個為不連續 4 個，最後 1 個計算全部六個，每個輸出特徵圖的像素點為各個輸入特徵圖進行卷積後計算的總和值，C3 共 1,516 個可訓練參數。<br>第四層 ( S4 ) 子採樣層，參數配置與第二層 ( S2 ) 一致，激活後生成 16 個特徵圖，特徵圖大小為 5 × 5，32 個可訓練參數。<br>第五層 ( C5 ) 卷積層，120 個卷積核與輸出對應特徵圖，卷積核大小 5 × 5，每個卷積核為全連接設計。<br>第六層 ( F6 ) 是一個MLP全連接層，包含 84 個單元，以連接MLP輸出層，這裡由於是展示 MNIST 手寫數字識別系統，因此輸出為 10 個數值，對應每一種類別的機率。</p><p>在損失函數的設計上使用均方誤差，雖然簡單但在分類任務有缺陷，缺乏類別之間的競爭效果，且可能導致網路參數崩塌，提出類似於 softmax + cross-entropy 的方法，透過對數後驗機率讓正確類別的分數提高，同時壓低錯誤類別，增強了分類的判別力。論文最後在附錄中介紹了幾個重要的訓練技巧，激活函數設計採用近似 sigmoid 的 tanh 變體，權重初始化針對共享參數設計合適的初始化策略，最佳化優化器使用隨機版 Levenberg-Marquardt 演算法，比單純 SGD 更快，這些細節確保了 LeNet-5 能在當時的計算資源 ，使用CPU無 GPU下有效訓練。</p><pre>class LeNet5(nn.Module):<br>    def __init__(self):<br>        super(LeNet5, self).__init__()<br>        self.conv1 = nn.Conv2d(1 ,6  , kernel_size=5, stride=1, padding=0) # C1<br>        self.conv2 = nn.Conv2d(6 ,16 , kernel_size=5, stride=1, padding=0) # C3<br>        self.conv3 = nn.Conv2d(16,120, kernel_size=5, stride=1, padding=0) # C5<br>        self.fc1 = nn.Linear(120, 84)  # F6<br>        self.fc2 = nn.Linear(84, 10)   # Output layer<br>        self.tanh = nn.Tanh()<br>        self.pool = nn.AvgPool2d(kernel_size=2, stride=2)<br><br>    def forward(self, x):<br>        x = self.tanh(self.conv1(x)) # C1 : Convolution + Activation<br>        x = self.tanh(self.pool(x))  # S2 : Subsampling + Activation<br>        x = self.tanh(self.conv2(x)) # C3 : Convolution + Activation<br>        x = self.tanh(self.pool(x))  # S4 : Subsampling + Activation<br>        x = self.tanh(self.conv3(x)) # C5 : Convolution<br>        x = x.view(x.size(0), -1)  <br>        x = self.tanh(self.fc1(x))   # F6 : MLP Linear Fully Connect<br>        x = self.fc2(x)              # Output layer<br>        return x</pre><p><a href="https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/ExperimentalSeries/LeNet_MNIST"><em>https://github.com/JiaenSuen/VisionLab/tree/main/ImageClassification/ExperimentalSeries/LeNet_MNIST</em></a></p><p>使用程式來實現還原論文中的模型，實作方式使用 PyTorch ，但不同的是以現今深度學習框架套件來實作 CNN，與文獻中所述不同的是現在的卷積層都是被設計為全連接，而池化層的參數則是不進行調整學習，使用現今的 GPU 資源訓練 LeNet 辨識 MNIST 皆可在幾分鐘內快速完成，訓練 Epoch 10 次後，於 MNIST 測試資料集實驗結果可達到 98.76% 準確率。</p><p>在當年他們測試了很多方法，論文中顯示了這些分類器在 10,000 筆測試集上的原始錯誤率，其中使用人工扭曲資料增強訓練的 Boosted LeNet-4 表現最佳，錯誤率為 0.7%，隨後的是做了人工扭曲資料增強的 LeNet-5，錯誤率為 0.8%，用一般的 LeNet-5 則為 0.95% 。此外，使用傳統方法搭配人工扭曲資料增強 V-SVM poly 9 可達 0.8%，結果接近 CNN。</p><p>同時，亦展示了CNN這項技術在現實世界場景、OCR 的成功應用，並將梯度式學習的概念引入來對模型最優化，對於多層或多模組系統，為了從單字符識別擴展到文件中單詞與句子的識別，引入了將多個模組結合、以減少整體錯誤率的概念，當需處理可變長度對象（如手寫單詞）時，必須操作有向圖，在內文展示了一種名為 Graph Transformer Network (GTN) 概念，能訓練整個多模組系統以最小化全域錯誤，而 LeNet-5 作為可訓練的分類器模組整合至 GTN 中並與其他模型連接，整個系統架構包含區域定位、區域切割、字元辨識模組、語境後處理模組與圖形轉換模組，所有模組的參數同時用 Backpropagation 與 Gradient Descent 優化。</p><p><strong>附錄 : CNN特徵圖大小計算式</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nzlAHeS1_lO0ZDaWieqxA.png" /></figure><h3>二十一世紀初的發展</h3><p>LeNet 的成功是在 MNIST 這種小資料集、低解析度下取得的，在手寫數字、郵政系統等小範圍得以應用，但如果換成更真實的資料 ( 例如彩色影像、上百類別 ) ，網路需要更深、更寬，參數數量會大幅增加，當時的 CPU 無法有效處理深度 CNN 的訓練，導致大型 CNN訓練不起來。當時深層網路面臨如梯度消失、過擬合、訓練困難等問題，使得訓練深度模型在實務中非常困難，當時，學術界主流仍偏好使用 手工特徵 ( SIFT ,1999、HOG ,2005 ) + SVM ( 支持向量機 ) ，因其在當時較小的資料集上容易訓練且表現穩定。 2006 年 Geoffrey Hinton 提出以 RBM 疊堆的 Deep Belief Network ( DBN ），並正式提出深度學習的概念，重燃深度網路的研究熱潮，Andrew Y. Ng 與同事提出 Convolutional Deep Belief Networks ( 2009 ) ，把無監督學習帶入卷積架構，強調平移不變與可擴展性，更為關鍵的發展是在 2010–2012，研究使用更好的激活與初始化，Bordes、Bengio 展示 Deep Sparse Rectifier Networks 的強大實務表現。ReLU 緩解梯度消失、帶來稀疏性，讓從隨機初始化直接訓練深網變得可行，CUDA 推出後，學界把矩陣運算搬上 GPU，加速訓練效率，以及大規模資料與基準，CIFAR、ImageNet 等大量資料，由於深度學習核心是從表徵學習，這要求有豐富的變化，因此大量資料的資料集使得深度學習的優勢開始出現。</p><p><strong>GPU 提高訓練效率</strong></p><p>現今，GPU 已成為深度學習領域不可或缺的工具，它們的架構和運算能力使它們非常適合神經網路訓練的高度並行性，GPU 的平行性透過累積大量輸入特徵向量和權重向量，然後將多個內積運算轉換為一個矩陣運算來充分利用，GPU 設計有大量內核，可以同時執行多個操作，因此對神經網路來說可以實現很好的平行處理與通量問題。這樣的歷史可以追溯到 2004 年，Kyoung-Su Oh 和 Keechul Jung 在 ATI Radeon 9700 Pro 顯示卡上訓練了一個三層前饋網絡，速度提升了 20 倍，以及 2005 年，微軟研究院和史丹佛大學的 Patrice Y. Simard 團隊在 ATI 和 Nvidia GPU 上嘗試訓練一個兩層前饋網路。2006 年，Kumar Chellapilla et al. 等人研究，首次將使用 GPU 應用於訓練 CNN，訓練速度比等效的 CPU 實作快 4 倍，2009 年，由 Andrew Ng 領導的另一個史丹佛大學團隊 ，使用 30 個 Nvidia GTX 280 GPU 訓練深度信念網路 ( Deep Belief Network ) ，速度提升約 70 倍，並首次提出了使用基於 CUDA 的 GPU 訓練深度神經網路的方案。到了 2011 年，於 IDSIA 實作 GPU 加速的深層 CNN ( DanNet ) 訓練，速度比 CPU 快 60 倍，並在視覺辨識競賽中取得「超越人類」的表現，是首個 GPU 上成功應用 CNN 的案例， 正式開啟深度學習熱潮的轉捩點為 2012 年，由 Geoffrey Hinton 團隊推出一個深層的 CNN ， AlexNet，使用兩張 NVIDIA GTX 580 GPU 訓練，在 ImageNet 資料集上大幅領先其他方法。</p><h3>Deep Convolution Neural Network : AlexNet</h3><p>名為 AlexNet 的卷積神經網路，其來自於一篇 2012 的論文， <strong>ImageNet Classification with Deep Convolutional Neural Networks</strong> ，多倫多大學的 Alex Krizhevsky 、 Ilya Sutskever 以及Geoffrey E. Hinton 教授，這項研究是訓練了一個大型深度卷積神經網絡，用於將 ImageNet LSVRC-2010 競賽中，top-1 和 top-5 錯誤率分別為 37.5% 和 17.0%，以及 ILSVRC-2012 引入變體模型，取得了 15.3% 的 Top-5 測試錯誤率 ( 即 84.7% Top-5 準確率 )，在當年表現遠遠超越了第二名的模型，取得了卓越的表現，這項里程碑式的進步體現了電腦卓越的視覺能力。</p><h4>ImageNet</h4><p>電腦視覺研究陷入瓶頸，研究者耗盡心力設計特徵與演算法，2007年時普林斯頓大學的李飛飛 ( Fei-Fei Li ) 教授，思考根本的挑戰究竟在於模型本身，還是在於輸入的資料，對這種範式轉變提出了質疑，她認為應該讓電腦透過分析不同圖像及其相互關聯進行學習的潛力之間的相似性，向機器注入大量多樣化視覺資料集來訓練機器的概念，從根本上改變電腦視覺和人工智慧的格局。這需要在照片標記上投入大量精力，透過 Amazon Mechanical Turk，跨 167 個國家的 4.9 萬名標註者參與，對超過 1.6 億張候選圖像進行了篩選和標註，到了2009年，團隊發表一篇關於這個包含320萬張圖像的綜合資料庫的論文，該資料庫後來擴展到1400萬張各標註三次的高質量圖像，2 萬多類別的龐大資料庫，李飛飛於 2009 年與PASCAL 視覺物件分類競賽展開合作，這促成了隨後 於 2010 年啟動的ImageNet ILSVRC 大規模視覺辨識挑戰賽，ILSVRC 比賽用的來源於ImageNet 的子集，選擇了 1000 個類別，每類約 1000~1300 張圖像，此挑戰賽包含 1000 個類別和物件定位任務。</p><h4>模型架構</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*F4WVczXSYnnzV9mL.png" /></figure><p>AlexNet 的結構大致可以分成三個部分，第一是特徵提取，使用卷積與池化，一共 5 個卷積層，部分後接的 max-pooling ，max-pooling 於窗口內選擇最大值，其餘都捨棄，前兩層加入局部響應正規化 ( LRN ) ，模擬生物神經抑制效果、提升泛化。第二是全連接層，3 個全連接層，中間兩層各有 4096 個神經元，最後一層是 1000 維 softmax。第三加強訓練網路的關鍵設計，在激活函數的設計上，改為使用ReLU 非線性函數，比 sigmoid/tanh 收斂快，減緩梯度消失，用兩張 NVIDIA GTX 580 訓練，模型被切分到兩顆 GPU 上並行，第二、第四和第五個卷積層的核心僅連接到前一層中位於同一 GPU 上的核映射，第三卷積層的核連接到第二層的所有核映射，加入Dropout 在全連接層中隨機屏蔽部分神經元，防止過擬合，進行資料增強，隨機裁切、水平翻轉，提升模型泛化能力。</p><p>Max-pooling : 統一設定 kernel size = 3×3 ，stride=2，採用重疊池化，能降低錯誤率並減少過擬合。 第一卷積層 : 使用 96 個大小為 11 x 11 的卷積核對 224 x 224 x 3 的輸入影像進行卷積濾波，步長為 4 像素， ReLU 激活函數，做 Max-pooling ，並進行 Response-normalization。 第二卷積層 : 使用 256 個大小為 5×5 的卷積核對 55×55×96 的輸入進行卷積濾波，步長為 1 ，padding 為 2， ReLU 激活函數，做 Max-pooling ，並進行 Response-normalization。 第三卷積層 : 使用 384 個大小為 3×3 的卷積核對 27×27×256 的輸入進行卷積濾波，步長為 1 ，padding 為 1， ReLU 激活函數 。 第四卷積層 : 使用 384 個大小為 3×3 的卷積核對 13×13×384 的輸入進行卷積濾波，步長為 1 ，padding 為 1， ReLU 激活函數 。 第五卷積層 : 使用 256 個大小為 3×3 的卷積核對 13×13×384 的輸入進行卷積濾波，步長為 1 ，padding 為 1， ReLU 激活函數，做 Max-pooling 。 全連接層 : 3 個全連接層，中間兩層各有 4096 個神經元，使用 ReLU 激活函數，並加入Dropout，機率為 0.5，最後一層是 1000 維 softmax。</p><h4>Rectified Linear Unit</h4><p>接著，談論一個非常重要的部分，在激活函數的設計，過去的標準方法是使用 Sigmoid 或 Tanh 函數，類似於一個 S 型的激活函數 ，但就梯度下降的訓練時間而言，這些飽和非線性函數比非飽和非線性函數慢很多，當 Sigmoid 和 tanh 在輸入很大或很小時，梯度會趨近於 0，導致深層網路難以學習。 ReLU 激活方式為 f ( x ) = max ( 0 , x ) ，在 x 輸入小於 0 時，輸出為 0，這讓許多神經元在特定輸入下不會被激活，同時ReLU 計算簡單，效率高，在他們的實驗中， 在相同架構下使用 ReLU 的收斂速度比使用 tanh 快了將近 6 倍，可以大幅縮短訓練時間。</p><h4>多 GPUs 訓練</h4><p>當時的 GTX 580 GPU 只有 3GB 記憶體，無法容納完整的大型網路，因此，他們將網路分佈在兩個 GPU 上，GPU 特別適合跨 GPU 並行化，能直接讀取和寫入彼此的內存，而無需經過主機內存，同時，GPU 之間只在特定層進行通訊，減少資料交換的開銷，選擇性連接透過交叉驗證來決定最佳模式，以平衡通訊與計算成本，此方案分別將 top-1 和 top-5 錯誤率降低了 1.7% 和 1.2%，且雙 GPU 網路的訓練時間略少於單 GPU 網路。</p><h4>Local Response Normalization</h4><p>ReLU 本身不會飽和，因此不需要輸入正規化來防止梯度消失，但作者發現加入 局部正規化 (local normalization) 可以幫助提升模型的泛化能力。其模仿生物神經元的側抑制 (lateral inhibition) 讓神經元之間產生競爭，如果某個神經元輸出很大，它會壓制鄰近神經元的活性，使得特徵提取更具選擇性，在同一位置 x,y，對鄰近卷積核的響應進行歸一化，如果參數 n 為 5 ， 在該層中，第 i 張特徵圖在位置的輸出會用自己和前後各 2 張（共 5 張）特徵圖輸出做正規化。不過現在的 CNN 已經不使用這種方式，幾乎被淘汰，只存在於 AlexNet 這類早期網路，改用 Batch Normalization 一次正規化處理一整層全部的特徵圖。</p><h4>資料增強</h4><p>研究中他們提出兩種方式來對抗過擬合問題，第一種資料增強進行了平移或水平翻轉，將大小 256×256 原圖，隨機裁剪出 224×224 的區塊，再加上其水平翻轉，這樣訓練資料集大小理論上增加了 2048 倍，第二種方式是顏色強度擾動，對整個訓練集的 RGB 像素做 PCA，近似地捕捉了自然影像重要特性，即物體身份不受光照強度和顏色變化的影響，此方案將 Top-1 錯誤率降低了 1% 以上。</p><h4>Dropout</h4><p>在訓練時，每個隱藏神經元以 50% 的機率被丟棄，被丟棄的神經元不參與 forward pass 也不參與 backpropagation，每次輸入資料時，網路就會隨機形成不同的子網路，但這些子網路共享權重，可以防止神經元之間形成互相依賴，迫使每個神經元學到更穩定通用的特徵。在早期的較大的模型中 Dropout 相當重要，但現今變得很少使用或幾乎沒有，由於 Batch Normalization 可以穩定訓練、降低過擬合，且現代網路結構自然減少過擬合需求，而使用 Dropout 訓練時間會稍微增加，對大型網路來說成本不低。</p><h4>Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*sGSOuAz5ACDF4zwc.png" /></figure><p>AlexNet 的成功不僅在於它突破了當時圖像分類的準確率記錄，也證明了深度卷積神經網路（CNN）在大規模圖像辨識中的強大能力，透過多層卷積、ReLU 激活、Dropout、資料增強等技巧，它能從上百萬張圖像中自動學到有用的特徵，甚至能分辨細微差異 。</p><h3>結語</h3><p>感知機的創始者 Frank Rosenblatt 想要的是向機器展示物體，並讓它識別這些物體，60年後，我們終於做到了，他走在正確的道路上，只是需要重複一百萬次，當時，還不知道如何訓練多層網路，但事後看來，他的演算法仍然是我們今天訓練深度網路的基礎，而現今世代的深度學習，更是仰賴Geoffrey Hinton、Yann LeCun 等等諸多先驅研究者的努力，從 Neocognitron 以及第一個 CNN LeNet，到 2012 年 AlexNet 的出現，這過程非常多的技術變革，AI 算法與模型的進展，而 AlexNet 可以說是一個深度學習與電腦視覺的起點，從那之後便開始出現非常大量的 深度學習與 CNN 的研究，研究者不斷提出更深、更複雜的網路結構，例如 VGG、GoogLeNet、ResNet 等，同時也發展出多種卷積技巧與訓練方法，使得 CNN 不僅在影像分類，還在物體檢測、語義分割、生成模型等領域取得驚人成就，後續會再更深入解析繼 AlexNet 後出現的更優秀的 CNN 模型的細節與原理，介紹深度學習與人工智能方面那些重大的研究，深入學習現今的電腦視覺人工智慧，以及在各行各業廣泛的應用的系統介紹。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2c742f9b7c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[生成對抗網絡 GAN 介紹與實作]]></title>
            <link>https://medium.com/@john20050826/%E7%94%9F%E6%88%90%E5%B0%8D%E6%8A%97%E7%B6%B2%E7%B5%A1-gan-%E7%AD%86%E8%A8%98%E8%88%87%E5%AF%A6%E4%BD%9C-467684c2760d?source=rss-a590a0c11a1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/467684c2760d</guid>
            <dc:creator><![CDATA[Jiaen]]></dc:creator>
            <pubDate>Wed, 05 Feb 2025 22:44:37 GMT</pubDate>
            <atom:updated>2025-02-07T15:01:22.630Z</atom:updated>
            <content:encoded><![CDATA[<h3>前言</h3><p>Generative AI ，旨在模擬和生成新的數據，如圖像、音頻或文本，電腦如何通過模型理解和生成模仿真實世界的複雜數據，例如圖像或自然語言？ 在機器學習中分成 辨別式AI與生成式AI兩種 ，而最早期的生成式AI採用 Naive Bayes 或 Hidden Markov Model 這類機器學習算法，至近幾年深度學習的發展，生成對抗網絡（Generative Adversarial Networks, GAN）於 2014 年被提出，在生成式 AI 領域造就一大突破的深度學習模型 GAN 被廣泛使用，筆者我學習深度學習的過程蒐集一些資料並彙整成了這篇文章。</p><p>對於 GAN 這樣的生成模型，ACM Turing Award 得主 <strong>Yann LeCun</strong> 曾表示 :</p><blockquote>The most important one, in my opinion, is adversarial training (also called GAN for Generative Adversarial Networks). This is an idea that was originally proposed by Ian Goodfellow when he was a student with Yoshua Bengio at the University of Montreal (he since moved to Google Brain and recently to OpenAI). This, and the variations that are now being proposed is the most interesting idea in the last 10 years in ML, in my opinion.</blockquote><h3>GAN 介紹</h3><p>在 2014 年，Ian Goodfellow 等人提出了 <strong>Generative Adversarial Networks (GAN) </strong>，這篇論文提出了一種新的框架來訓練生成模型，<strong>此架構會同時訓練兩個模型，透過對抗學習（adversarial process） 的方式</strong>， 由<strong>生成器（Generator, G） 和辨別器（Discriminator, D） </strong>兩個網絡組成，在過程中相互競爭，並相互進步。生成對抗網絡 GAN 背後的核心思想便是涉及到博弈論的思維，生成器會去生成假的資料，使假的資料不被辨識出來，辨別器會被訓練能夠鑑別真實或假的圖像資料，兩者會同時訓練並持續優化，使生成模型生成更仿真的圖像。GAN的訓練目標可以寫成一個<strong>極小極大問題</strong>，這正是博弈論中常見的數學模型。該模型旨在找到一個平衡點，使得生成器與判別器都無法通過單方面調整來獲得更優的結果，這與博弈論中的Nash均衡概念相符，從理論上保證了訓練過程可以達到一種平衡狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cWZSJ_TOSfcQhurTurZjQ.jpeg" /></figure><p>在GAN的這篇論文中，作者闡述了通過深度學習能夠發現或學習出一種豐富且具有層次結構的模型 ，能夠捕捉和表達資料中各種複雜的機率分布 ，使用深度類神經網路則是其中一個手段，因此通過 MLP 模型嘗試去發掘並擬合希望去生成的物件資料其潛在分佈。模型要學習到數據的統計特性，進而能夠產生符合該分佈的新樣本。假設我們訓練一個貓圖片的生成模型，如果模型只是記住訓練數據，它只能輸出已經見過的圖片，這並不是生成而是記憶，若模型學習到貓圖片的 <strong>統計特徵（distribution）</strong>，它便能生成新的但仍然像貓的圖片 。因此通過這樣一個 GAN 的架構底下建構了兩個 MLP 模型，負責生成與鑑別的工作，而通過 GAN 這樣的架構不需要傳統生成模型中的最大似然估計或顯式的概率分佈建模，以對抗式學習使其隱式學習數據分佈，解決那些複雜的機率計算問題。</p><p>以往所做生成的方式便是總是想要去將物件、圖像的明確參數化的機率分布函數構造出來，通過最大化它的 Log Likelihood ，必須依賴複雜近似與馬可夫鏈蒙地卡羅估算梯度，在訓練時變得十分困難和低效。在 GAN 被提出之前，就有一些相關工作像是 Generative Machines，這些模型不需要明確計算對數似然，而是著重於如何生成與目標分布相似的樣本，Generative Stochastic Networks 是其中一個例子，該方法可以利用 backpropagation 來訓練，再透過馬可夫鏈學習轉移去生成新資料，過程避免了傳統玻爾茲曼機那種依賴近似的困難，但GSN跟GAN相比它模型內部必須使用的馬可夫鏈採樣，而GAN消除了這樣的問題。</p><p>當時，GAN出來前是有一些非常相似的生成圖像模型的，其中一個項目就是Variational Autoencoder , VAE 由 Max Welling 在 2013 時基於Autoencoder這個經典的人工身經網路模型所做出，Autoencoder 架構包含 Encoder和Decoder ，VAE 希望將原始圖像壓縮至低維度空間為一個特徵分佈 ，在這個空間分布中挑取一個點用Decoder 就會生成新的圖像，與GAN做法不同，VAE擬合學習的特徵可以進一步調整，也可以和文字、語音做結合。另外，通過這樣辨別模型去訓練生成模型的方法，在先前就有Noise-Contrastive Estimation ， NCE 將生成模型與一個固定的噪音分布進行對比，藉由學習一組權重使模型能夠辨別真實數據與噪音樣本，但NCE 的缺點在於損失函數相對GAN來說比複雜一點，GAN性能就更好一些。</p><h3>GAN 模型</h3><p><strong>生成器</strong></p><p>在生成器部分 ， MLP 透過輸入一個<strong>隨機變數 z</strong> 來生成數據 G(z) ，此隨機變數會是一個均值為0，變異數為1的高斯分布噪音，這樣一個分布透過 MLP 函式映射在要生成的圖像資料分布上，所以透過訓練就可以找出這樣一個函式能形成<strong>噪音到生成資料的映射</strong>。</p><pre>class Generator(nn.Module):<br>    def __init__(self, z_dim , img_dim):<br>        super().__init__()<br>        self.gen = nn.Sequential(<br>            nn.Linear(z_dim,256),<br>            nn.LeakyReLU(0.1),<br>            nn.Linear(256 , img_dim),<br>            nn.Tanh(),<br>        )<br><br>    def forward(self , x):<br>        return self.gen(x)</pre><p>z_dim 代表隨機的一組向量的矩陣大小，img_dim 為輸出之圖片大小，使用 LeakyReLU 作為非線性激活函數，最後使用 Tanh激活函數，將輸出值壓縮到 [−1,1] 的範圍內</p><pre>gen   = Generator(z_dim , image_dim)<br>noise = torch.randn(batch_size , z_dim)<br>fake  = gen(noise)</pre><p>使用深度類神經網路能夠去擬和任何的函數，生成器上只需要通過輸入足夠大的一個分布 z ，MLP的擬和並非真正理解所要生成的過程所需要的結構或邏輯，而是輸入大量的數據資料來擬和 Mapping 的一個函式，只能看機率運氣的分佈去生成一個還算相似的圖片，這也是 GAN 比較不方便的一個問題。</p><p><strong>辨別器</strong></p><p>而在辨別器的部分，其為一個MLP 兩類別分類器，只需要將欲希望生成的圖片作為 MLP 輸入資料，其圖片代表真實圖片( 以 1 標註 )，而由上方所述的生成器，通過噪音產出的圖片就會被視為假的圖片資料 ( 以 0 標註 ) ， D(x) 表示了這份 x 是來自於真實資料還是生成出來的資料。</p><pre>class Discriminator(nn.Module):<br>    def __init__(self , in_features):<br>        super().__init__()<br>        self.disc = nn.Sequential(<br>            nn.Linear(in_features , 128),<br>            nn.LeakyReLU(0.1),<br>            nn.Linear(128 , 1),<br>            nn.Sigmoid(),<br>        )<br><br><br>    def forward(self,x):<br>        return self.disc(x)</pre><p><strong>對抗式網路</strong></p><p>所以訓練過程中，會同時訓練這兩個MLP模型，而此架構的Generator最小化log(1 − D(G(z))) ，代表著Generator優化目標要使Discriminator盡可能的出錯，形成一個目標函數，稱作 <strong>two-player minimax game</strong> ，並以這樣的價值函數表示 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWif5dxYwtL2UbOikP_1bw.png" /></figure><p>這個價值函數表示說，若是判別器可以完美的分類情況下，其會符合 D (x) 等於 1 ，D ( G(z) ) 為 0，這樣 log 過後皆會為 0 ，也就是價值函數的最大值 ， 判別器也希望去最大化價值函數的輸出，但在生成器訓練過程就不會使其可以完美分辨，D (x) 不等於 1 且 D (G(z))輸出不為0 的情況時，價值函數就為一個負數的輸出 ，生成器就會去盡可能最小化價值函數。另外，在這裡使用 log 另一用途是能夠在損失計算時，提供足夠的學習信號，有助於避免梯度消失問題。</p><h3>GAN 訓練演算法</h3><p>整個訓練流程會進行多次迭代 :</p><p><strong>訓練判別器：</strong></p><p>在每次迭代中，先重複 k 次下面的步驟：</p><ul><li>從噪音分布 pg(z) 中抽取一個 mini-batch 的噪音樣本。</li><li>從真實資料分布 pdata(x) 中抽取一個 mini-batch 的真實資料 。</li></ul><p>使用這兩組樣本，計算以下梯度，並根據梯度上升更新判別器的參數：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*ypay5sc5XnkNmT-W3UtHXQ.png" /></figure><p><strong>訓練生成器：</strong></p><p>在更新完判別器後，抽取一個新的 mini-batch 噪音樣本，使用這組噪音樣本然後根據梯度計算後<strong>更新生成器的參數</strong></p><p>生成器更新的梯度計算公式如下 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*-otmKUBU4lc9UGLf2b3MiA.png" /></figure><h3>GAN 訓練實作 ( PyTorch )</h3><p>講完了理論部分後，這邊以 PyTorch 並使用MNIST ( Modified National Institute of Standards and Technology )手寫數字資料集訓練 GAN 去 生成數字為例，資料集共包含60,000張訓練圖像和10,000張測試圖像，尺寸為28×28像素，在這裡只需要訓練資料集的圖片資料部分。</p><p><strong>匯入所需要的函式庫</strong></p><pre>import torch <br>import torch.nn as nn<br>import torch.optim as optim<br>import torchvision<br>import torchvision.datasets as datasets<br>from torch.utils.data import DataLoader <br>import torchvision.transforms as transforms<br>from torch.utils.tensorboard import SummaryWriter<br>import os</pre><p>torch 協助我們建構深度類神經網路模型並打包資料集進行訓練，這邊匯入torchvision內的一些功能可以更好的對圖像調整與tensorboard展示生成圖像，同時也可藉由torchvision匯入一些我們想要的資料集，MNIST的手寫數字資料就包含在其中。</p><p><strong>建構生成器與判別器</strong></p><pre>class Discriminator(nn.Module):<br>    def __init__(self , in_features):<br>        super().__init__()<br>        self.disc = nn.Sequential(<br>            nn.Linear(in_features , 128),<br>            nn.LeakyReLU(0.1),<br>            nn.Linear(128 , 1),<br>            nn.Sigmoid(),<br>        )<br>    def forward(self,x):<br>        return self.disc(x)<br>        <br>class Generator(nn.Module):<br>    def __init__(self, z_dim , img_dim):<br>        super().__init__()<br>        self.gen = nn.Sequential(<br>            nn.Linear(z_dim,256),<br>            nn.LeakyReLU(0.1),<br>            nn.Linear(256 , img_dim),<br>            nn.Tanh(),<br>        )<br>    def forward(self , x):<br>        return self.gen(x)</pre><p><strong>初始化參數數值</strong></p><pre>device = &quot;cuda&quot;<br>z_dim = 64<br>image_dim = 28 * 28 * 1<br>batch_size = 64<br>num_epochs = 100<br><br>disc = Discriminator(image_dim).to(device)<br>gen  = Generator(z_dim , image_dim).to(device)<br>fixed_noise = torch.randn(batch_size, z_dim).to(device)<br>transform  =   transforms.Compose(<br>  [transforms.ToTensor() , transforms.Normalize((0.5,) , (0.5))]<br>)<br><br>dataset = datasets.MNIST(root=&quot;data/&quot;,transform= transform,download=True)<br>loader = DataLoader(dataset , batch_size=batch_size , shuffle=True)<br><br>opt_disc = optim.Adam(disc.parameters() , lr=1e-4 , betas=(0.5, 0.999))<br>opt_gen  = optim.Adam(gen.parameters()  , lr=3e-4 , betas=(0.5, 0.999))<br><br>criterion = nn.BCELoss()<br>writer_fake = SummaryWriter(f&quot;runs/GAN_MNIST/fake/&quot;)<br>writer_real = SummaryWriter(f&quot;runs/GAN_MNIST/real/&quot;)<br>step = 0</pre><p>MNIST手寫數字的圖像規格是28 x 28 像素，因此設定生成器網路的輸出會是一維28x28大小的Tensor，對兩個MLP分別設置其參數優化器，這裡使用Adam優化器以及配置Learning Rate ，判別器的分類問題使用 Binary Cross-Entropy Loss 計算損失，torchvision的dataset匯入MNIST手寫數字資料的圖像，並使用transforms轉成Tensor，並做 Normalize 加速訓練收斂，穩定模型更新，以及將其打包成dataloader ，接著就可以開始訓練了。</p><p><strong>訓練 GAN</strong></p><pre>for epoch in range(num_epochs):<br>    for batch_idx , (real , _ ) in enumerate(loader):<br>        real = real.view(-1 , 784).to(device)<br>        batch_size = real.shape[0]<br><br><br>        noise = torch.randn(batch_size , z_dim).to(device)<br>        fake  = gen(noise)<br><br>       # Train Discriminator<br>        # real <br>        disc_real = disc(real).view(-1)<br>        lossD_real = criterion(disc_real , torch.ones_like(disc_real))<br><br><br>        # fake <br>        disc_fake = disc(fake).view(-1)<br>        lossD_fake = criterion(disc_fake , torch.zeros_like(disc_fake))<br><br>        # Avg loss of real and fake <br>        lossD = (lossD_real + lossD_fake ) / 2<br><br><br>        disc.zero_grad()<br>        lossD.backward()<br>        opt_disc.step()<br><br><br>       # Train Generator<br>        noise = torch.randn(batch_size, z_dim).to(device)  <br>        fake = gen(noise)<br>        output = disc(fake).view(-1)<br>        lossG = criterion(output , torch.ones_like(output))<br><br>        gen.zero_grad()<br>        lossG.backward()<br>        opt_gen.step()<br><br>    # 在 tensorboard 上展示 生成結果<br>        if batch_idx == 0:<br>            print(<br>                f&quot;Epoch [{epoch}/{num_epochs}] Batch {batch_idx}/{len(loader)} \<br>                      Loss D: {lossD:.4f}, loss G: {lossG:.4f}&quot;<br>            )<br>            with torch.no_grad():<br>                fake = gen(fixed_noise).reshape(-1, 1, 28, 28)<br>                data = real.reshape(-1, 1, 28, 28)<br>                img_grid_fake = torchvision.utils.make_grid(fake, normalize=True)<br>                img_grid_real = torchvision.utils.make_grid(data, normalize=True)<br><br>                writer_fake.add_image(<br>                    &quot;Mnist Fake Images&quot;, img_grid_fake, global_step=step<br>                )<br>                writer_real.add_image(<br>                    &quot;Mnist Real Images&quot;, img_grid_real, global_step=step<br>                )<br>                step += 1</pre><p>real 變數為來自於MNIST真實的圖片，將其處理轉換成一維的資料 28 x 28 大小作為輸入，再從標準正態分布中採樣一組噪音，透過生成器產生假圖像。使用的二元交叉熵 BCE損失函數計算預測結果與標籤的差異，lossD = (lossD_real + lossD_fake) / 2，判別器的損失分為兩部分，真實資料應該接近 1，另一部分為生成資料接近 0，將這兩部分損失取平均，使得梯度更新的量級平衡，不會因為某一部分損失過大而主導整體梯度。再來，計算生成器的損失，生成器希望判別器把假圖像誤判為真，所以標籤設定為 1。這部分損失鼓勵生成器改進，使得生成圖片更具真實性。</p><p><strong>訓練過程</strong></p><p>GAN的訓練過程一開始的生成器的初期會產生出非常混亂的圖像，剛開始並不能夠直接抓到特徵跟分布，隨著訓練的進行，生成器會通過反覆的迭代過程，逐漸優化其生成的圖像，使其更加符合真實圖像的特徵。這意味著生成的圖像開始展現出一些基本的規律性，例如簡單的邊緣、顏色分佈等，但仍然可能有顯著的缺陷。從手寫數字生成的範例中可以看見迭代訓練後的變化，到中間開始已經有些圖像可以明顯具有數字的特徵，但仍很混亂，到後面訓練迭代了400~500個epoch後可以出現一寫看起來比較正常的數字模樣圖片，可能有些模糊或缺口，代表模型可以正確的生成了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DV2tyEk3iekSKvZxI_9Pw.jpeg" /><figcaption>GAN 訓練生成手寫數字</figcaption></figure><p>在訓練的過程中，可能出現一些的訓練問題，論文中就表示，在初期訓練時，由於生成器生成的圖像混亂跟真實的圖片資料差得很多，很容易得會把判別器訓練得很好，但生成器仍然很差，所以在計算log(1 − D(G(z)))時很容易處在 0 的情況，計算梯度時就會更新不動，將目標換成最大化 log(D(G(z))) 能稍微改善，或是調整參數策略或改良生成器模型來使生成器有更好的收斂。另一個問題是，由於GAN的架構下有兩個模型，一個往上走另一個往下走， 判斷GAN 的收斂是比較困難的，整體來說 GAN 的收斂是非常不穩定的，訓練過程中出現震盪、發散或停滯現象，GAN訓練也缺乏明確的評估指標，需要人工觀察生成結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CatDa5AqF5FCsqaytUxBDQ.jpeg" /><figcaption>GAN 生成圖像的結果，來源 : <a href="https://arxiv.org/abs/1406.2661">https://arxiv.org/abs/1406.2661</a></figcaption></figure><h3>GAN後續延伸</h3><p>GAN在2014時被提出，Ian Goodfellow 他的工作開創了一個新的領域，能夠便捷的利用深度學習進行數據圖像的生成，但GAN當時的效能、功能性都不太夠，也在訓練時很難收斂，所以後續有很多很多的工作來解決這樣的問題 ，舉例來說 :</p><p>1 . 在最初的GAN僅是能抓住圖像的分佈與特徵來生成，在MNIST手寫數字的案例中可以看到，輸入的數字包含了0~9數字，但機器並未能真正理解這些是不同的數字或不同圖像物件的類別，所以當初論文提到將條件 輸入到生成器與判別器中，之後 Mirza 與 Osindero 就在 2014 年提出了 Conditional GAN ，讓機器的生成器是能夠限定生成的圖片中所出現的類別或物件。</p><p>2. DCGAN (Deep Convolutional GAN) 是一個GAN的延伸模型 ， 目標函數基本上與原始的GAN完全相同，利用深度卷積神經網路CNN來架構生成器與判別器，完全捨棄傳統全連接層，更能提取圖片的特徵等細節，改善 GAN 訓練時不穩定的問題，生成能力會比使用MLP的GAN更好。</p><p>3. WGAN (Wasserstein GAN) 使用 Wasserstein 距離衡量生成器與真實分佈之間距離， 與原始的GAN鑑別器相比，Wasserstein GAN鑑別器為生成器提供了更好的學習訊號，當生成器在非常高維度空間中學習分佈時，這使得訓練更加穩定 。</p><p>除此之外，還有很多 GAN 的延伸工作，足以使的現在 GAN 這樣的深度學習模型應用在許多的地方，像是 CycleGAN 則針對影像轉換任務，包含像是畫風轉化、夏天轉冬天等用途，ProGAN 採用逐步增大解析度的方式生成高解析度圖片，SRGAN 針對單張低解析度圖片進行超解析度重建，生成高解析度圖像，又或是 pix2pix 模型生成無人車駕駛的街景 。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*T2UdIZ4e-z4DLX9Q0y2dhw.png" /><figcaption>Cycle GAN 圖像轉換，Horse to Zebra</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fi_AkVYGl7T5p1wQPXgxg.jpeg" /><figcaption>NVIDIA research : GauGAN 將塗鴉變成逼真風景</figcaption></figure><h3>結語</h3><p>Generative Adversarial Network 僅透過輸入真實的圖像使深度學習模型去模仿生成，也是一種Unsupervised Learning 的方式 ，不需要人工大量的標註資料，用 GAN 可以便利地用於圖像的生成，也可以產生高品質的訓練資料來輔助其他模型更好的訓練，GAN的相關論文在2014後也開始大幅度的增加，相關的GAN的延伸模型與技術應用，我也打算在後續更深的探討與嘗試研究看看。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467684c2760d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>