Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
FREEDOM251

Freedom251 › Blog › Class Imbalance

How to Handle Class Imbalance in Concrete Crack Segmentation

By Freedom251 Team · · 11 min read

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a staged approach: measure crack-pixel prevalence, establish BCE and Dice baselines, add weighting or focal/Tversky loss only when the foreground is genuinely sparse, and tune the decision threshold on validation images. Treat sampling as a separate experiment. This avoids the two common failures of crack segmentation: a model that predicts background everywhere with deceptively high accuracy, and a model that finds cracks by flagging every crack-like texture.

What class imbalance means in concrete crack segmentation

In a pixel-segmentation task, class imbalance is the difference between the number of background pixels and crack pixels. A 2,000 × 1,000 image contains two million pixels; if a thin crack occupies 0.2% of the image, only 4,000 pixels represent the foreground. A model can therefore obtain very high pixel accuracy while missing most of the crack.

As an Amazon Associate I earn from qualifying purchases.

Concrete imagery makes the problem harder than the ratio alone suggests. Cracks may be one or two pixels wide, interrupted by shadows, partly hidden by dirt, or visually similar to joints, stains, aggregate boundaries and spalled edges. The minority class is also heterogeneous: a hairline crack and a wide, branching fracture do not present the same texture or geometry.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Imbalance ratios are dataset-specific. Nguyen and Thai’s 2023 paper in Engineering Structures reports the following values using its own calculation:

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
Dataset Images Reported imbalance ratio Context
GAPs384 384 278:1 Concrete crack imagery; figures reported by Nguyen and Thai (2023)
CRKWH100 100 218:1 Concrete crack imagery; figures reported by Nguyen and Thai (2023)
Labeled Cracks in the Wild (LCW) 3,817 332:1 Crack imagery collected under varied conditions; figures reported by Nguyen and Thai (2023)
CrackLS315 315 394:1 Concrete crack imagery; figures reported by Nguyen and Thai (2023)

Those ratios describe the named datasets and the paper’s method; they are not a universal threshold at which every model becomes unusable. The same paper describes DeepCrack as 537 images at 544 × 384 pixels, containing concrete and asphalt pavement scenes, and EdmCrack600 as 600 images at 1,920 × 1,080 pixels, both with pixel-wise annotations. Image resolution, annotation thickness and the proportion of empty scenes can change the effective difficulty even when two datasets have similar ratios.

Measure the imbalance before changing the loss

Calculate foreground prevalence on the training split

For binary masks, calculate:

crack prevalence = crack pixels / total pixels

Also report the inverse background-to-crack ratio if that is how your team communicates imbalance. Keep the calculation on the training split so that validation and test information does not influence preprocessing decisions. A single mean can conceal important variation, so retain the per-image distribution as well.

Inspect how prevalence varies by scene

Record the percentage of crack pixels for every source image before making patches. Plot or tabulate empty images, images with a tiny isolated crack, and images containing broad or branching damage. A model trained mostly on images with one easy crack can fail on a site where cracks are faint and fragmented, even if the overall pixel ratio looks acceptable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prevent leakage when making patches

Split by source image, structure, inspection visit or site before extracting patches whenever related images could occur in more than one split. Creating overlapping patches first and then randomly distributing them can place near-duplicates in training and validation, producing an optimistic score. Patch extraction should be deterministic and documented after the split.

  • Store the source-image identifier with every patch.
  • Keep all patches from one source image in the same split.
  • Report the number of source images and patches separately.
  • Recalculate crack prevalence after patch selection because sampling changes the training distribution.

Choose a loss function by imbalance severity and error cost

No loss function is a universal winner. Nguyen and Thai compared 12 commonly used losses across four datasets and found that rankings changed with the model, dataset and imbalance severity. Their abstract reports that most losses had relatively similar accuracy on mildly imbalanced data, while weighted binary cross-entropy, Focal, Dice-based and compound losses became more effective as imbalance increased. Their highlighted conclusion identifies Focal Tversky as the most robust loss in their severe-imbalance comparison.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Binary cross-entropy: the reference baseline

