<?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 Ege Kasal on Medium]]></title>
        <description><![CDATA[Stories by Ege Kasal on Medium]]></description>
        <link>https://medium.com/@egekasal?source=rss-56d5bc413da6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3ijWS_bNWJHgyUd_qYxhcg.jpeg</url>
            <title>Stories by Ege Kasal on Medium</title>
            <link>https://medium.com/@egekasal?source=rss-56d5bc413da6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 16:45:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@egekasal/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[The Pinnacle of Face Recognition: The Collapse of Softmax, Triplet Loss, and ArcFace’s Angular…]]></title>
            <link>https://medium.com/@egekasal/the-pinnacle-of-face-recognition-the-collapse-of-softmax-triplet-loss-and-arcfaces-angular-f2422e6ba39f?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2422e6ba39f</guid>
            <category><![CDATA[face-detection-app]]></category>
            <category><![CDATA[arcface]]></category>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 20:49:38 GMT</pubDate>
            <atom:updated>2026-06-25T20:49:38.499Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Pinnacle of Face Recognition: The Collapse of Softmax, Triplet Loss, and ArcFace’s Angular Revolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-1l1nrrOX7ZVwNzsQGKNA.png" /></figure><p>In deep learning-based face recognition, mapping an image into a discriminative vector space is the ultimate objective. However, arriving at a perfectly optimized 512-dimensional embedding space required overcoming severe geometric pitfalls, computational bottlenecks, and architectural limitations.</p><h4>The Curse of Dimensionality in Euclidean Space</h4><p>Using raw Euclidean distance to compare facial feature vectors introduces a critical disadvantage known as the Curse of Dimensionality. The fundamental flaw is that Euclidean distance evaluates the straight-line distance between vector endpoints in space.</p><p>In face recognition models, image quality directly dictates vector magnitude (||x||). High-quality, front-facing, well-lit photos yield massive vector lengths, whereas blurry or dark photos produce short vector lengths.</p><p>Consider three vectors:</p><ul><li><strong>Vector A:</strong> High-quality photo of Person 1 (Length: 25)</li><li><strong>Vector B:</strong> Blurry photo of Person 1 (Length: 5)</li><li><strong>Vector C:</strong> High-quality photo of Person 2 (Length: 22)</li></ul><p>Because Vectors A and C are both long, their endpoints lie in a similar outer region of the vector space, making the Euclidean distance between them short. Consequently, the model misidentifies two completely different individuals as the same person. Conversely, the Euclidean distance between Person 1’s high-quality photo (A) and their own blurry photo (B) becomes massive, leading to a false rejection.</p><h4>Projecting onto the Hypersphere via L2 Normalization</h4><p>To eliminate the distorting effect of image quality and vector magnitude, models apply L2 Normalization. This operation divides a vector by its own L2 Norm, transforming it into a unit vector.</p><p>A fundamental rule of linear algebra ensures that multiplying or dividing a vector by a positive scalar alters only its length along that specific trajectory; its spatial angle and direction remain completely unchanged. Geometrically, mapping all vectors to a uniform distance of exactly 1 from the origin projects the data onto a 512-dimensional Hypersphere. Once restricted to this unit sphere, the length discrepancy is eliminated, leaving only the directional orientation (angle) to differentiate identities.</p><h4>From Softmax to Metric Learning</h4><p>Traditional classification networks rely on the Softmax function. Softmax aims to predict an explicit identity label by updating weights to draw decision boundaries (walls) between distinct classes.</p><p>Metric Learning abandons discrete class labeling entirely. Instead of optimizing for a class probability, the model is engineered to output a geometric distance. The sole objective of Metric Learning is to warp the embedding space so that vectors belonging to the same person attract each other like magnets, while vectors of different individuals fiercely repel. Early Siamese architectures implemented this by passing image pairs through twin networks to minimize or maximize Euclidean distance, but pair-wise optimization ultimately proved inefficient.</p><h4>FaceNet, Triplet Loss, and the Combinatorial Explosion</h4><p>In 2015, Google introduced FaceNet, advancing metric learning by introducing Triplet Loss. Instead of pairs, the network is trained using triplets of images simultaneously: an Anchor (A), a Positive (P) from the same identity, and a Negative (N) from a different identity.</p><p>The optimization objective enforces that the distance between the Anchor and the Positive (d(A,P)) must be smaller than the distance between the Anchor and the Negative (d(A,N)) by a specified margin ($\alpha$):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*B4SECZU-9W43iwG_vi_EVQ.png" /></figure><p>If the model successfully pushes the Negative further than the Positive plus the margin, the loss becomes zero. If the Negative is too close, a loss is generated, forcing backpropagation to pull $P$ closer and push $N$ away.</p><p>Despite its mathematical brilliance, Triplet Loss suffers from a catastrophic flaw: <strong>Combinatorial Explosion</strong>. In a dataset containing millions of images, selecting random triplets yields easy negatives, resulting in a continuous loss of zero, meaning the model stops learning. To force optimization, developers must implement “Hard Triplet Mining” — an intensive search algorithm to continuously locate highly similar looking different people. As the dataset scales, this mining process becomes computationally unsustainable, paralyzing infrastructure.</p><h4>ArcFace and the Additive Angular Margin Devolution</h4><p>ArcFace elegantly resolved the combinatorial mining crisis. It utilizes the highly efficient architectural framework of Softmax, yet applies the mathematical force of Metric Learning directly through class weights (W), eliminating the need for complex triplet matching.</p><p>On a unit sphere (r=1), the straight-line Euclidean distance between endpoints is replaced by <strong>Geodesic Distance</strong> — the shortest path carved directly along the surface of the sphere. Through trigonometric simplification, this surface arc length is exactly equal to the angle (theta) between the vectors in radians.</p><p>While traditional Softmax attempts to maximize Cosine Similarity cos(theta), it fails to directly tighten the geodesic path. ArcFace replaces the standard target logit with an <strong>Additive Angular Margin</strong> (m), transforming the loss function component into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*l9epwjpefY_DXNGJ_I6T4g.png" /></figure><p>The margin m represents an explicit extra arc length penalty on the hypersphere surface. For the model to successfully classify an embedding to its correct class center, it cannot merely bring the vector close; it must force the vector to cross the margin boundary, shortening the Geodesic Distance by an extra $m$ radians.</p><p>This aggressive angular constraint forces embeddings of the same identity into an exceptionally tight localized cluster on the sphere surface (maximizing intra-class compactness). Because spatial real estate on a unit sphere is mathematically limited, compressing one identity’s cluster inherently drives all other identities much further away (maximizing inter-class separability). ArcFace achieves the rigorous clustering behavior of Triplet Loss natively within a classification layer, setting the gold standard for modern facial recognition engines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2422e6ba39f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a FastMCP Server to Google Cloud Run: How to Fix the “Invalid Host Header” and 421 Errors]]></title>
            <link>https://medium.com/@egekasal/deploying-a-fastmcp-server-to-google-cloud-run-how-to-fix-the-invalid-host-header-and-421-errors-bbfc8d121e26?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbfc8d121e26</guid>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 10:22:56 GMT</pubDate>
            <atom:updated>2026-06-21T10:22:56.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eW0lPDFlPQl5gG8B8IaW2Q.png" /></figure><p>I recently tried deploying a remote Model Context Protocol (MCP) server to Google Cloud Run so I could connect it to Cursor from anywhere. While setting up a local MCP server is easy, moving it to a serverless cloud environment brings a few unexpected production roadblocks.</p><p>There aren’t many specific guides out there for Google Cloud deployment, and I spent quite a bit of time digging through logs to fix timeout and security errors.</p><p>Here is a straightforward guide and the exact boilerplate you need to get your remote MCP server running on Cloud Run on the first try.</p><h4><strong>The Core Problem: Why Does It Fail on Cloud Run?</strong></h4><p>If you try to run a standard FastMCP app using the default app.run(transport=&quot;sse&quot;), it will fail in production for two main reasons:</p><ol><li><strong>Port Hardcoding:</strong> FastMCP.run() binds to 127.0.0.1:8000 by default. Google Cloud Run expects your container to listen on 0.0.0.0 and dynamically read the $PORT environment variable injected by Google. If it doesn&#39;t, the deployment will time out and crash (DEADLINE_EXCEEDED).</li><li><strong>DNS Rebinding Protection (The 421/500 Error):</strong> Anthropic’s Python SDK has strict built-in security. When Cursor tries to connect to your public Cloud Run URL (https://...run.app/sse), the MCP server detects a mismatch in the Host header, flags it as a potential security risk, and throws a 421 Misdirected Request or ValueError: Request validation failed.</li></ol><p>To fix this, we need to bypass FastMCP.run(), use <strong>Uvicorn</strong> to handle the cloud routing, and explicitly adjust the SDK&#39;s transport security settings.</p><h4>1. The Production Code (app.py)</h4><p>Here is the clean, working structure. The trick is initializing FastMCP with host=&quot;0.0.0.0&quot; and passing a modified TransportSecuritySettings object to disable DNS rebinding protection for the public cloud domain.</p><pre>import math<br>import os<br>from mcp.server.fastmcp import FastMCP<br>from mcp.server.transport_security import TransportSecuritySettings<br><br># Initialize FastMCP with cloud-ready security settings.<br># This bypasses the strict Host header verification that triggers 421 errors.<br>mcp_app = FastMCP(<br>    &quot;Calculating Machine&quot;,<br>    host=&quot;0.0.0.0&quot;,<br>    transport_security=TransportSecuritySettings(<br>        enable_dns_rebinding_protection=False,<br>        allowed_hosts=[&quot;*&quot;]<br>    )<br>)<br><br>@mcp_app.tool()<br>async def calculate_hypotenuse(a: float, b: float) -&gt; str:<br>    &quot;&quot;&quot;Calculates the hypotenuse of a right-angled triangle.<br>    args:<br>        a: length of the first side<br>        b: length of the second side<br>    &quot;&quot;&quot;<br>    c = math.sqrt(a**2 + b**2)<br>    return f&quot;The hypotenuse is {c}&quot;<br>    <br>@mcp_app.resource(&quot;info://constraints&quot;)<br>async def constraints() -&gt; str:<br>    &quot;&quot;&quot;Returns the static constraints of the system.&quot;&quot;&quot;<br>    return (<br>        &quot;PI number: 3.14159\n&quot;<br>        &quot;Speed of light: 299792458 m/s\n&quot;<br>    )<br><br># Expose the underlying ASGI app so Uvicorn can run it directly.<br>app = mcp_app.sse_app</pre><h4>2. The Docker Configuration (Dockerfile)</h4><p>Instead of using the mcp run CLI wrapper, we use standard uvicorn to run the .sse_app instance. This gives us full control over the network host and port.</p><pre>FROM python:3.11-slim<br>WORKDIR /app<br><br># Install standard production packages<br>RUN pip install --no-cache-dir mcp fastapi uvicorn<br><br>COPY app.py .<br><br># Dynamically read the $PORT assigned by Google Cloud Run at runtime<br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;uvicorn app:app --host 0.0.0.0 --port $PORT&quot;]</pre><h4>3. Deploying to Cloud Run</h4><p>Run the following gcloud command in your project directory. Make sure to allow unauthenticated traffic so Cursor can reach the endpoint.</p><pre>gcloud run deploy mcp-calculating-machine \<br>    --source . \<br>    --region us-central1 \<br>    --allow-unauthenticated<br></pre><p>Once the deployment finishes successfully, Google will hand you a public service URL. It will look something like this: https://mcp-calculating-machine-&lt;your-unique-hash&gt;-uc.a.run.app</p><h4>4. Connecting to Cursor</h4><p>Open your Cursor MCP settings (Settings -&gt; Features -&gt; MCP) or update your global mcp_config.json file.</p><p>Instead of using command or args, use the native remote <strong>url</strong> type and point it directly to your Cloud Run URL with the /sse suffix:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;CalculatingMachineCloud&quot;: {<br>      &quot;url&quot;: &quot;https://mcp-calculating-machine-&lt;your-unique-hash&gt;-uc.a.run.app/sse&quot;<br>    }<br>  }<br>}</pre><p>Hit save or refresh. The red warning icons should turn into a solid green indicator immediately. Your MCP server is now fully serverless, scales to zero when not in use, and can be accessed securely by your IDE from any machine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbfc8d121e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Correcting Tilted Faces with Math: SVD, Similarity Transform, and the Umeyama Algorithm]]></title>
            <link>https://medium.com/@egekasal/correcting-tilted-faces-with-math-svd-similarity-transform-and-the-umeyama-algorithm-d20d7bc40f5a?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d20d7bc40f5a</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[affine-transformation]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Mon, 01 Jun 2026 11:06:43 GMT</pubDate>
            <atom:updated>2026-06-01T11:06:43.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qSpJDpV0cntAU9nZobDpQ.png" /></figure><p>When capturing faces in real-world scenarios, they rarely arrive perfectly aligned to the camera plane. To pass them reliably into a facial recognition network, these faces must be normalized onto a flat, uniform 2D coordinate space. However, using a standard affine transformation introduces a dangerous geometric artifact: it can warp or stretch the facial features through shear, causing the face to deform and lose its anatomical reality.</p><h4>Preserving Anatomy: Affine vs. Similarity Transform</h4><p>To prevent facial distortion or aspect ratio corruption, we must eliminate shear entirely from our transformation matrix. We restrict our geometric operations exclusively to rotation, uniform scaling, and translation. This specific subset of operations is known as a <strong>Similarity Transform</strong>. It ensures that the face can rotate, scale up or down homogeneously, and translate along the axes while preserving its true structural proportions.</p><p>The SVD-based Umeyama algorithm mathematically models this alignment problem by establishing an optimal mapping between source facial landmark points ($S_i$) and destination reference coordinates ($D_i$):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*4i2MFORza3crXety7w0KGQ.png" /></figure><p>Where:</p><ul><li>$c$ is a scalar representing uniform scale.</li><li>$R$ is an orthogonal rotation matrix.</li><li>$t$ is a translation vector.</li></ul><h4>The Umeyama Algorithm: SVD for Optimal Rotation</h4><p>The mathematical elegance of Umeyama’s approach lies in its use of Singular Value Decomposition (SVD) rather than a naive ordinary least squares regression, which would allow for non-rigid warping. The execution follows a strict linear algebra pipeline:</p><p><strong>1- Centroid Normalization:</strong> The geometric centers (centroids) of both the source and destination landmark sets are computed. The point sets are shifted to center around their respective origins, temporarily removing the translation vector ($t$) from the core optimization equation.</p><p><strong>2- Cross-Covariance Matrix Calculation:</strong> A cross-covariance matrix ($H$) is constructed between the centered source and destination point clouds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*PN9ELexIIhz-6U8rR1BGOw.png" /></figure><p><strong>3- Singular Value Decomposition:</strong> The matrix $H$ is factored into its singular components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*GEinOX753J45ndQh_XHd6g.png" /></figure><p><strong>4- Optimal Rotation Extraction:</strong> Using orthogonal constraints, the most optimal rotation matrix ($R$) that minimizes the mean squared error without introducing any shear distortion is extracted via:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/1*vqLJUEyLJvcVKBPALetibw.png" /></figure><p>This methodology provides an exact, uncompromised mathematical foundation to align faces cleanly.</p><h4>Performance Analysis: Python vs. Compiled C</h4><p>In production face recognition pipelines, alignment operations must be executed with minimal latency. Benchmarking the core transform calculation and the subsequent pixel interpolation (warp_affine) reveals a distinct performance gap between native Python code and compiled C implementations.</p><p>An evaluation of compute_similarity_transform over 5,000 iterations yields the following execution metrics:</p><ul><li><strong>Python Execution:</strong> 0.25856 seconds</li><li><strong>C Execution:</strong> 0.03988 seconds</li><li><strong>Performance Gain:</strong> <strong>6.48x speedup</strong></li></ul><p>When measuring the warp_affine operation—which handles the actual pixel mapping over a $112 \times 112 \times 3$ image matrix—over 100 iterations, the results show:</p><ul><li><strong>Python Execution:</strong> 0.14044 seconds</li><li><strong>C Execution:</strong> 0.02416 seconds</li><li><strong>Performance Gain:</strong> <strong>5.81x speedup</strong></li></ul><pre>=== Face Alignment Benchmarks ===<br>compute_similarity_transform (5000 iter):<br>- Python: 0.25856 sec<br>- C:      0.03988 sec  --&gt; 6.48x Speedup<br><br>warp_affine (100 iter):<br>- Python: 0.14044 sec<br>- C:      0.02416 sec  --&gt; 5.81x Speedup</pre><h4>Overcoming the Marshalling Tax</h4><p>When calling a compiled C shared library from Python using ctypes, a fixed data conversion cost called <strong>marshalling</strong> is imposed to convert native Python types into C-compatible pointers.</p><p>For a lightweight operation like compute_similarity_transform, the core C execution logic finishes very quickly, meaning the fixed marshalling overhead accounts for a substantial percentage of the total elapsed time. However, for the warp_affine function, the heavy computational cost of iterating through thousands of individual color pixel channels entirely dominates the small, fixed marshalling cost. Consequently, moving pixel-intensive data transformations to compiled memory yields massive, uncompromised real-world performance gains.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d20d7bc40f5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Neural Networks Learn Object Dimensions: Anchor Box Geometry and K-Means]]></title>
            <link>https://medium.com/@egekasal/how-neural-networks-learn-object-dimensions-anchor-box-geometry-and-k-means-03aa0fa9b8c6?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/03aa0fa9b8c6</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Tue, 26 May 2026 10:59:53 GMT</pubDate>
            <atom:updated>2026-05-26T10:59:53.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-WanHhfFkQE7WDI-U777Q.png" /></figure><p>In object detection, a neural network rarely predicts bounding boxes entirely from scratch. Real-world objects exhibit drastic variations in form and scale — pedestrians are tall and narrow, vehicles are wide and horizontal, and camera distance introduces massive scaling differences. Forcing a network to guess arbitrary coordinate boundaries across infinite permutations introduces severe optimization instability. Instead, modern detection architectures formulate this problem as a geometric regression task relative to pre-defined reference structures known as Anchor Boxes.</p><h4>Bounding Box Regression and Scale-Invariant Decoding</h4><p>An anchor box acts as a mathematical prior for shape, scale, and aspect ratio. The task of the neural network is not to invent a box, but to calculate precisely how much to shift and stretch a specific reference anchor to perfectly encircle the target object.</p><p>Let the anchor coordinates be defined by its center point and dimensions $(x_a, y_a, w_a, h_a)$. The model outputs four parametric offsets: $dx, dy, dw,$ and $dh$. To construct the final, real-world predicted bounding box $(x, y, w, h)$, these offsets must be decoded using strict geometric principles.</p><p>The center coordinates are calculated relative to the anchor’s own dimensions to ensure scale-invariance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*S5ZgIqIa6tuOfbjB0e_w0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*m6tLg-RwAiK-Kw6R0tfmsQ.png" /></figure><p>For example, if the network predicts $dx = 0.5$, it geometrically dictates that the center of the bounding box must be shifted to the right by exactly half of the anchor’s total width.</p><h4>The Exponential Constraint for Scale Adjustments</h4><p>Regressing the width ($w$) and height ($h$) requires a different mathematical formulation. A simple linear scaling multiplier (such as $w = w_a \cdot dw$) cannot be safely utilized. Neural networks, by nature, produce unconstrained outputs spanning from $-\infty$ to $+\infty$. If the network predicts a negative offset value for $dw$ or $dh$, a direct multiplication would yield a negative or zero dimension for the bounding box, which is geometrically impossible.</p><p>To safely map the network’s unbounded real-number output $(-\infty, +\infty)$ into a strictly positive spatial dimension space $(0, +\infty)$, an exponential decoding function ($e^x$) is required:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*Jqpx0mbYYhlUpfJ9fcFjCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/1*XZTKg2FFNPBqdgtTfv4sbw.png" /></figure><p>This exponential logic enforces safe geometric transformations across all output values:</p><ul><li><strong>Zero Scaling ($dw = 0$):</strong> Since $e⁰ = 1$, the predicted width remains identical to the anchor width ($w = w_a \cdot 1$).</li><li><strong>Positive Scaling ($dw &gt; 0$, e.g., $0.69$):</strong> Since $e^{0.69} \approx 2$, the predicted dimension expands safely to twice the anchor’s size ($w \approx w_a \cdot 2$).</li><li><strong>Negative Scaling ($dw &lt; 0$, e.g., $-0.69$):</strong> Since $e^{-0.69} \approx 0.5$, the dimension shrinks gracefully without ever crossing into zero or negative space ($w \approx w_a \cdot 0.5$).</li></ul><h4>Anchors Optimization: K-Means with an IoU Distance Metric</h4><p>To maximize the efficiency of this regression mechanism, the initial anchor box dimensions cannot be assigned arbitrarily. They must be mathematically optimized to match the statistical distributions of the target dataset. This requires clustering thousands of ground-truth annotations.</p><p>When executing clustering for anchor generation, spatial positioning parameters $(x, y)$ are completely disregarded because the objective is strictly to discover recurring object <em>shapes</em>. The K-Means algorithm is adapted by forcing the center coordinates of all bounding box samples to a unified origin $(0,0)$. When stacked directly on top of each other at $(0,0)$, their intersection can be derived entirely from their dimensions:</p><ul><li><strong>Intersection Width:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*Qt0kBYgsgbfQG0xm-YTcMQ.png" /></figure><ul><li><strong>Intersection Height:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*boR2-ySSYzJWsDHVJVIS2A.png" /></figure><ul><li><strong>Intersection Area:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*4eYjy1Cm00TbPnJkvw1tlQ.png" /></figure><ul><li><strong>Union Area:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*s_JumTicYdOBcdvwJV7www.png" /></figure><p>Standard K-Means relies on Euclidean distance to cluster points. However, Euclidean distance fails completely for variable-scale bounding boxes. Under a Euclidean metric, large bounding boxes inherently generate significantly larger numerical errors than smaller bounding boxes, biasing the clustering centroids toward oversized dimensions.</p><p>To create a scale-invariant clustering process, the distance metric is redefined using Intersection over Union (IoU):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*e9AWh-WcUVmsv8mVQ6o8xA.png" /></figure><p>This creates bounded, scale-invariant distance limits:</p><ul><li>If two box profiles match perfectly ($\text{IoU} = 1$), the calculated distance is $0$.</li><li>If two box profiles share completely zero structural similarity ($\text{IoU} = 0$), the calculated distance is $1$.</li></ul><p>By running the iterative K-Means assignment loop using this custom $1 — \text{IoU}$ distance metric, the centroids converge precisely on the most representative aspect ratios and dimensions required for the dataset. This optimization ensures that the model’s neural network only has to perform minimal geometric adjustments during inference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03aa0fa9b8c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accuracy and Speed in Face Detection: IoU, NMS Logic, and a 200x Speedup from Python to C]]></title>
            <link>https://medium.com/@egekasal/accuracy-and-speed-in-face-detection-iou-nms-logic-and-a-200x-speedup-from-python-to-c-70ac0d9b6e5d?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/70ac0d9b6e5d</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Sat, 16 May 2026 13:59:47 GMT</pubDate>
            <atom:updated>2026-05-16T13:59:47.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBG7oxk53py_606KD8SH8A.png" /></figure><p>Object detection pipeline efficiency rests on two pillars: architectural accuracy and execution speed. In real-time face detection, after a model generates raw bounding box regressions, we must accurately evaluate these predictions and eliminate redundancies instantly. This requires deep optimization at both the algorithmic and systemic levels.</p><h4>Measuring Accuracy via Intersection over Union (IoU)</h4><p>To quantify how accurately a model predicts a face’s location, we use Intersection over Union (IoU). The calculation evaluates the overlap between the annotated ground-truth box and the model’s predicted bounding box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*riGAIimaJdNZEfpLKYSW4w.png" /></figure><p>Mathematically, the intersection area is determined by the overlapping region of the two rectangles, while the union area is the total area covered by both boxes minus their intersection. In standard evaluation pipelines, a threshold of 0.5 is established as the baseline; any prediction with an IoU below 0.5 is classified as a failure.</p><h4>Eliminating Redundancies: Non-Maximum Suppression (NMS)</h4><p>During inference, a convolutional network frequently predicts multiple overlapping bounding boxes for the same face. To resolve this, Non-Maximum Suppression (NMS) is applied. NMS identifies the bounding box with the highest confidence score, calculates its IoU against all other overlapping candidate boxes, and suppresses (rejects) any box that exceeds a specific IoU threshold. This ensures that each detected face is bounded by exactly one optimal box.</p><h4>Engineering Optimization: Overcoming the Marshalling Bottleneck</h4><p>While prototyping these geometric operations in Python is straightforward, executing them saniyede binlerce kez (thousands of times per second) within an inference loop introduces massive performance degradation.</p><p>A native Python implementation of an IoU calculation benchmark yields a median latency of 1473.33 ns per call. Rewriting the core logic in C and accessing it via Python’s ctypes foreign function interface drops the raw execution latency down to 319.37 ns per call—a 4.61x algorithmic speedup. However, if we call this C function individually for every single bounding box candidate, data conversion overhead—known as <strong>marshalling</strong>—creates a severe bottleneck. Including marshalling costs, the median latency climbs back up to 1158.92 ns per call, degrading the real-world performance gain to a mere 1.27x.</p><pre>=== Latency Breakdown per Call ===<br>Python Native:        1473.33 ns<br>C (Call Only):         319.37 ns  --&gt; 4.61x Pure Algorithmic Gain<br>C (With Marshalling): 1158.92 ns  --&gt; 1.27x Effective Gain (Bottlenecked)</pre><p>The engineering solution to circumvent this cost is to avoid granular, per-box cross-boundary calls. Instead of looping in Python and shifting individual coordinate variables to C, the entire bounding box array must be passed to C in bulk. By transferring the entire block of data once, the entire multi-candidate processing loop executes natively within compiled memory, rendering the marshalling cost completely negligible.</p><h4>The Benchmark Results</h4><p>To validate this architectural pattern, an intensive loop test was executed over large box arrays to compare native Python loop processing against a bulk-loaded C shared library (libiou.so):</p><ul><li><strong>Python Execution Time:</strong> 0.35321 seconds</li><li><strong>C Library Execution Time:</strong> 0.00183 seconds</li></ul><pre>======= SPEED COMPARISON =======<br>Python:   0.35321 sec<br>C (DLL):  0.00183 sec<br>Result: C implementation is 192.67x FASTER than Python.</pre><p>By transitioning the loop logic entirely to the C layer, the optimization successfully bypasses the marshalling tax, yielding a <strong>192.67x speedup</strong>. This architectural shift is what enables deep learning pipelines to sustain high-throughput, real-time edge processing without sacrificing mathematical precision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70ac0d9b6e5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning’s Eyes: Why Edge Detection and Padding are Critical in Convolutional Networks?]]></title>
            <link>https://medium.com/@egekasal/deep-learnings-eyes-why-edge-detection-and-padding-are-critical-in-convolutional-networks-83f54be0812c?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f54be0812c</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[edge-detection]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Fri, 15 May 2026 10:30:50 GMT</pubDate>
            <atom:updated>2026-05-15T10:30:50.769Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fu7fuaXkL-_Yb9M-fYGYGw.png" /></figure><p>Computer vision does not begin with the recognition of complex objects; it starts with the fundamental ability to detect edges. To a neural network, an image is simply a matrix of brightness values, where high values represent light and low values represent dark regions.</p><h4>The Mathematics of Transitions: 3x3 Kernels</h4><p>An “edge” in an image is defined as a sharp transition in pixel intensity. To identify these transitions, we employ a 3x3 matrix known as a kernel. For instance, a standard vertical edge detection kernel consists of a column of 1s, a column of 0s, and a column of -1s.</p><p>When this kernel slides over a uniform region (where all pixels have similar values), the positive and negative multipliers cancel each other out, resulting in a sum of zero. However, when the kernel encounters a transition — such as a bright area on the left and a dark area on the right — the positive side yields a high value while the negative side remains near zero. The resulting output matrix highlights these sharp changes, making edges visible to the system. Historically, computer scientists manually designed these weights to create specialized filters like the Sobel or Scharr filters.</p><h4>The Evolution: From Manual Tuning to Backpropagation</h4><p>Deep Learning has fundamentally changed how we approach feature extraction. We no longer manually hardcode the nine values within a 3x3 kernel. Instead, these values are initialized as trainable weights. Through the process of backpropagation, the CNN analyzes the data and learns for itself whether it needs to detect vertical lines, 45-degree angles, or complex patterns to solve a specific task.</p><h4>Spatial Integrity: The Critical Necessity of Padding</h4><p>Convolutional operations, by their mathematical nature, cause the output image to shrink. A 6x6 image processed by a 3x3 kernel results in a 4x4 output. In modern deep networks containing hundreds of layers, the original image would shrink until it disappears (1x1) before the network can extract meaningful high-level features.</p><p>Furthermore, without intervention, edge pixels are inherently ignored. While central pixels are covered by the kernel multiple times as it slides across the image, a corner pixel might only be touched once. This leads to a loss of information at the boundaries of the frame.</p><p>Padding — adding a border of zeros around the image — is the engineering solution to these problems:</p><ul><li><strong>Valid Padding:</strong> No padding is applied, allowing the image to shrink naturally.</li><li><strong>Same Padding:</strong> A border is added so that the output matrix dimensions remain identical to the input.</li></ul><p>By implementing “Same” padding, we pull the original edge pixels into the “center” of the operation, ensuring they are processed with the same frequency and depth as the rest of the image, thus preserving critical spatial data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f54be0812c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimization Pitfalls: The Hidden Cost of Marshaling in Python/C Bridging]]></title>
            <link>https://medium.com/@egekasal/optimization-pitfalls-the-hidden-cost-of-marshaling-in-python-c-bridging-eee50c6e0558?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/eee50c6e0558</guid>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[facedetection]]></category>
            <category><![CDATA[iou]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 09:33:32 GMT</pubDate>
            <atom:updated>2026-04-18T09:40:27.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccS9RseK-RRoL0XXMyvBiQ.png" /></figure><p>In the field of computer vision and object detection, accuracy metrics are the pulse of model performance. One of the most fundamental metrics is <strong>Intersection over Union (IoU)</strong>. It measures the overlap between a predicted bounding box and the ground truth annotation.</p><p>The logic is straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*w7WyGKJNquNNT8x-_AH3Zw.png" /></figure><p>While a score below 0.5 is generally considered a failure, the threshold is often adjusted based on specific project requirements. However, when processing thousands of boxes per frame, the implementation’s efficiency becomes just as critical as the model’s accuracy.</p><h4>The Baseline: Python Implementation</h4><p>I initially implemented the calculate_iou function in pure Python. While Python is excellent for rapid development, high-frequency mathematical operations often hit a ceiling.</p><p>The code is straightforward:</p><pre>def calculate_iou(box1, box2):<br><br>    if not validate_box(box1) or not validate_box(box2):<br>        return 0.0<br><br>    ax1, ay1, ax2, ay2 = box1<br>    bx1, by1, bx2, by2 = box2<br>    <br>    inter_x1 = max(ax1, bx1)<br>    inter_y1 = max(ay1, by1)<br>    inter_x2 = min(ax2, bx2)<br>    inter_y2 = min(ay2, by2)<br><br>    inter_w = max(0, inter_x2 - inter_x1)<br>    inter_h = max(0, inter_y2 - inter_y1)<br><br>    inter_area = inter_w * inter_h<br><br>    area_a = (ax2 - ax1) * (ay2 - ay1)<br>    area_b = (bx2 - bx1) * (by2 - by1)<br><br>    union_area = area_a + area_b - inter_area<br><br>    if union_area &lt;= 0:<br>        return 0.0<br><br>    iou = inter_area / union_area<br>    return iou<br><br><br>def validate_box(box):<br>    if len(box) != 4:<br>        return False<br>    if not isinstance(box[0], (int, float)) or not isinstance(box[1], (int, float)) or not isinstance(box[2], (int, float)) or not isinstance(box[3], (int, float)):<br>        return False<br>    if box[0] &gt;= box[2] or box[1] &gt;= box[3]:<br>        return False<br>    return True</pre><p><strong>Performance Metrics (Python):</strong></p><ul><li><strong>Median Latency:</strong> 1528.87 ns/call (~1.53 µs)</li><li><strong>Throughput:</strong> ~654,000 calls/second</li><li><strong>Stability:</strong> Consistent results with minimal jitter.</li></ul><p>For many use cases, 650k calls per second is sufficient. But for real-time applications involving high-density detection, I looked toward C for further optimization.</p><h4>The “Optimization”: Bridging to C with ctypes</h4><p>I rewrote the IoU logic in C and used the ctypes library to call the compiled shared library from Python. Theoretically, C should offer a massive performance leap. The benchmark results, however, told a more nuanced story.</p><p>The code is straightforward:</p><pre>#include &lt;float.h&gt;<br>#include &lt;math.h&gt;<br>#include &lt;stddef.h&gt;<br><br>float fmax_f(float a,float b)<br>{<br>    return a &gt; b ? a : b;<br>}<br><br>float fmin_f(float a,float b)<br>{<br>    return a &lt; b ? a : b;<br>}<br><br>int validate_box(float *box);<br><br>float calculate_iou(float *box1, float *box2)<br>{<br>    if (!validate_box(box1) || !validate_box(box2))<br>    {<br>        return 0.0f;<br>    }<br><br>    float ax1 = box1[0];<br>    float ay1 = box1[1];<br>    float ax2 = box1[2];<br>    float ay2 = box1[3];<br>    float bx1 = box2[0];<br>    float by1 = box2[1];<br>    float bx2 = box2[2];<br>    float by2 = box2[3];<br>    <br>    float inter_x1 = fmax_f(ax1, bx1);<br>    float inter_y1 = fmax_f(ay1,by1);<br>    float inter_x2 = fmin_f(ax2,bx2);<br>    float inter_y2 = fmin_f(ay2,by2);<br><br>    float inter_w = fmax_f(0,inter_x2-inter_x1);<br>    float inter_h = fmax_f(0,inter_y2-inter_y1);<br><br>    float inter_area = inter_w * inter_h;<br><br>    float area_a = (ax2-ax1)*(ay2-ay1);<br>    float area_b = (bx2-bx1)*(by2-by1);<br><br>    float union_area = area_a + area_b - inter_area;<br><br>    if (union_area &lt;= 0)<br>    {<br>        return 0.0f;<br>    }<br><br>    float iou = inter_area / union_area;<br>    <br>    return iou;<br>}<br><br>int validate_box(float *box)<br>{<br><br>    if (box == NULL)<br>    {<br>        return 0;<br>    }<br>    if (!isfinite(box[0]) || !isfinite(box[1]) || !isfinite(box[2]) || !isfinite(box[3]))<br>    {<br>        return 0;<br>    }<br>    if (box[0] &gt;= box[2] || box[1] &gt;= box[3])<br>    {<br>        return 0;<br>    }<br><br>    return 1;<br>}</pre><p><strong>The Benchmark Results (30 repeats, 1M calls each):</strong></p><ul><li><strong>Python Median:</strong> 1473.33 ns/call</li><li><strong>Raw C Median (Call Only):</strong> 319.37 ns/call (<strong>4.61x speedup</strong>)</li><li><strong>C Median (With Marshaling):</strong> 1158.92 ns/call (<strong>1.27x speedup</strong>)</li></ul><h4>The Conclusion: The Marshaling Tax</h4><p>The data reveals a critical engineering bottleneck: <strong>Marshaling</strong>.</p><p>While the core logic in C is nearly 5 times faster than Python, the overhead of converting Python objects into C-compatible data types (and back) consumes the vast majority of those gains. When calling the function individually for each bounding box, we only see a 27% improvement instead of the potential 460%.</p><p><strong>The Takeaway:</strong> If you are bridging to C to optimize a high-frequency function, avoid individual calls. The real performance gain lies in <strong>batch processing</strong>. By passing a large array of bounding boxes to C in a single marshaling step, the overhead becomes negligible, allowing the raw speed of C to be fully utilized.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eee50c6e0558" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why RAG is the Backbone of Reliable AI Applications]]></title>
            <link>https://medium.com/@egekasal/why-rag-is-the-backbone-of-reliable-ai-applications-ac29aa5811db?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac29aa5811db</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 08:36:26 GMT</pubDate>
            <atom:updated>2026-01-07T08:36:26.661Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Gap in LLMs</h4><p>Large Language Models (LLMs) are impressive, but they have two major flaws: <strong>hallucinations</strong> and <strong>static knowledge.</strong> They can only answer based on the data they were trained on, which is often outdated or lacks your specific, private data. This is where <strong>Retrieval-Augmented Generation (RAG)</strong> comes in.</p><h4>What is RAG?</h4><p>RAG is an architectural framework that bridges the gap between a generative model and external, live data sources. Instead of relying solely on its internal memory, the model “retrieves” relevant information from a specific dataset (PDFs, databases, or documentation) before “generating” a response.</p><h4>How It Works: A Simple JavaScript Implementation</h4><p>To understand RAG, let’s look at how we can implement a basic version using JavaScript. In this example, we provide the model with “private context” that it wouldn’t know otherwise.</p><pre>// A simple representation of a RAG flow<br>async function generateRAGResponse(userQuery) {<br>  // 1. Imagine this is our &quot;Vector Database&quot; or private data<br>  const privateKnowledgeBase = {<br>    &quot;project_status&quot;: &quot;The Skin Healthcare App is currently in beta version 2.1.&quot;,<br>    &quot;tech_stack&quot;: &quot;It uses Flutter, Firebase, and DeepSeek-OCR via Vertex AI.&quot;<br>  };<br><br>  // 2. Retrieval Step: Find relevant info based on the query<br>  // For simplicity, we are doing a direct lookup here<br>  const context = userQuery.includes(&quot;status&quot;) <br>                  ? privateKnowledgeBase.project_status <br>                  : &quot;No specific context found.&quot;;<br><br>  // 3. Augmentation Step: Combine context with the prompt<br>  const augmentedPrompt = `<br>    Context: ${context}<br>    Question: ${userQuery}<br>    Answer the question based only on the context provided above.<br>  `;<br><br>  // 4. Generation Step: Send to LLM (e.g., OpenAI or Vertex AI API)<br>  const response = await callLLM(augmentedPrompt);<br>  return response;<br>}</pre><h4>Why It Matters for Developers</h4><ul><li><strong>Accuracy:</strong> It significantly reduces hallucinations because the model is forced to base its answer on provided facts.</li><li><strong>Cost-Efficiency:</strong> Fine-tuning a model is expensive. RAG allows you to update the model’s knowledge simply by updating your database.</li><li><strong>Privacy:</strong> You can connect LLMs to your private data without the need to upload that data for retraining the core model.</li></ul><h4>The Bottom Line</h4><p>In the world of AI APIs, a raw LLM is just a generalist. An LLM powered by RAG is a specialist. For any production-ready application that requires precision and real-time data, RAG is not an option — it is a necessity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac29aa5811db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Strong Dataset Versions in Roboflow: Preprocessing, Augmentation, and Lessons from…]]></title>
            <link>https://medium.com/@egekasal/building-strong-dataset-versions-in-roboflow-preprocessing-augmentation-and-lessons-from-e699e7f753c3?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e699e7f753c3</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[roboflow]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 15:54:33 GMT</pubDate>
            <atom:updated>2025-07-31T15:54:33.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Strong Dataset Versions in Roboflow: Preprocessing, Augmentation, and Lessons from Experience</h3><p>The success of a computer vision model doesn’t just depend on the number of labeled images — it’s just as much about how that data is processed. I’ve seen this repeatedly in my own projects.</p><p>In this article, I want to share some core principles I follow when preparing dataset versions in Roboflow:</p><ul><li>Which preprocessing and augmentation steps are actually effective</li><li>When they help — and when they hurt</li><li>What to watch out for in embedded or resource-limited environments</li></ul><h3>Why Dataset Versioning Matters</h3><p>Roboflow allows you to manage your datasets in versioned pipelines. That means you can experiment with different data processing methods without changing your original annotations.</p><p>Each version can be exported in formats like YOLOv5/8, COCO, or ONNX. Preparing this pipeline properly before training saves a lot of time and effort later.</p><h3>Step 1: Preprocessing — Clean Before You Train</h3><p>Preprocessing steps in Roboflow apply to every image in your dataset. The goal is to feed your model data that’s clean, consistent, and machine-learning friendly.</p><p>Here are the steps I personally rely on:</p><h4>Resize</h4><ul><li>Resize to a square format (e.g. 640×640)</li><li>YOLO models expect square inputs</li><li>Try to maintain aspect ratio when resizing</li></ul><h4>Auto-orient</h4><ul><li>Fixes images rotated due to EXIF metadata</li><li>Should always be enabled</li></ul><h4>Remove Empty Annotations</h4><ul><li>Useful when working with imported or bulk datasets</li><li>Avoids feeding false data to your model</li></ul><blockquote><em>⚠️ Note: On edge devices like Raspberry Pi, avoid high resolutions (e.g. 1024x1024) due to memory and speed constraints.</em></blockquote><h3>Step 2: Augmentation — Generalize, But Don’t Overdo It</h3><p>Augmentation helps your model generalize to new inputs — but too much of it can do more harm than good, especially with small datasets.</p><h4>My Preferred Augmentations</h4><ul><li><strong>Horizontal Flip:</strong> Helps the model recognize mirrored or flipped objects</li><li><strong>Brightness / Contrast Adjustments:</strong> Adds robustness to varying lighting conditions</li><li><strong>Light Blur:</strong> Prepares for motion blur or out-of-focus frames</li><li><strong>Rotation (±10°):</strong> Trains the model on slightly different angles</li></ul><p><em>I typically apply 1–2 augmentations at most per image.</em></p><p><strong>Note:</strong> Avoid aggressive augmentations like mosaic, random crop, or harsh color changes — unless your dataset is synthetic or unusually diverse.</p><h3>Key Takeaways from My Experience</h3><h4>1. Don’t Over-Attack Small Datasets</h4><p>If you have fewer than 1000 images, too much augmentation might confuse the model.</p><h4>2. Match Augmentations to Deployment Environment</h4><p>If you’re deploying to embedded hardware (e.g. Raspberry Pi), keep the augmentations simple and close to the real camera input conditions.</p><h3>Export Settings to Double-Check</h3><p>When exporting from Roboflow, here’s what I personally look out for:</p><ul><li>Format: <strong>YOLOv8 (PyTorch)</strong></li><li>Don’t select pre-trained weights</li><li>Make sure .txt annotation files match .jpg/.png filenames exactly(generally there is no problem at this stage, but I recommend it to do if there are few images)</li><li>If you’re using ONNX, ensure image dimensions and annotation structure match your model’s input expectations</li></ul><h3>Conclusion</h3><p>Dataset preparation is the foundation of your model’s intelligence. Roboflow is a powerful tool — but the way you use it matters just as much as the data itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e699e7f753c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding PID Control: From Core Principles to Practical Code]]></title>
            <link>https://medium.com/@egekasal/understanding-pid-control-from-core-principles-to-practical-code-8e93c5f74ebb?source=rss-56d5bc413da6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e93c5f74ebb</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[pid-controller]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Ege Kasal]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 19:06:53 GMT</pubDate>
            <atom:updated>2025-07-27T19:06:53.721Z</atom:updated>
            <content:encoded><![CDATA[<p>A clear and intuitive explanation of the Proportional–Integral–Derivative algorithm, its components, and how they translate into real code.</p><h3>What Is PID Control?</h3><p>PID stands for <strong>Proportional–Integral–Derivative</strong>. It’s a control algorithm used to bring a system to a desired state (the <strong>setpoint</strong>) by minimizing the difference (<strong>error</strong>) between the desired value and the actual value.</p><p>For example:<em>You want a fan to rotate to 90°. It starts at 0°. A PID controller will calculate how to adjust the motor so that the position smoothly reaches 90° — </em><strong><em>not too fast</em></strong><em>, </em><strong><em>not too slow</em></strong><em>, and </em><strong><em>without overshooting</em></strong><em>.</em></p><h3>Real-Life Analogies for Each Component</h3><h4>1.Proportional (P) — “How far off am I?”</h4><p><strong>Analogy</strong>: You’re steering a car to stay in your lane. The further off you are from the center, the more you turn the wheel.<br><strong>Effect</strong>: The bigger the error, the stronger the correction.</p><p><em>output = Kp * error</em></p><p>Too much <strong>P</strong>? System becomes unstable.<br> Too little <strong>P</strong>? System responds sluggishly.</p><h4>2.Integral (I) — “Have I been off for a long time?”</h4><p><strong>Analogy</strong>: You’re trying to fill a bathtub to a certain level, but it’s filling slowly. Even if you’re just below the desired level, you keep it on a bit longer to “catch up.”<br><strong>Effect</strong>: It accumulates error over time and corrects long-term drift.</p><p><em>integral += error * dt<br> </em><em>output += Ki * integral</em></p><p>Too much <strong>I</strong>? System will overshoot or oscillate.<br> Too little <strong>I</strong>? Steady-state error remains.</p><h4>3.Derivative (D) — “Am I changing too quickly?”</h4><p><strong>Analogy</strong>: You’re approaching a red light. You slow down based on how fast you’re moving — not just your distance to the light.<br><strong>Effect</strong>: Predicts future error and damps sudden changes.</p><p><em>derivative = (error - previous_error) / dt<br></em><em>output += Kd * derivative</em></p><p>Too much <strong>D</strong>? System becomes noisy and jittery.<br> Too little <strong>D</strong>? System may react too aggressively.</p><h3>The Full PID Equation</h3><p>The PID control equation is given as:</p><p><strong>u(t) = Kp × e(t) + Ki × ∫e(t)dt + Kd × (de(t)/dt)</strong></p><p>where:</p><ul><li><strong>Kp</strong> is the proportional gain</li><li><strong>Ki</strong> is the integral gain</li><li><strong>Kd</strong> is the derivative gain</li><li><strong>e(t)</strong> is the current error between setpoint and measurement</li><li><strong>u(t)</strong> is the control output</li></ul><h4>Code Translation:</h4><pre>float error = setpoint - input;<br>integral += error * (interval / 1000.0);<br>float derivative = (error - previous_error) / (interval / 1000.0);<br>float output = Kp * error + Ki * integral + Kd * derivative;<br>previous_error = error;</pre><p>interval / 1000.0 converts milliseconds to seconds for time-based calculations.</p><h3>Conclusion</h3><p>PID control is at the heart of countless engineering systems, from robotics to industrial automation. Yet despite its widespread use, many engineers rely on it as a black box.</p><p>In this article, we broke that box open.</p><p>We explored:</p><ul><li><strong>What PID really is</strong>, in plain terms</li><li><strong>How each component (P, I, D)</strong> behaves and why it matters</li><li><strong>Real-world analogies</strong> to build intuition</li><li><strong>Mathematical structure</strong> of the PID equation</li><li><strong>How that math translates into code</strong></li></ul><p>Understanding these layers — not just using a library — gives you better control over your system’s behavior. It enables informed tuning, smoother response, and more stable designs.</p><p>This is the foundation. In future articles, we’ll look at practical implementations on embedded hardware and real-time tuning in the field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e93c5f74ebb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>