CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 2 · Lesson 27/48

    Log scale transformation: when to use log, log1p and their inverses

    Identify scenarios where log scale transformation is appropriate

    16 min read
    2.11% of exam
    10 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Recognise features and targets that call for a log transform: right-skewed values, values spanning orders of magnitude, multiplicative relationships, and spread that grows with the level
    • Explain why scaling, binning, one-hot encoding or dropping rows do not fix the problem a log transform solves
    • Choose log1p or a shift when a column contains zeros or negatives, knowing that Spark's log functions return NULL at or below zero
    • Pair each forward transform with its inverse (log with exp, log1p with expm1) when you choose it

    Key concept

    Log scale transformation — Replacing a positive value with its logarithm. Equal ratios become equal steps, so a long right tail is pulled in and multiplicative patterns become additive ones that a linear model can fit.

    1.Right-skewed features that span orders of magnitude

    A log transform is the right tool when a numeric column has a long right tail. In that shape most values sit in a narrow band and a few run many times larger. House prices are the usual example: most homes sell under $500,000, while a handful of luxury properties sell above $5,000,000. On the raw scale those few rows stretch the axis by a factor of ten, and a linear regression fitted to them gives the tail far more pull than its share of the data.

    The logarithm counts orders of magnitude instead of units. In base 10, the values 1, 10 and 100 become 0, 1 and 2, so each tenfold jump turns into one step of the same size. Applied to prices, $500,000 maps to about 5.7 and $5,000,000 to about 6.7. The luxury tail moves from ten times the typical value to one unit above it, and the distribution looks far more symmetric.

    log10 turns each tenfold increase into a step of exactly 1python
    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([(1,), (10,), (100,)], ["value"])
    df.select("*", dbf.log10(df.value)).show()
    
    +-----+------------+
    |value|LOG10(value)|
    +-----+------------+
    |    1|         0.0|
    |   10|         1.0|
    |  100|         2.0|
    +-----+------------+

    Linear models are where this pays off most. Many modelling setups work best when features are roughly normal, and a log transform maps a lognormal shape (the typical shape of prices, incomes and durations) close to a normal one. Measure the skew before you decide. skewness(col) in pyspark.sql.functions returns one number per column, and a large positive value means a long right tail. A histogram of the column, covered in visualizations for continuous features, shows the same thing. Check again after transforming, because a transform that suits one distribution can do little for another.

    The other options tempt people because each changes the column in some way, but none changes its shape. Min-max scaling and standardization are linear: they shift and stretch every value by the same amount, so the luxury homes are still far out in the tail, just with smaller numbers. Removing them as outliers (standard-deviation or IQR filtering) throws away real sales and leaves the remaining prices still skewed. One-hot encoding price buckets (where one-hot encoding fits) destroys the ordered numeric scale the regression needs.

    What each preparation does to a long right tail in a price feature
    PreparationEffect on the tailVerdict for a skewed linear-regression feature
    log10 or lnCompresses it: each tenfold gap becomes one unitAppropriate
    MinMaxScaler / StandardScalerRange or centre changes, shape stays skewedDoes not address skew
    Drop high values as outliersRemoves real rows, skew in the rest remainsLoses data
    One-hot encode price bucketsReplaces the continuous scale with categoriesLoses the numeric relationship

    Checkpoint 1 of 7· Fill the gap

    A price-like column runs from 1 to 100, and you want every tenfold increase to become a step of exactly 1, so that the values 1, 10 and 100 come out as 0.0, 1.0 and 2.0. Which function completes this sample?

    from pyspark.sql import functions as dbf
    df = spark.createDataFrame([(1,), (10,), (100,)], ["value"])
    df.select("*", dbf. ? (df.value)).show()

    Checkpoint 2 of 7· Exam question

    A data scientist is preparing a price feature for a linear regression model predicting home values. The feature is heavily right-skewed, with most homes priced under $500,000 but a small number of luxury properties priced above $5,000,000, stretching the tail. Which transformation is the most appropriate way to prepare this feature before training the model?

    Sources123

    2.Multiplicative growth and spread that grows with the level

    A logarithm turns ratios into differences. Each doubling of the input adds exactly 1 to its base-2 log, so a series that grows by a constant factor becomes a series that grows by a constant amount. On the log scale that is a straight line.

    Doubling the input adds a constant 1 on the log2 scalepython
    from pyspark.sql import functions as dbf
    df = spark.sql("SELECT * FROM VALUES (1), (2), (4) AS t(value)")
    df.select("*", dbf.log(2.0, df.value)).show()
    
    +-----+---------------+
    |value|LOG(2.0, value)|
    +-----+---------------+
    |    1|            0.0|
    |    2|            1.0|
    |    4|            2.0|
    +-----+---------------+

    This is what to look for in a relationship between two variables. Suppose weekly marketing spend and website signups move together in percentages: a given relative rise in spend brings a relative rise in signups, not a fixed number of extra signups. On raw axes the scatter curves, and a straight line fits it badly. Log-transform both columns and the percentage relationship becomes a linear one, which linear regression fits directly. Standardizing both columns leaves the curve exactly as it was, only relabelled. Binning spend into quartiles swaps the smooth trend for step changes. Imputing missing values (median imputation) fills gaps and does nothing to the curve.

    Spread that grows with the level is the same pattern showing up in the noise. When small accounts vary by a few dollars and large accounts by thousands, the scatter fans out as values rise. Least-squares linear regression assumes residuals of constant variance, and a fan shape breaks that. Taking logs measures every deviation relative to its level, so the fan narrows to a band. That is the variance-stabilizing effect log and power transforms are used for.

    Checkpoint 3 of 7· Check yourself

    You fit a least-squares linear regression on account revenue. In the residual plot, small accounts miss by a few dollars and large accounts by thousands, so the points fan out as revenue rises. Which preparation addresses this?

    Checkpoint 4 of 7· Exam question

    An ML team is modeling the relationship between weekly marketing spend and website signups. Exploratory plots show that signups grow multiplicatively as spend increases: each additional dollar of spend produces a percentage increase in signups rather than a fixed increase. Which technique best addresses this relationship before fitting a linear regression model?

    Sources453

    3.Zeros and negatives: log1p or a shift

    The logarithm is defined only for positive numbers, and Spark handles the rest without warning. log, ln, log10 and log2 all return NULL for zero and for negative inputs. Nothing fails, so the first sign of a problem is usually a model trained on fewer rows than expected, or an imputer filling in values that were never missing.

    Zero and negative inputs to log come back as NULLpython
    from pyspark.sql import functions as dbf
    df = spark.sql("SELECT * FROM VALUES (1), (2), (0), (-1), (NULL) AS t(value)")
    df.select("*", dbf.log(3.0, df.value)).show()
    
    +-----+------------------+
    |value|   LOG(3.0, value)|
    +-----+------------------+
    |    1|               0.0|
    |    2|0.6309297535714...|
    |    0|              NULL|
    |   -1|              NULL|
    | NULL|              NULL|
    +-----+------------------+

    log1p is the standard fix for non-negative data that includes zeros. It computes the natural log of the value plus one, so 0 maps to 0.0 and large values are compressed almost exactly as ln would compress them. Resolution times are a good fit: the zero-minute auto-closed tickets stay in the data at 0, and the multi-day tail is still pulled in. Dropping the zero rows so that plain ln runs would throw away a real and common outcome, and the model would never learn that tickets can close instantly.

    log1p as a pipeline step: the zero input becomes 0.0 rather than undefinedpython
    >>> import numpy as np
    >>> from sklearn.preprocessing import FunctionTransformer
    >>> transformer = FunctionTransformer(np.log1p, validate=True)
    >>> X = np.array([[0, 1], [2, 3]])
    >>> # Since FunctionTransformer is no-op during fit, we can call transform directly
    >>> transformer.transform(X)
    array([[0.        , 0.69314718],
           [1.09861229, 1.38629436]])

    Negative values need a shift before any log. Add a constant big enough to make the smallest value positive, then take the log, and record that constant, because inverting the transform later means subtracting it again. Box-Cox, a related power transform, has the same strictly-positive requirement.

    Checkpoint 5 of 7· Check yourself

    Daily purchase counts per customer are heavily right-skewed, and about a third of the rows are legitimately 0. You want to compress the tail in Spark without losing any observations. Which approach fits?

    Checkpoint 6 of 7· Exam question

    A dataset of customer support ticket resolution times includes many tickets resolved in under an hour, a long tail of tickets that took several days, and a subset of tickets with a resolution time of exactly zero minutes because they were auto-closed. The team wants to log-transform resolution time to reduce skew before training a model. Which approach correctly handles this feature?

    Sources673

    4.Choosing the inverse when you choose the transform

    Every forward transform you apply to a target commits you to a specific inverse. A model trained on log-transformed values predicts on the log scale, and those predictions have to be converted back before anyone reads them; that step is covered in exponentiating log-transformed predictions before metrics and interpretation. What belongs to the transform decision is which inverse: exp undoes ln, and expm1, which computes the exponential minus one, undoes log1p. Applying exp to a log1p prediction makes every prediction one unit too high. That is easy to miss on prices in the hundreds of thousands and badly wrong on counts near zero.

    Forward transforms and the inverse each one commits you to
    ForwardUse whenInverse
    ln / logAll values strictly positiveexp
    log1pValues non-negative, zeros presentexpm1
    Shift by a constant, then logNegative values presentexp, then subtract the same constant
    expm1 maps 0 back to 0.0, the exact inverse of log1ppython
    from pyspark.sql import functions as dbf
    df = spark.sql("SELECT id AS value FROM RANGE(5)")
    df.select("*", dbf.expm1(df.value)).show()
    
    +-----+------------------+
    |value|      EXPM1(value)|
    +-----+------------------+
    |    0|               0.0|
    |    1| 1.718281828459...|
    |    2|  6.38905609893...|
    |    3|19.085536923187...|
    |    4|53.598150033144...|
    +-----+------------------+

    Some tooling makes you name both directions at once. scikit-learn's TransformedTargetRegressor takes a func and an inverse_func, transforms the target before fitting, and maps predictions back through the inverse. By default it checks at fit time that the two functions actually invert each other. In scikit-learn's worked example, a LinearRegression is fitted on a synthetic target (2,000 rows, 8 features, the target built by exponentiating) with np.log as func and np.exp as inverse_func, and it scores an R² of 0.67 on held-out data. Replace the inverse with a function that returns its input unchanged, bypass the check with check_inverse=False, and the same setup scores −3.02. Training is unchanged; only the mapping back to the original scale is wrong.

    Declaring the forward and inverse transforms together for a regression targetpython
    >>> def func(x):
    ...     return np.log(x)
    >>> def inverse_func(x):
    ...     return np.exp(x)

    Checkpoint 7 of 7· Match them up

    Each regression target below was transformed before training. Match each forward transform to the back-transform that returns predictions to the original scale.

    Tap a term, then the definition that fits it.

    Sources8910

    Sources

    (10)

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

    1. 3.
      “In many modeling scenarios, normality of the features in a dataset is desirable.”
      ↩︎ Right-skewed features that span orders of magnitude
      “map samples drawn from a lognormal distribution to a normal distribution”
      ↩︎ Right-skewed features that span orders of magnitude
      “This highlights the importance of visualizing the data before and after transformation.”
      ↩︎ Right-skewed features that span orders of magnitude
      “In practice we often ignore the shape of the distribution and just transform the data to center it”
      ↩︎ Right-skewed features that span orders of magnitude
      “in order to stabilize variance and minimize skewness”
      ↩︎ Multiplicative growth and spread that grows with the level
      “Box-Cox can only be applied to strictly positive data.”
      ↩︎ Zeros and negatives: log1p or a shift
      “in order to stabilize variance and minimize skewness”
      ↩︎ Key concept
      “In practice we often ignore the shape of the distribution and just transform the data to center it”
      ↩︎ Exam trap 1
    2. 4.
      “If there is only one argument, then this takes the natural logarithm of the argument.”
      ↩︎ Multiplicative growth and spread that grows with the level
    3. 6.
      “If base or expr are less than or equal to 0 the result is NULL.”
      ↩︎ Zeros and negatives: log1p or a shift
      “If base or expr are less than or equal to 0 the result is NULL.”
      ↩︎ Exam trap 2
    4. 7.
      “Computes the natural logarithm of the given value plus one.”
      ↩︎ Zeros and negatives: log1p or a shift
      “Computes the natural logarithm of the given value plus one.”
      ↩︎ Exam trap 3
      “Computes the natural logarithm of the given value plus one.”
      ↩︎ Checkpoint
    5. 8.
      “Computes the exponential of the given value minus one.”
      ↩︎ Choosing the inverse when you choose the transform
      “Computes the exponential of the given value minus one.”
      ↩︎ Exam trap 4
    6. 10.
      “The predictions are mapped back to the original space via an inverse transform.”
      ↩︎ Choosing the inverse when you choose the transform
      “By default, the provided functions are checked at each fit to be the inverse of each other.”
      ↩︎ Choosing the inverse when you choose the transform
      “it is possible to bypass this checking by setting check_inverse to False”
      ↩︎ Choosing the inverse when you choose the transform

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