Binary cross-entropy (BCE) computes a penalty for each pixel and is a useful first baseline because it is easy to interpret and optimize. It can work well when crack prevalence is only mildly skewed or when labels contain substantial uncertainty. Plain BCE, however, allows the large background population to dominate the aggregate loss when cracks are extremely sparse.

Weighted BCE: increase the cost of missed crack pixels

Weighted BCE assigns a larger contribution to crack pixels than to background pixels. The weight should be selected on validation data rather than copied from the raw ratio automatically; an extreme ratio can produce unstable gradients or excessive false positives. Compare several moderate weights while keeping the optimizer, augmentation and training schedule fixed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Dice and Jaccard losses: optimize overlap

Dice and Jaccard (intersection over union) losses emphasize the overlap between predicted and annotated regions rather than treating every background pixel equally. They are often useful when the foreground is thin and sparse. They can be less informative when a prediction contains many isolated false-positive pixels but still overlaps a small true crack, so pair them with precision and visual inspection.

Focal loss: concentrate on difficult pixels

Focal loss down-weights well-classified examples and concentrates training on difficult pixels. Its implementation commonly exposes alpha and gamma; the meaning and accepted input format depend on the library version. Tune those parameters against validation precision, recall and overlap instead of assuming values from an unrelated detection task.

Tversky and Focal Tversky losses: choose the false-error trade-off

Tversky-family losses let you give different importance to false positives and false negatives. This is useful when missing a faint crack is more costly than investigating an extra candidate, or when an inspection workflow cannot tolerate a large number of false alarms. Focal Tversky adds focusing behavior to emphasize hard examples. In the cited comparison it was the strongest severe-imbalance choice, but that result remains bounded by the tested datasets, architecture and metrics.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Compound losses: combine complementary signals

A compound loss can combine a pixel-wise term such as BCE with an overlap term such as Dice. The pixel-wise component supplies local supervision while the overlap component counters foreground sparsity. Because the relative scale of each term affects optimization, compare combinations with a fixed validation protocol and record the exact coefficients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Approach Best reason to try it Main risk What to monitor
BCE Transparent baseline and stable pixel-wise supervision Background can dominate when cracks are very rare Recall, precision and predicted crack prevalence
Weighted BCE Raises the penalty for missed crack pixels Too much weight can create false positives or unstable training Precision–recall trade-off and training stability
Dice or Jaccard Directly emphasizes region overlap Small noisy regions can distort the overlap signal Dice/IoU plus isolated false positives
Focal Focuses optimization on difficult pixels Alpha and gamma are sensitive to task and implementation Hard-example behavior and calibration
Tversky Controls the relative cost of false negatives and false positives Mis-set asymmetry can favor one error excessively Recall or precision according to deployment cost
Focal Tversky Strong candidate for very sparse foregrounds More hyperparameters and no guarantee of cross-dataset superiority Robustness across scenes and thresholds
Compound loss Combines pixel and overlap supervision Component scaling can make optimization difficult Each component and the total validation score

Segmentation Models PyTorch documents Dice and Focal implementations and exposes focal-loss parameters including alpha and gamma. Check the installed version’s documentation for the expected tensor shape, activation setting and parameter semantics before transferring a configuration between projects.

Use sampling to change exposure, not to hide the problem

Sampling and loss design address different parts of imbalance. A loss changes how an observed pixel contributes to the gradient; sampling changes which images or patches the model sees and how often.

Oversampling crack-containing images or patches

Oversampling raises the frequency of minority examples. It is useful when a training epoch contains too few informative crack pixels, but repeating the same examples does not add diversity. It can amplify annotation noise, encourage memorization of a particular texture and make the training distribution unlike deployment.

Undersampling background-heavy data

Removing some background-heavy images or patches can reduce the dominance of easy negatives. Excessive undersampling discards global context such as clean concrete, joints, edges and surface patterns that are needed to reject crack-like backgrounds.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Filtering empty patches

