CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 3 · Lesson 29/48

    Class imbalance: undersampling, SMOTE and class weights

    Identify methods to mitigate data imbalance in training data

    15 min read
    2.07% of exam
    3 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Explain why a heavily imbalanced label distorts what a classifier learns
    • Undersample a majority class with sampleBy without losing the minority class
    • Tell random oversampling and SMOTE apart, and name the risk each one carries
    • Choose class weights when rows must not be dropped or duplicated
    • Keep validation and test data at the real class distribution after rebalancing training data

    Key concept

    Rebalance training data only — Undersampling, oversampling, SMOTE and class weights change what the model learns from, so they apply only to the training split. Validation and test data keep the real class mix, because that is the mix the model will meet in production.

    1.Why an imbalanced label misleads a classifier

    When one class is rare, a classifier can do well on its loss by ignoring that class. Take a fraud dataset where 2% of transactions are fraudulent. A model that labels every transaction legitimate is 98% accurate and catches no fraud at all. The loss gives the same weight to every row, so 98 legitimate rows pull the decision boundary toward the majority for every 2 fraud rows, and the model learns very little about what fraud looks like.

    There are two ways to fix this during training. You can change the rows: drop majority rows (undersampling) or add minority rows, either as copies (random oversampling) or as synthetic points (SMOTE). Or you can change the weights: keep every row and make minority-class errors cost more in the loss (class weights). Databricks AutoML combines the two. When it detects imbalance, it undersamples the majority class and then adds class weights. Every method has a cost, and exam questions usually turn on that cost. Choosing a metric that exposes the problem is a separate topic, covered in classification metrics such as F1 and ROC AUC.

    Checkpoint 1 of 8· Check yourself

    A fraud model trained on data with 2% fraudulent transactions reaches 98% accuracy but flags no fraud. Which change corrects the imbalance during training?

    Sources1

    2.Undersampling the majority class with sampleBy

    In Spark, DataFrame.sampleBy gives you stratified undersampling. You pass the label column and a dictionary that maps each label value to the fraction of its rows to keep. To undersample, give the majority label a small fraction and the minority label 1.0. It samples without replacement, so a row can never appear twice. That means sampleBy can only shrink a class. It cannot oversample.

    sampleBy keeps a per-key fraction of rows. Key 2 is not in the fractions dict, so it is missing from the output entirely.python
    from pyspark.sql import functions as sf
    dataset = spark.range(0, 100, 1, 5).select((sf.col("id") % 3).alias("key"))
    sampled = dataset.sampleBy("key", fractions={0: 0.1, 1: 0.2}, seed=0)
    sampled.groupBy("key").count().orderBy("key").show()
    # +---+-----+
    # |key|count|
    # +---+-----+
    # |  0|    4|
    # |  1|    9|
    # +---+-----+

    The fractions are sampling probabilities, not exact counts. Key 0 had 34 rows and a fraction of 0.1, and 4 rows came back. Expect roughly the requested share, not exactly that number.

    Undersampling's cost is the information it throws away. Suppose you cut 500,000 majority rows down to match 3,000 minority rows. The model now trains on 6,000 rows, and more than 99% of the majority class's variety is gone. It may draw a poor boundary for majority cases it never saw, so it generalizes worse on that class. That is the main downside. It does not cause overfitting to repeated rows, because nothing is repeated. It does not create out-of-range feature values, because nothing is synthesized. Undersampling works best when the majority class is huge and redundant, or when training time matters more than squeezing out every bit of signal.

    Checkpoint 2 of 8· Fill the gap

    This sample keeps 10% of key-0 rows and 20% of key-1 rows, and drops key 2. Which DataFrame method fills the blank?

    from pyspark.sql import functions as sf
    dataset = spark.range(0, 100, 1, 5).select((sf.col("id") % 3).alias("key"))
    sampled = dataset. ? ("key", fractions={0: 0.1, 1: 0.2}, seed=0)
    sampled.groupBy("key").count().orderBy("key").show()
    # +---+-----+
    # |key|count|
    # +---+-----+
    # |  0|    4|
    # |  1|    9|
    # +---+-----+

    Checkpoint 3 of 8· Exam question

    An engineer randomly undersamples the majority class of a 500,000-row imbalanced dataset down to match a 3,000-row minority class before training a classifier. What is the most likely downside of this specific approach?

    Sources2

    3.Oversampling: duplicated rows versus SMOTE's synthetic rows

    Oversampling grows the minority class and keeps every majority row. The simplest form is random oversampling, which copies existing minority rows until the classes are closer in size. In Spark you can do this with df.sample(withReplacement=True, fraction=...) on the minority rows, using a fraction above 1, and then union the result back with the majority rows. No information is lost. The risk is that the model sees the same few minority rows many times. It can memorize those exact rows and overfit to them instead of learning the general pattern of the class.

    SMOTE (Synthetic Minority Over-sampling Technique) creates new points instead of copying. It takes a minority row, picks one of its nearest neighbors from the minority class, and creates a new row at a random point on the line between the two. Each new row is an interpolation that has never existed before, so the minority region of feature space fills in rather than piling up on the same points. SMOTE does not copy rows verbatim, does not remove majority rows near the boundary, and does not touch the loss function. Those are random oversampling, an undersampling cleanup method and class weighting. SMOTE has its own weakness. Interpolated points can land where real data never occurs, for example between two clusters, or as a fractional value in a feature that should be a whole number or a category.

    Every oversampling method has to run after the train/test split. If you oversample first, copies or close interpolations of a training row can end up in the test set. The model is then scored on rows it has effectively already seen, and the score is too high. Split first, then rebalance only the training portion.

    Checkpoint 4 of 8· Check yourself

    You run SMOTE on the full labeled dataset and only then split it into train and test sets. What is the most likely effect on the reported test scores?

    Checkpoint 5 of 8· Exam question

    A team building a churn model on Databricks decides to apply SMOTE to the minority (churned) class before training. A reviewer asks how SMOTE actually generates its additional training rows. Which description is accurate?

    Sources1

    4.Class weights: rebalancing without touching the rows

    Class weights change how much each row counts in the loss, not which rows exist. A minority row with weight 49 adds 49 times as much loss when it is misclassified as a majority row with weight 1. The optimizer then has as much incentive to get fraud right as legitimate traffic. No rows are dropped and none are duplicated, so this is the method to pick when a requirement rules out both. In scikit-learn, LogisticRegression(class_weight='balanced') sets each class's weight inversely proportional to its frequency. In Spark ML, many classifiers, LogisticRegression among them, accept a weightCol that names a numeric column of per-row weights, which you compute from the class counts.

    Databricks AutoML's classification API exposes the same idea through sample_weight_col. Weights must be the same for every row of a class, and a higher-weighted class pulls harder on the learning algorithm. Weighting keeps all the data, but it does not add any new information about the minority class. With only 50 fraud rows, a weight of 1,000 can make the model swing hard on those 50 examples. That is the weighting equivalent of overfitting to duplicates.

    Weights can also undo a distortion that resampling introduces. In the AutoML worked example, 95 class-A and 5 class-B rows become 70 A and 5 B after A is downsampled by a ratio of 0.736. Class A is then given weight 1/0.736 = 1.358 so that the model's predicted probabilities still match the real class mix. Here the majority class is the one upweighted, and the purpose is calibration, not emphasis. class_weight='balanced' works in the opposite direction and upweights the minority class so the model pays attention to it.

    Three ways to rebalance training data, compared by what they change and what they risk
    MethodEffect on training rowsMain riskWins when
    Random undersampling (sampleBy on the label)Drops majority rowsLoses majority-class information, so it generalizes worse on that classThe majority class is huge and redundant, or training cost matters
    Random oversampling (duplicate minority rows)Adds exact copies of minority rowsOverfits to the repeated minority rowsData is small and no rows can be thrown away
    Class weights (sample_weight_col and similar)None: every row kept as isVery large weights make training unstable on few examplesRows must not be dropped or duplicated

    Checkpoint 6 of 8· Check yourself

    In the AutoML worked example, class A (95 rows) is downsampled to 70 rows. Class B keeps its 5 rows. AutoML then gives class A a weight of 1/0.736 = 1.358, and class B keeps a weight of 1. Why does it upweight the majority class?

    Checkpoint 7 of 8· Exam question

    A data scientist on Databricks is training a LogisticRegression model on a fraud dataset where only 2% of transactions are fraudulent. The team wants to correct for this imbalance during training itself, without discarding any rows and without duplicating any existing rows. Which approach best satisfies these constraints?

    Sources31

    5.Evaluate on the real class distribution

    Resampling is a training technique, so the data you measure on must keep its natural class mix. If you balance the test set to 50/50 as well, the precision you measure would only hold if fraud were half of all traffic. When the model goes live on 2% fraud, its false positives outnumber its true positives by a margin the test never showed. Leave validation and test data unbalanced and judge the model on the distribution it will actually face.

    Stratify the split so that a rare class shows up in every partition. A plain random split of a dataset with 1% positives can, by chance, put very few positives into a small validation set, and the metrics computed on it become noise. A stratified split keeps the class proportions the same in train, validation and test. Then rebalance only the training partition, and score with a metric that reflects the minority class. Picking that metric is covered in choosing a metric for the objective.

    Checkpoint 8 of 8· Check yourself

    Production traffic is 2% fraud, and the team trains on a 50/50 undersampled set. Which evaluation plan gives precision and recall figures that will still hold once the model goes live?

    Sources1

    Sources

    (3)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “it tries to reduce the imbalance of the training dataset by downsampling the major class(es) and adding class weights”
      ↩︎ Why an imbalanced label misleads a classifier
      “AutoML only balances the training dataset and does not balance the test and validation datasets.”
      ↩︎ Oversampling: duplicated rows versus SMOTE's synthetic rows
      “AutoML scales up the class weight for class A by the ratio 1/0.736, or 1.358”
      ↩︎ Class weights: rebalancing without touching the rows
      “Doing so ensures that the model performance is always evaluated on the non-enriched dataset with the true input class distribution.”
      ↩︎ Evaluate on the real class distribution
      “For classification, a stratified random split ensures that each class is adequately represented in the training, validation, and test sets.”
      ↩︎ Evaluate on the real class distribution
      “AutoML only balances the training dataset and does not balance the test and validation datasets.”
      ↩︎ Key concept
      “AutoML only balances the training dataset and does not balance the test and validation datasets.”
      ↩︎ Exam trap 2
      “Doing so ensures that the model performance is always evaluated on the non-enriched dataset with the true input class distribution.”
      ↩︎ Exam trap 4
      “it tries to reduce the imbalance of the training dataset by downsampling the major class(es) and adding class weights.”
      ↩︎ Checkpoint
      “To ensure that the final model is correctly calibrated and the probability distribution of the model output is the same as that of the input”
      ↩︎ Checkpoint
      “AutoML only balances the training dataset and does not balance the test and validation datasets.”
      ↩︎ Checkpoint
    2. 2.
      “Returns a stratified sample without replacement based on the fraction given on each stratum.”
      ↩︎ Undersampling the majority class with sampleBy
      “If a stratum is not specified, we treat its fraction as zero.”
      ↩︎ Undersampling the majority class with sampleBy
      “If a stratum is not specified, we treat its fraction as zero.”
      ↩︎ Exam trap 1
    3. 3.
      “Classes with higher sample weights are considered more important, and have a greater influence on the learning algorithm.”
      ↩︎ Class weights: rebalancing without touching the rows
      “Each sample within a class must have the same sample weight”
      ↩︎ Class weights: rebalancing without touching the rows
      “Classes with higher sample weights are considered more important, and have a greater influence on the learning algorithm.”
      ↩︎ Exam trap 3

    Ready to test yourself?

    Practise the 7 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.