<?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 Yuda Risma Wahyudi on Medium]]></title>
        <description><![CDATA[Stories by Yuda Risma Wahyudi on Medium]]></description>
        <link>https://medium.com/@yudarw?source=rss-17b7fe1f8582------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kZRVY52LoQWAl0X0M46N1A@2x.jpeg</url>
            <title>Stories by Yuda Risma Wahyudi on Medium</title>
            <link>https://medium.com/@yudarw?source=rss-17b7fe1f8582------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:10:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yudarw/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[Understanding the difference between CPK and PPK in process capability analysis]]></title>
            <link>https://medium.com/@yudarw/understanding-the-difference-between-cpk-and-ppk-in-process-capability-analysis-94a07bee0fba?source=rss-17b7fe1f8582------2</link>
            <guid isPermaLink="false">https://medium.com/p/94a07bee0fba</guid>
            <category><![CDATA[process-capability]]></category>
            <dc:creator><![CDATA[Yuda Risma Wahyudi]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 10:33:32 GMT</pubDate>
            <atom:updated>2026-04-01T10:33:32.279Z</atom:updated>
            <content:encoded><![CDATA[<p>In quality control, process capability indices are essential tools for evaluating how well a process meets specification limits. The most widely used indices are Cpk and Ppk. Although they are often confused, these two metrics serve distinct purposes and provide different insights into process stability and performance. This article explores their differences, explains how to calculate them along with sigma within and sigma overall, and offers guidance on interpreting the results.</p><h3>Difference Between Cpk and Ppk</h3><ul><li><strong>Cpk</strong> : measures the potential capability of a process assuming it is stable and in statistical control. It uses the within-subgroup variation (short-term variation) to estimate capability.</li><li><strong>Ppk</strong> : measures the actual performance of a process, taking into account all the data, including long-term variation. It uses the overall variation (long-term variation) to estimate capability.</li></ul><p>In short, Cpk reflects the best-case scenario, while Ppk reflects the real-world scenario. If a process is stable and consistent, Cpk and Ppk values will be close. If not, Ppk will usually be lower than Cpk.</p><h3>Formula</h3><h4>Calculate Cpk</h4><p>To estimate the short-term standard deviation (sigma within), we can use the average moving range (MR) and a statistical constant called d2. The d2 value depends on the number of observations used in the moving range calculation (which is typically N = 2 for consecutive points). For N = 2, the constant d2 is always 1.128.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*pcOLSELUL1ax9YOuzvIssQ.png" /></figure><p>The moving range is the absolute difference between consecutive data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*1m4aRF39diIR2-BPcl9i7Q.png" /></figure><p>To calculate the average moving range, we can sum all the calculated moving ranges and divide by the number of ranges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*JbmJwNtIbMS5pRILv3ut1A.png" /></figure><p>Now, as we already have the short-term standard deviation (sigma within), we can calculate the Cpk using the standard Cpk formula as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*IGPuHqKhlnLWtX6gsrgAZw.png" /></figure><p>Example of calculating sigma within by using C#:</p><pre>private double calc_sigma_within(double[] samples)<br>{<br>    double sigma = 0;<br>    double sum_mr = 0;<br>    for(int i = 0; i &lt; samples.Length; i++)<br>    {<br>        if (i &lt; samples.Length - 1)<br>        {<br>            sum_mr += Math.Abs((samples[i + 1] - samples[i]));<br>        }<br>    }<br>    sigma = (sum_mr / (samples.Length - 1)) / 1.128;<br>return sigma; <br>}</pre><h4>Calculate Ppk</h4><p>To calculate the Ppk index, we use the overall standard deviation of all collected data points. Ppk measures the actual historical performance of the entire process dataset, regardless of whether the process was stable or not. The Ppk formula is identical to the Cpk formula, but it uses the long-term standard deviation in the denominator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*9pl8peaW1V7EH2h2doL-Mw.png" /></figure><p>The overall standard deviation (s) can be calculated using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*MCJq-ZU3zYRbIuk7IkqtuQ.png" /></figure><p>Example of calculating standard deviation using C#:</p><pre>public static double calc_sigma_overall(double[] values)<br>{<br>    double mean = values.Average();<br>    double sumSquares = values.Sum(v =&gt; Math.Pow(v - mean, 2));<br>    return Math.Sqrt(sumSquares / (values.Length - 1));<br>}</pre><h3>Interpreting the Results</h3><h4>Cpk Close to Ppk</h4><p>When the Cpk and Ppk values are close to each other, it is a very positive indication that your manufacturing or business process is statistically stable and in control. The closeness of Cpk and Ppk indicates that there are no significant differences between the short-term variation (used for Cpk) and the long-term variation (used for Ppk). There are no “special causes” of variation (e.g., equipment failures, untrained operators, or inconsistent material batches) causing the average output to shift or drift unpredictably. The only variation present is “common cause” variation inherent in the system itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*o1FFINoU08x0aVfRLVqnHw.png" /></figure><h4>Cpk is Higher than Ppk</h4><p>When the <strong>Cpk value is higher than the Ppk value</strong>, it means <strong>the process is likely unstable or not operating in a state of statistical control</strong>. The gap between Cpk and Ppk indicates that while the process <em>could</em> perform well under ideal conditions (short-term potential), its actual long-term performance is suffering due to variability, shifts, or drifts over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*lH-abRMArsVlCWYv6YaUIg.png" /></figure><p>Based on this example, we can see that there is a significant difference between Cpk and Ppk, where Cpk = 5.95 is higher than Ppk = 1.34. This is because Ppk will calculate the variance of the entire data, including the shift that occurs early in the process (around the first 10 data points). Therefore, the deviation value is high, resulting in a low Ppk.</p><p>Meanwhile, Cpk calculates short-term variation by dividing the data into subgroups. From the individual charts, we can see that the overall process stabilizes after the first 10 data points. It can be said that 90% of the process is stable. Therefore, Cpk indicates that this process has the potential to stabilize if we can maintain and minimize the causes of variation, such as environmental issues (path loss, etc.), operator fault, or other causes.</p><h3>Conclusion</h3><p>Cpk and Ppk are complementary indices that help organizations understand both the <strong>potential capability</strong> and the <strong>actual performance</strong> of a process.</p><ul><li><strong>Cpk</strong> focuses on short-term variation and shows what the process <em>could</em> achieve under control.</li><li><strong>Ppk</strong> focuses on long-term variation and shows what the process <em>is actually achieving</em>.</li></ul><p>When Cpk ≈ Ppk, the process is stable. When Cpk &gt; Ppk, it signals instability and the need for corrective action. By monitoring both indices along with sigma within and sigma overall, businesses can gain a holistic view of process health and drive continuous improvement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94a07bee0fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scratch Defect Detection Method for Automated Optical Inspection (AOI)]]></title>
            <link>https://medium.com/@yudarw/scratch-defect-detection-method-for-automated-optical-inspection-aoi-2e0fe1a83a2e?source=rss-17b7fe1f8582------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e0fe1a83a2e</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[defect-detection]]></category>
            <dc:creator><![CDATA[Yuda Risma Wahyudi]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 02:44:10 GMT</pubDate>
            <atom:updated>2024-12-14T07:01:56.520Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Automated Optical Inspection (AOI) is a visual inspection technology used primarily in the electronic manufacturing industry to enhance product quality by efficiently detecting defects during the manufacturing process. This technology involves the use of cameras and image processing software to automatically inspect defects, where speed and precision are essential, especially for its application in a production line. AOI systems inspect various surface features to check for defects, presence or absence, size, color, shape, alignment, and pattern of components. They check each component in real-time during the manufacturing process to ensure it meets specific design criteria.</p><p>AOI systems consist of two main components: an optical system and software algorithms.</p><h4>Optical System</h4><p>In an AOI system, the optical system plays a key role, as it is responsible for acquiring images for the object to be inspected. The quality of these images impacts the overall performance of the system. The typical optical system in an AOI consists of a light source, a set of lenses, and a digital camera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*OikgoZ3HdywY7ZZ8.jpg" /></figure><h4>Software Algorithm</h4><p>The detection performance and capability of an AOI system rely on the speed and precision of the algorithms. The algorithm is used for analyzing the images captured by the optical system to identify the defects or anomalies in the objects being inspected. This algorithm serves as a ‘brain’ of the AOI system, enabling it to discern acceptable units from those with defects.</p><p>There are several types of software algorithms typically used in AOI systems.</p><ul><li><strong>Pattern Matching Algorithm</strong>, this algorithm works by comparing the captured images of the product to a predefined “good” pattern. This technique is highly effective where consistency is key, such as checking the placement and orientation of components on a printed circuit board.</li><li><strong>Statistical Pattern Matching</strong>, when there is a variation in the components, statistical pattern matching algorithms are used. These algorithms analyze the statistical properties of the images to identify defects by learning the normal variations in the appearance of products over a number of good units and using statistical metrics to determine when a product deviates too far from the normal variation.</li><li><strong>Feature-Based Algorithm</strong>, these are particularly useful when the inspection task involves verifying complex characteristics. These algorithms identify and quantify specific features in the image, such as edges, corners, or areas of a particular color or texture. The identified features are then compared against predefined criteria to determine whether the inspected unit passes or fails.</li><li><strong>Machine Learning Algorithm</strong>, in recent years, machine learning algorithms have begun to find their place in AOI systems. These algorithms, often based on neural network architectures, are capable of learning to identify defects from a large set of training images. This makes them particularly effective for tasks where the defect types are diverse and difficult to define explicitly, or where the appearance of the product can vary significantly.</li></ul><p>It’s crucial to understand that the effectiveness of an algorithm depends heavily on the specific inspection task. Some algorithms may perform well in certain scenarios but not in others. Therefore, a deep understanding of the inspection requirements is essential for selecting the most suitable algorithm for an AOI system.</p><h3>Scratch Defect Detection Algorithm</h3><p>After understanding what AOI is and its key components, we will now try to design an algorithm to detect scratch defects. The product we will inspect is a smartphone LCD screen. The goal is to inspect whether there are any scratch defects on the LCD screen as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gANwBM2exEmGqEwD3TKbmw.png" /><figcaption>Scratch Defect on a LCD Screen</figcaption></figure><p>In this project, we will create a simple object detection algorithm by implementing several image processing techniques with the following pipeline.</p><ul><li>ROI</li><li>Gaussian filtering</li><li>Canny edge detection</li><li>Dilation</li><li>Contour</li><li>Bounding box</li><li>Size filtering</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*TmtyMPZfhGYlU9hf.PNG" /></figure><h4>1. Import the Image</h4><p>For this project, we will use Python and OpenCV library to implement image processing as it offers a wide range of functions to manipulate an image. In Python, we can import the OpenCV library by the following code.</p><pre>import cv2 as cv<br>import matplotlib.pyplot as plt</pre><p>After that, use the cv.imread() to read the image from the local source. Then we will rescale the image. It helps to standardize the dimensions of images, making it easier to process and analyze them consistently, especially when dealing with large datasets. Smaller images require less computational power and memory, which can speed up processing times and reduce resource usage.</p><pre># Import the image<br>img = cv.imread(&quot;Scr_0001.jpg&quot;)<br><br># Convert into a grayscale image<br>img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)  <br><br># Rescale<br>scale_percent = 50  <br>h = int(img.shape[0] * scale_percent / 100)  <br>w = int(img.shape[1] * scale_percent / 100)  <br>input_img = cv.resize(img, (w, h), interpolation=cv.INTER_AREA)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*kYBb2DIWqZWQ6Cc0qYXlJg.png" /></figure><h4><strong>2. Crop image (ROI)</strong></h4><p>In a defect detection system using image processing, defining a Region of Interest (ROI) is crucial for enhancing the accuracy and efficiency of the inspection process. The ROI allows the system to focus on specific areas of the image where defects are most likely to occur, effectively ignoring irrelevant parts of the image that do not contribute to the analysis. By isolating these critical regions, the system can perform more detailed and precise inspections, reducing the computational load and speeding up processing times. This targeted approach not only improves detection accuracy by minimizing noise and irrelevant data but also optimizes resource usage, making the defect detection process more efficient and reliable.</p><pre>x, y, w, h = 140, 80, 680, 340<br>roi = input_img[y:y+h, x:x+w]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*wZy2sbTbxRSzDOeNOeyFcw.png" /></figure><h4>3. Gaussian Filter</h4><p>A Gaussian filter is a linear smoothing filter that’s used to reduce noise and blur regions of an image. It’s a weighted averaging process that uses the Gaussian distribution to assign higher weights to pixels closer to the center of the image and lower weights to pixels farther away. The primary purpose of Gaussian filtering is to reduce noise and detail in the image, making it easier to analyze and process. This is particularly important for tasks like image thresholding, where noise can lead to inaccurate results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*knHQF7roKGQU0bg9fLcTQg.png" /></figure><p>In OpenCV, we can use cv.GaussianBlur()function to apply this filter. The img_gray is the input image that we want to apply the Gaussian filter. It should be a grayscale image. (5, 5)is a tuple representing the size of the Gaussian kernel. The kernel size should be positive and odd (e.g., 3, 5, 7). The kernel size determines the area of the image that will be used to calculate the new pixel values. The 0.5 is the standard deviation in the X direction, denoted as sigmaX . It controls the amount of blurring. A larger value results in more blurring. If sigmaYis not specified, it defaults to the same value as sigmaX .</p><pre>img_gauss = cv.GaussianBlur(img_gray, (5, 5), 0.5)</pre><h4>4. Canny Edge Detection</h4><p>Canny edge detection is a method that is used to identify the edges of objects within an image by detecting areas of rapid intensity change. The process involves several steps: first, a Gaussian filter is applied to smooth the image and reduce noise. Then, the intensity gradients of the image are calculated to highlight regions with significant changes in brightness. Non-maximum suppression is applied to thin out the edges, followed by double thresholding to classify edges as strong, weak, or non-edges. Finally, edge tracking by hysteresis is used to connect weak edges to strong edges, ensuring continuous edge lines.</p><p>In scratch detection, Canny edge detection is particularly useful because it can accurately highlight the boundaries of scratches on surfaces as shown in the image below.</p><p>In OpenCV, we can use cv.Canny() function to perform Canny edge detection. The first parameter is the input image, second and third parameters are the lower and upper thresholds for the hysteresis procedure.</p><pre>img_canny = cv.Canny(img_gauss, 100, 200)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlaKWAWRhvgYqKMEwpOc9g.png" /><figcaption>Canny edge detection result with and without Gaussian filter</figcaption></figure><h4>5. Dilation</h4><p>Dilation is one of the morphological operations in image processing that involves expanding the boundaries of objects within an image. This is achieved by convolving the image with a structuring element (or kernel), which causes the bright regions to grow and fill in small holes or gaps. The primary purpose of dilation is to enhance certain features of the image, such as connecting disjointed elements, filling small holes, and emphasizing the structure of objects. It is particularly useful in applications like noise removal, where it helps to merge fragmented parts of an object, and in preparing images for further analysis, such as edge detection or object recognition.</p><pre>kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))<br>img_dilation = cv.dilate(img_canny, kernel, iterations=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*lmKpcH3uW6TuZpYU9Pn1YA.png" /><figcaption>Result of dilation</figcaption></figure><h4>6. Find Contours</h4><p>We perform steps 1 to 5 to preprocess the image, allowing us to clearly filter and separate the defect areas from any noise. Once the defect areas are distinct, the final step is to draw a bounding box to mark the defects. The cv.findContours()function identifies the contours in the preprocessed image, representing the boundaries of potential defects. For each detected contour, the cv.boundingRect() function calculates a bounding rectangle that encloses the contour. Additionally, the code labels each detected defect with the text “Defect”.</p><pre>contours, hierarchy = cv.findContours(img_dilation, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)<br>for contour in contours:<br>    rect = cv.boundingRect(contour)<br>    cv.rectangle(roi, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (255, 0, 0), 2)<br>    <br>    # Draw text with color filled background<br>    text = &quot;Defect&quot;<br>    font = cv.FONT_HERSHEY_DUPLEX<br>    font_scale = 0.7<br>    font_thickness = 1<br>    text_size = cv.getTextSize(text, font, font_scale, font_thickness)[0]<br>    text_x = rect[0]<br>    text_y = rect[1] - 10 if rect[1] - 10 &gt; 10 else rect[1] + 40<br>    cv.rectangle(roi, (text_x, text_y - text_size[1] - 5), (text_x + text_size[0] + 5, text_y + 5), (255, 0, 0), cv.FILLED)<br>    cv.putText(roi, text, (text_x, text_y), font, font_scale, (255, 255, 255), font_thickness)</pre><p>The final result of our scratch detection algorithm is shown as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*NryMfpmjuXXbbWRBTrrWgw.png" /></figure><h3>Full Python Code Implementation</h3><pre>import cv2 as cv<br>import matplotlib.pyplot as plt<br><br>def plot_image(img, title):<br>    # Plot the images<br>    plt.figure(figsize=(10, 5))<br>    plt.axis(&#39;off&#39;)<br>    plt.title(title)<br>    plt.imshow(img)<br>    plt.show()<br><br>def defect_detection(filename):<br>    # Load image<br>    img = cv.imread(filename)<br>    <br>    #print(f&quot;Resolution = {img.shape}&quot;)<br><br>    # Rescale image<br>    scale_percent = 50<br>    h = int(img.shape[0] * scale_percent / 100)<br>    w = int(img.shape[1] * scale_percent / 100)<br>    input_img = cv.resize(img, (w, h), interpolation=cv.INTER_AREA)<br><br>    # Crop<br>    x, y, w, h = 140, 80, 680, 340<br>    #roi = input_img.copy()<br>    roi = input_img[y:y+h, x:x+w]<br>    #plot_image(roi,&quot;roi&quot;)<br><br><br>    # Convert to gray<br>    #img_gray = cv.cvtColor(input_img, cv.COLOR_BGR2GRAY)<br>    img_gray = cv.cvtColor(roi, cv.COLOR_BGR2GRAY)<br><br>    # Gaussian blur<br>    img_gauss = cv.GaussianBlur(img_gray, (5, 5), 0.5)<br><br>    # Canny edge detection<br>    img_canny = cv.Canny(img_gauss, 100, 200)<br><br>    # Dilation<br>    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))<br>    img_dilation = cv.dilate(img_canny, kernel, iterations=1)<br>    # Find contours<br>    contours, hierarchy = cv.findContours(img_dilation, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)<br><br>    for contour in contours:<br>        rect = cv.boundingRect(contour)<br>        #print(f&quot;Rectangle size: {rect[2]}x{rect[3]}&quot;)<br>        cv.rectangle(roi, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (255, 0, 0), 2)<br>        # Draw text with color filled background<br>        text = &quot;Defect&quot;<br>        font = cv.FONT_HERSHEY_DUPLEX<br>        font_scale = 0.7<br>        font_thickness = 1<br>        text_size = cv.getTextSize(text, font, font_scale, font_thickness)[0]<br>        text_x = rect[0]<br>        text_y = rect[1] - 10 if rect[1] - 10 &gt; 10 else rect[1] + 40<br>        cv.rectangle(roi, (text_x, text_y - text_size[1] - 5), (text_x + text_size[0] + 5, text_y + 5), (255, 0, 0), cv.FILLED)<br>        cv.putText(roi, text, (text_x, text_y), font, font_scale, (255, 255, 255), font_thickness)<br><br>    return input_img<br><br># Try to detect the image:<br>img = defect_detection(&quot;Scr_0001.jpg&quot;)<br>plot_image(img, &quot;img1&quot;)</pre><p>To achieve better accuracy, the parameters used in calculating ROI, Gaussian, Canny, or dilation can be adjusted according to the condition of the defect image to be detected. Basically, as long as we can eliminate objects and noise other than the defect, it will be easy to determine the area on the screen categorized as a scratch defect. This algorithm is very simple and quite reliable for application in simple systems, such as detecting scratch defects on smartphone screens. However, if the type of defect and its complexity cannot be resolved with image processing, we must use other object classification methods like deep learning. Of course, the process and computation will become more complicated, and the speed may not be as fast as using image processing.</p><p>At the end, optimizing the algorithm is about how we can use the appropriate method for the task or problem we want to solve.</p><h3>Implementation of the Algorithm in Different Images</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*tSCbcYDkxx0DlRVWR4Euxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*Y80dQmB2PFplwtRFVanVwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*_Bkg5Q17ETQIG7Ug5BL8cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*DC0WRXSgktFrrzZn65mbvA.png" /></figure><h3>Reference</h3><p>The dataset of images can be downloaded in <a href="https://www.kaggle.com/datasets/girish17019/mobile-phone-defect-segmentation-dataset">h</a>ere.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e0fe1a83a2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apa itu Batch Size dan bagaimana Batch Size mempengaruhi proses training?]]></title>
            <link>https://medium.com/@yudarw/apa-itu-batch-size-dan-bagaimana-batch-size-mempengaruhi-proses-training-dcaaf7a2ebf8?source=rss-17b7fe1f8582------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcaaf7a2ebf8</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yuda Risma Wahyudi]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 09:15:40 GMT</pubDate>
            <atom:updated>2024-11-19T09:39:18.737Z</atom:updated>
            <content:encoded><![CDATA[<p>Pada artikel ini, kita akan membahas mengenai <em>batch size, </em>konsep dasar, dan pengaruh <em>batch size</em> dalam training machine learning. Selain itu kita juga akan mempelajari perbedaan antara <em>batch size</em> besar dan kecil berserta kelebihan dan kekuranganya, sehingga kita dapat memahami bagaimana cara menentukan ukuran <em>batch size</em> yang optimal untuk meningkatkan efisiensi pada proses training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*OwFUbX0jyR8jTzK0.jpg" /></figure><h3>Memahami <em>Batch Size</em></h3><p><em>Batch size</em> adalah salah satu parameter penting dalam training model pada machine learning. <em>Batch size</em> mengacu pada penentuan jumlah sampel yang diproses dalam satu kali iterasi sebelum memperbarui bobot (<em>weight</em>) pada model. Sebagai contoh, jika kita memiliki dataset yang terdiri dari 1000 sampel dan kita menetapkan <em>batch size</em> sebesar 50, maka model akan memproses 50 sampel sekaligus, meng-<em>update </em>parameter, kemudian melanjutkan ke 50 sampel berikutnya, seterusnya hingga seluruh dataset selesai diproses.</p><p>Pemilihan <em>batch size</em> akan berpengaruh secara langsung pada berbagai aspek dalam proses training, seperti kecepatan konvergensi dan generalisasi model. <em>Batch size</em> yang kecil dapat membantu model untuk lebih sering memperbarui parameter, yang bisa membantu dalam menemukan solusi yang lebih baik dan menghindari jebakan <em>local minima</em>. Namun, <em>batch size</em> yang terlalu kecil juga dapat menyebabkan pembaruan parameter yang terlalu bising dan tidak stabil. Sebaliknya, <em>batch size</em> yang lebih besar cenderung menghasilkan pembaruan parameter yang lebih stabil dan konsisten, tetapi mungkin membutuhkan lebih banyak waktu untuk mencapai konvergensi dan bisa beresiko <em>overfitting</em>.</p><p>Memahami <em>trade-off</em> antara <em>batch size</em> sangat penting untuk mendapatkan hasil training yang optimal.</p><h3>Pemilihan Batch Size Kecil</h3><p>Penggunaan <em>batch size</em> kecil dalam proses pelatihan model mempunyai beberapa keuntungan. Pertama, <em>batch size</em> kecil cenderung menghasilkan komputasi yang lebih efisien dimana model akan lebih sering memperbarui parameter sehingga dapat mencapai konvergensi lebih cepat. Selain itu, pemilihan <em>batch size</em> kecil memungkinkan model untuk menjelajah ruang parameter secara lebih luas, yang berpotensi membantu keluar dari titik <em>local-minimum</em> dan mencapai solusi yang lebih baik. B<em>atch size </em>yang kecil juga cenderung membutuhkan memori yang lebih sedikit, sehingga cocok digunakan untuk training pada <em>hardware </em>yang terbatas atau untuk menangani dataset yang lebih besar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*HPZzjWrTndq1Kq0C4UJ2tg.png" /><figcaption>A local minium and a global minimum</figcaption></figure><p>Selain dari keuntungan-keuntungan tersebut,<em> batch size</em> yang kecil juga mempunyai beberapa kelemahan. Salah satu masalah yang sering ditemui adalah potensi pembaruan parameter yang bising (<em>noisy update</em>) yang akan menyebabkan perhitungan gradien menjadi kurang akurat. Gradien menunjukkan arah dan seberapa besar perubahan yang diperlukan untuk mengurangi error. Ketika menggunakan <em>batch size</em> yang kecil, hanya sedikit sample data yang digunakan untuk menghitung gradien pada setiap iterasi. Hal ini menyebabkan estimasi gradien menjadi lebih bervariasi atau “<em>noisy</em>” karena <em>batch size </em>yang kecil mungkin tidak cukup merepresentasikan keseluruhan data. <em>Batch size</em> kecil juga membutuhkan iterasi yang lebih banyak sehingga akan membuat waktu training menjadi lebih lambat. <em>Batch size</em> kecil juga cenderung meningkatkan variasi performa pada setiap iterasi sehingga menyebabkan proses training menjadi kurang stabil.</p><h3>Pemilihan Batch Size Besar</h3><p>Menggunakan <em>batch size</em> yang besar dalam pelatihan model pada machine learning memiliki beberapa keuntungan. Dengan <em>batch size</em> yang lebih besar, estimasi gradien menjadi lebih stabil dan mengurangi variasi, karena lebih banyak sampel yang digunakan untuk menghitung gradien sehingga menjadi lebih stabil dan lebih akurat.<em> Batch size</em> yang besar dapat memanfaatkan efisiensi komputasi pada perangkat keras seperti GPU, yang sering kali dioptimalkan untuk memproses data dalam jumlah besar secara paralel. Karena lebih banyak data yang diproses dalam setiap iterasi, pelatihan model bisa lebih cepat dalam hal waktu per iterasi (<em>epoch</em>).</p><p>Namun, pemilihan ukuran <em>batch size</em> yang besar juga memiliki beberapa kelemahan. Masalah pertama adalah keterbatasan memori, khususnya untuk menangani dataset atau model dengan jumlah parameter yang sangat besar. <em>Batch size</em> yang besar membutuhkan lebih banyak memori yang akan menjadi masalah apabila <em>hardware</em> yang digunakan memiliki memori yang terbatas. <em>Batch size </em>yang besar membutuhkan lebih banyak memori untuk menyimpan data selama proses perhitungan dan pembaruan gradien yang kemungkinan besar dapat melebihi kapasitas memori yang tersedia, sehingga dapat menyebabkan<em> out-of-memory error</em> dan mengurangi kecepatan training. Selain itu, dengan <em>batch size</em> yang besar, model mungkin lebih mudah overfit pada data pelatihan karena pembaruan parameter yang lebih jarang dan kurangnya variasi dalam data yang diproses pada setiap iterasi. <em>Update </em>parameter yang lebih jarang juga membuat waktu yang diperlukan model untuk mencapai konvergensi menjadi lebih lama.</p><p>Ukuran <em>batch size</em> yang besar dapat menghasilkan <em>smoother optimization-trajectory </em>dan meningkatkan efisiensi komputasi, tetapi <em>batch size</em> yang besar juga mempunyai tantangan berkaitan dengan keterbatasan memori dan konvergensi yang lebih lambat.</p><h3>Cara Menentukan Batch Size yang Optimal</h3><p>Memilih ukuran <em>batch size</em> yang sesuai adalah tahapan yang krusial dalam proses training model machine learning karena hal ini akan sangat mempengaruhi performa dari model tersebut. Berikut ini adalah panduan dan langkah-langkah untuk menentukan ukuran <em>batch size</em>.</p><ul><li><strong>Ukuran Dataset</strong>: Untuk dataset yang lebih kecil, gunakan <em>batch size</em> yang kecil seperti 32 atau 64. Ukuran <em>batch size </em>yang kecil umumnya memberikan hasil yang lebih stabil dan memungkinkan model untuk belajar lebih cepat pada tahap awal. Sebaliknya, untuk dataset yang lebih besar, gunakan <em>batch size</em> yang besar agar komputasi menjadi lebih efisien.</li><li><strong>Arsitektur Model</strong>: kompleksitas arsitektur model dapat mempengaruhi pemilihan <em>batch size</em>. Model yang kompleks dengan lebih banyak parameter membutuhkan <em>batch size</em> yang lebih kecil untuk mengatasi keterbatasan memori. Sebaliknya, model yang lebih sederhana akan lebih efektif apabila menggunakan <em>batch size</em> yang lebih besar.</li><li><strong>Sumber daya komputasi</strong>: Pastikan <em>batch size</em> yang dipilih sesuai dengan kapasitas memori GPU yang kita gunakan. Pemilihan <em>batch size</em> harus mempetimbangkan spesifikasi hardware untuk memaksimalkan komputasi tanpa melebihi kapasitas memori yang tersedia.</li></ul><h3>Trade-Off</h3><p>Pemilihan <em>batch size</em> yang optimal perlu mempertimbangkan <em>trade-off</em> dari berbagai faktor seperti <em>training speed</em>, <em>convergence stability</em>, dan <em>generalization performance</em>.</p><ul><li><strong>Training Speed</strong>: Training menggunakan <em>batch size</em> yang besar cenderung menghasilkan waktu iterasi yang lebih cepat. Sedangkan <em>batch size</em> yang kecil mungkin membutuhkan waktu konfergensi yang lebih lama tapi pembaruan parameter akan menjadi lebih sering.</li><li><strong>Convergence Stability</strong>: <em>Batch size </em>yang kecil mungkin membutuhkan waktu konfergensi yang lebih lama dan pembaruan parameter yang lebih bervariasi. Sedangkan <em>batch size</em> yang lebih besar cenderung menghasilkan pembaruan parameter yang lebih stabil.</li><li><strong>Generalization Performance</strong>: Ukuran <em>batch </em>yang lebih besar dapat mempercepat pelatihan tetapi mungkin mengorbankan generalisasi model yang dapat menyebabkan <em>overfitting</em>. Sebaliknya, ukuran <em>batch </em>yang lebih kecil dapat meningkatkan generalisasi tetapi memperlambat pelatihan.</li></ul><h3>Best Practice</h3><p>Untuk mengetahui pengaruh dari <em>batch size</em> dalam training, kita dapat mempertimbangkan beberapa hal sebagai berikut:</p><ul><li><strong>Pengaturan Learning Rate</strong>: Kita dapat meningkatkan stabilitas training dengan mengatur <em>learning rate</em> yang sesuai. <em>Batch size</em> yang besar cenderung membutuhkan<em> learning rate</em> yang lebih tinggi untuk mengatasi masalah konfergensi. Sedangkan <em>batch size</em> yang kecil akan lebih optimal jika menggunakan <em>learning rate</em> yang lebih rendah untuk menghindari <em>overshooting</em>.</li><li><strong>Batch Normalization</strong>: <em>Batch normalization</em> adalah teknik yang umumnya digunakan untuk menstabilkan proses training can mempercepat konfergensi. Normalisasi aktivasi pada setiap <em>mini-batch</em> dapat mengurangi <em>internal covariate shift </em>dan membantu menstabilkan gradien selama proses training.</li><li><strong>Mini-Batch Gradient Descent</strong>: <em>Mini-batch gradient descent</em> adalah algoritma optimisasi yang populer untuk training model dengan<em> batch size</em> yang berbeda. Algortima ini membagi dataset pelatihan menjadi kelompok-kelompok kecil yang disebut <em>mini-batch</em>. Setiap <em>mini batch</em> digunakan untuk menghitung <em>error </em>dan memperbarui parameter model.</li></ul><h3>Contoh Implementasi Batch Size</h3><p>Pada bagian ini, kita akan mempelajari pengaruh <em>batch size</em> pada pelatihan model menggunakan dataset MNIST. Kita akan menggunakan TensorFlow dan Keras untuk melatih model sederhana dengan dua <em>batch size</em> yang berbeda: 32 dan 128.</p><h4>Contoh Program</h4><pre>import tensorflow as tf<br>from tensorflow.keras.datasets import mnist<br>from tensorflow.keras.models import Sequential<br>from tensorflow.keras.layers import Dense, Flatten<br>from tensorflow.keras.optimizers import Adam<br><br># Memuat dataset MNIST<br>(x_train, y_train), (x_test, y_test) = mnist.load_data()<br>x_train, x_test = x_train / 255.0, x_test / 255.0<br><br># Membuat model sederhana<br>def create_model():<br>    model = Sequential([<br>        Flatten(input_shape=(28, 28)),<br>        Dense(128, activation=&#39;relu&#39;),<br>        Dense(10, activation=&#39;softmax&#39;)<br>    ])<br>    model.compile(optimizer=Adam(), loss=&#39;sparse_categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>    return model<br><br># Melatih model dengan batch size 32<br>model_32 = create_model()<br>history_32 = model_32.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_test, y_test))<br><br># Melatih model dengan batch size 128<br>model_128 = create_model()<br>history_128 = model_128.fit(x_train, y_train, epochs=5, batch_size=128, validation_data=(x_test, y_test))</pre><h4>Hasil Pengujian</h4><p>Setelah menjalankan program di atas, kita bisa membandingkan hasil pelatihan untuk kedua batch size. Berikut adalah hasil yang didapatkan:</p><p><strong>Batch Size 32</strong></p><ul><li>Waktu training: 9 detik/iterasi</li><li>Akurasi training: 98.56%</li><li>Akurasi validasi: 97.61%</li></ul><p><strong>Batch Size 128</strong></p><ul><li>Waktu training: 3 detik/iterasi</li><li>Akurasi training : 97.82%</li><li>Akurasi validasi: 97.33%</li></ul><h4>Analisis</h4><p><strong>Batch Size 32</strong>: Update parameter lebih sering, yang dapat membantu model menemukan solusi yang lebih baik, tetapi membutuhkan lebih banyak waktu untuk setiap epoch.<br><strong>Batch Size 128</strong>: Update parameter lebih jarang, yang dapat mempercepat pelatihan tetapi mungkin kurang efektif dalam menemukan solusi optimal.</p><h3>Kesimpulan</h3><p>Pemilihan <em>batch size</em> akan sangat mempengaruhi performa training dari sebuah model. Memahami pengaruh pemilihan<em> batch size</em> (kecil atau besar) sangat penting untuk mendapatkan proses training yang optimal dan hasil yang sesuai. Pemilihan <em>batch size</em> perlu mempertimbangkan <em>trade-off</em> antara beberapa faktor seperti ukuran dataset, arsitektur model, dan spesifikasi <em>hardware</em>. Selain itu, untuk meningkatkan performa model juga dapat dilakukan dengan mengatur <em>learning rate</em> dan normalisasi <em>batch </em>untuk mengetahui pengaruh dari pemilihan <em>batch size</em>.</p><h3>Reference</h3><p><a href="https://mljourney.com/how-does-batch-size-affect-training/">How Does Batch Size Affect Training? — ML Journey</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcaaf7a2ebf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with YOLOv8]]></title>
            <link>https://medium.com/@yudarw/getting-started-with-yolov8-f7f415703293?source=rss-17b7fe1f8582------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f415703293</guid>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolov8]]></category>
            <dc:creator><![CDATA[Yuda Risma Wahyudi]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 14:25:43 GMT</pubDate>
            <atom:updated>2024-11-17T04:24:19.500Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSCkO2Q8v_4m-V3fVQ6pEw.png" /></figure><p>This article will describe the step-by-step on how to use YOLOv8 for object detection. Getting started with YOLO involves setting up our environment, installing dependencies, preparing dataset, and running the object detection pipeline. YOLOv8 is part of the latest generation of the YOLO object detection. It brings improvements in speed, accuracy, and usability.</p><h3>Step 1: Install YOLOv8</h3><p>First step, we need to install YOLOv8 package and its dependencies in our Python environment. We can do this by using the following command.</p><pre>pip install ultralytics</pre><h3>Step 2: Load a Pre-trained Model</h3><p>Once everything is installed, verify that the YOLOv8 package is installed correctly and the dependencies are working. We can run the following command to check if the YOLOv8 package is working.</p><pre>from ultralytics import YOLO<br><br># Load a pretrained YOLOv8 model (e.g., YOLOv8n for a smaller and faster model)<br>model = YOLO(&#39;yolo8n.pt&#39;) # replace &#39;n&#39; with &#39;s&#39;,&#39;m&#39;,&#39;l&#39;, or &#39;x&#39; for different sizes<br><br>results = model.predict(&#39;path/to/image.jpg&#39;)<br>img = results[0].plot()<br>cv.imshow(&#39;Yolov8 object detection result&#39;, img)</pre><p>The following example show how to detect object from webcam.</p><pre>from ultralytics import YOLO<br>import cv2 as cv<br><br># Load a pretrained YOLOv8 model<br>model = YOLO(&#39;yolov8n.pt&#39;)<br><br># Initialize webcam<br>cap = cv.VideoCapture(0)<br><br>while True:<br>    ret, frame = cap.read()<br>    if not ret:<br>        break<br><br>    results = model.predict(frame)<br>    image = results[0].plot()<br>    cv.imshow(&#39;results&#39;, image)<br><br>    if cv.waitKey(1) &amp; 0xFF == ord(&#39;q&#39;):<br>        break<br><br>cap.release()<br>cv.destroyAllWindows()</pre><h3>Step 3: Training Your Custom Model</h3><p>YOLOv8 can be trained on a custom dataset or used with an existing datset like COCO or VOC. The following steps describe how to prepare our own dataset and train the dataset using YOLO.</p><h4>Prepare Dataset</h4><p>The dataset should be in the YOLO format, which consist of:</p><ul><li>Images: Each image file (usually .jpg or .png )</li><li>Annotations: A .txt file for each image containing annotations. Each line in the annotation file corresponds to one object in the image and has the following format:</li></ul><pre>&lt;class_id&gt; &lt;x_center&gt; &lt;y_center&gt; &lt;width&gt; &lt;height&gt;</pre><ul><li>class_id is an integer representing the ID of the object class. x_center and y_center are the normalized center coordinates of the object relative to the image width and height. width and height are the normalized width and height of the object</li></ul><h4>Organize the Dataset</h4><p>The dataset should be organized in the following structure:</p><pre>/dataset<br>  /images<br>    /train<br>      image1.jpg<br>      image2.jpg<br>      ...<br>    /val<br>      val_image1.jpg<br>      val_image2.jpg<br>      ...<br>/labels<br>  /train<br>    image1.txt<br>    image2.txt<br>    ...<br>  /val<br>    val_image1.txt<br>    val_image2.txt<br>    ...</pre><p>Make sure that the images and their corresponding annotation files are in the correct folders.</p><h4>Create a Configuration File</h4><p>Create a YAML file for the dataset configuration. This file will specify paths to the images and labels, as well as the number of classes and class names.</p><p>Create a file so called dataset.yaml</p><pre>train: path/to/train/images<br>val: path/to/val/images<br>nc: &lt;number_of_classes&gt;<br>names: &lt;&#39;class1&#39;,&#39;class2&#39;,...,&#39;classN&#39;&gt;## Dada</pre><h4>Train the Model</h4><p>Now, we are ready to train the YOLOv8 model on our custom dataset. To train a YOLOv8 model, we can use the train method from the ultralytics package.</p><pre># load a base model<br>model = YOLO(&#39;yolov8n.pt&#39;)<br>model.train(data=&#39;dataset.yaml&#39;, epochs=50, imgsz=640)</pre><ul><li>The yolov8n refers to the YOLOv8 Nano model configuration (we can also use yolov8s for small, yolov8m for medium, and yolov8l for large models depending on the needs).</li><li>dataset.yaml specifies the path to the dataset configuration.</li><li>epochs=50 represents the number of training epochs</li><li>imgsz=640 is the inpit image size for training</li></ul><h4>Evaluate Model</h4><p>To validate the model performance, we can use the following code.</p><pre>results = model.val(data=&#39;dataset.yaml&#39;)<br>print(results)</pre><h4>Export Model</h4><p>We can export our trained YOLOv8 model to other formats, such as TensorFlow, ONNX (Open Neural Network Exchange), or CoreML for deployment.</p><p>For example, to export to the ONNX format:</p><pre>model.export(format=&quot;onnx&quot;, imgsz=640)</pre><p>This will save the model in the current directory as yolov8n.onnx (or another model name, depending on the model we loaded)</p><p>If you want to deploy the model in a PyTorch based environment, you can export it in the TorchScript format.</p><pre>model.export(format=&quot;torchscript&quot;, imgsz=640)</pre><h3>Conclusion</h3><p>By following these steps, you should be able to:</p><ol><li>Setup the environment for YOLOv8.</li><li>Prepare dataset in the YOLO format.</li><li>Train a custom model.</li><li>Perform inference and evaluate performance.</li><li>Export the model for deployment.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f415703293" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>