Keeping fewer completely empty patches is often safer than deleting all negative examples. Set a documented retention rule, preserve a representative sample of empty and near-empty scenes, and check that validation retains the original scene distribution. A patch policy that removes every negative patch can produce a model that marks normal concrete as damaged.

Sampling choice Benefit Failure mode Safeguard
Oversample crack patches More minority exposure per epoch Repeated examples, overfitting and amplified label noise Use augmentation and track unique source images
Undersample background patches Less dominance by easy negatives Loss of scene-level context and hard negatives Retain diverse backgrounds and inspect deployment-like negatives
Remove only some empty patches Shorter, more informative epochs Shifted prevalence if the filter is too aggressive Measure prevalence before and after filtering
No sampling change Closest to deployment distribution Very few crack pixels may reach the optimizer Use a foreground-aware loss or larger batches where feasible

Tune the probability threshold on validation images

A segmentation network usually outputs a crack probability for each pixel. Converting that probability into a binary mask requires a threshold. A threshold of 0.5 is only a convention; it is not automatically optimal for thin concrete cracks.

In Nguyen and Thai’s comparison, BCE performed best around thresholds from 0.25 to 0.45 on the mildly imbalanced datasets they examined. Dice-based losses were described as less sensitive to threshold changes, with 0.5 suggested in that context. Treat these as study-specific observations, not universal defaults.

  1. Train the model without looking at the test set.
  2. Generate probability maps for every validation image.
  3. Sweep a documented threshold range and calculate precision, recall, Dice and IoU at each point.
  4. Choose the threshold using the deployment objective, such as a minimum recall for safety-critical screening or a precision target for an expensive manual review queue.
  5. Freeze that threshold before evaluating the held-out test set.
  6. Inspect overlays at the chosen threshold and at nearby values to detect brittle behavior.

Do not select a threshold from a single visually attractive image. A threshold that recovers one faint crack may create hundreds of false-positive regions on another surface.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Evaluate more than pixel accuracy

Report metrics that expose both missed cracks and false alarms. Pixel accuracy is useful as a diagnostic but can be dominated by background.

Metric What it answers Why it matters here
Precision Of predicted crack pixels, how many are correct? Reveals false alarms on texture, joints and stains
Recall (sensitivity) How many annotated crack pixels were recovered? Reveals missed faint, thin or fragmented cracks
Dice How well do prediction and annotation overlap? Balances missed and extra pixels in one overlap score
IoU (Jaccard) What fraction of the union is correctly overlapped? Penalizes mismatched regions and supports comparison with prior work
Pixel accuracy What fraction of all pixels is correct? Useful only alongside foreground-sensitive metrics under severe imbalance

Report aggregate scores and per-image or per-site distributions. Include representative overlays for true positives, false positives and false negatives. Pay particular attention to crack-like texture that the model repeatedly labels as damage and to faint or hairline cracks that disappear from the prediction.

An end-to-end workflow that isolates the causes

  1. Define the operational error. Decide whether missed cracks or unnecessary reviews are more costly. This determines how you interpret precision and recall and how you will select a threshold.
  2. Audit the annotations. Check line thickness, disconnected segments, uncertain regions and whether shadows or joints are labeled consistently. Loss tuning cannot correct systematic label ambiguity.
  3. Split by source. Keep related images from the same structure, site or visit in one split where leakage is possible.
  4. Measure prevalence. Calculate total and per-image crack-pixel prevalence on the training split, then repeat the report for validation and test to expose distribution shift.
  5. Extract patches after splitting. Record source identifiers and retain enough empty and background-rich patches to preserve context.
  6. Train a BCE baseline. Keep architecture, augmentations, optimizer and schedule fixed so that later changes can be attributed to the loss or sampler.
  7. Add a Dice or Jaccard baseline. Compare overlap, precision and recall rather than choosing by accuracy alone.
  8. Test one intervention at a time. Evaluate weighted BCE, Focal or a Tversky-family loss separately. Change sampling in a separate experiment before combining it with a loss change.
  9. Sweep thresholds on validation data. Store the selected threshold and the metric used to select it.
  10. Stress-test by scene. Review results on smooth concrete, rough aggregate, shadows, joints, stains, wide cracks and hairline cracks.
  11. Lock the configuration. Freeze preprocessing, loss, sampling policy and threshold before the held-out evaluation.
  12. Document deployment behavior. Save probability maps, binary masks, metrics and representative overlays so a later audit can distinguish model errors from threshold or annotation effects.

Troubleshoot common failure patterns

Observed symptom Likely cause Corrective experiment
Nearly every pixel is background Foreground contribution is overwhelmed or crack examples are too rare Verify prevalence, try a moderate crack weight or focal/overlap loss, and inspect whether empty patches dominate each epoch
Many broad false-positive regions Foreground weighting is too aggressive, negatives were undersampled, or the threshold is too low Restore hard background examples, compare a higher validation threshold and inspect precision by scene
Thin cracks are broken into gaps Downsampling, annotation width or a recall-insensitive objective may be suppressing weak pixels Review image and mask resolution, compare recall-oriented loss settings and inspect probability maps before thresholding
Training improves but validation collapses Oversampling repeats a small set of crack patches or the model memorizes site-specific texture Track unique source images, reduce repetition, strengthen scene-diverse augmentation and recheck the split
Scores change sharply with small threshold changes Probabilities are poorly separated or calibration differs across scenes Plot validation precision–recall curves, select a threshold from the deployment objective and test stability on separate sites
High aggregate score but obvious missed cracks Background dominates the metric or a few large images mask failures on thin cracks Report per-image recall, inspect false negatives and add crack-width or scene-stratified analyses

How to decide between recall and false-positive control

For an automated screening system that sends candidates to an inspector, favoring recall may be sensible because a human can reject extra candidates. For a system that triggers costly access, traffic control or repair work, false positives may carry a larger operational cost. Neither choice is encoded solely by the loss name.

Use the same validation set to compare candidate configurations at their selected thresholds. A useful decision table contains crack prevalence, precision, recall, Dice, IoU, threshold sensitivity and the number of images with conspicuous false alarms. If two losses have similar overlap, choose the one whose errors are safer and whose behavior is more stable across surfaces.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Limits of published comparisons

The four-dataset comparison by Nguyen and Thai is directly relevant to concrete crack segmentation, but its rankings are bounded by the datasets, model setup and evaluation criteria used in that paper. Annotation policy, camera viewpoint, lighting, resolution, augmentation and deployment prevalence can change the result. A loss that leads on GAPs384 may not lead on a site-specific inspection collection.

DeepCrack includes both concrete and asphalt pavement imagery, so its performance should not be interpreted as a guarantee for every structural-concrete application. Likewise, the reported image counts and imbalance ratios are characteristics of the named datasets, not a specification for a new project.

A practical selection rule

  • Mild imbalance: start with BCE and Dice or Jaccard, then tune the threshold on validation images.
  • Severe imbalance: compare weighted BCE, Focal, Dice-based and compound losses, and include Focal Tversky as a candidate rather than assuming it will win.
  • Very few unique crack examples: treat oversampling cautiously; preserve scene diversity and inspect for memorization.
  • High cost of missed cracks: prioritize recall during threshold selection, then quantify the resulting false-positive workload.
  • High cost of false alarms: retain hard background examples and select a threshold that meets a precision or review-rate requirement.
  • Uncertain outcome: run a small controlled comparison with identical splits, augmentations and training budgets, and report the complete precision–recall–Dice–IoU picture.

The reliable solution is not a single “best” loss. It is a controlled pipeline in which prevalence measurement, source-level splitting, loss choice, sampling, thresholding and error inspection are tested separately and then evaluated together on imagery that matches deployment.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Class ImbalanceComputer Visionconcrete crack segmentationDeep LearningDice lossFocal losssemantic segmentation

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.