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.
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.
| Preparation | Effect on the tail | Verdict for a skewed linear-regression feature |
|---|---|---|
| log10 or ln | Compresses it: each tenfold gap becomes one unit | Appropriate |
| MinMaxScaler / StandardScaler | Range or centre changes, shape stays skewed | Does not address skew |
| Drop high values as outliers | Removes real rows, skew in the rest remains | Loses data |
| One-hot encode price buckets | Replaces the continuous scale with categories | Loses 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()Base-10 logarithms count orders of magnitude, so 1, 10 and 100 map to 0, 1 and 2, and each tenfold jump becomes one equal step. log2 would give about 3.32 for 10, ln about 2.30, and log1p takes the log of value plus one, so 1 would not map to 0.
Source: docs.databricks.comCheckpoint 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?
Correct answer: A — Apply a log transformation to the price feature, which compresses the extreme high values and pulls the distribution closer to a normal shape that linear regression assumes.
- A. A log transformation compresses large values proportionally more than small ones, which pulls in the long right tail created by the luxury properties and moves the feature toward the roughly normal shape linear regression works best with.
- B. Min-max scaling only rescales the numeric range of a feature; it applies the same linear stretch to every value, so the right-skewed shape of the price distribution, including the stretched-out tail, remains exactly as it was before scaling.
- C. Converting a continuous price feature into categorical buckets throws away the ordered numeric relationship between prices, which a linear model relies on to estimate a continuous coefficient for the feature.
- D. Deleting the luxury properties removes legitimate high-value homes from the training data rather than reshaping the distribution, which biases the model against ever predicting high prices correctly.
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.
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?
Spread that grows with the level is a multiplicative pattern. Taking logs measures each deviation relative to its level, which narrows the fan to a band of constant variance. Standardizing, binning and imputing all leave the multiplicative spread in place.
“in order to stabilize variance and minimize skewness”Source: scikit-learn.org
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?
Correct answer: A — Log-transform both the spend and signup features, which converts the multiplicative growth pattern into an approximately linear relationship a model can fit.
- A. When a percentage change in one variable corresponds to a percentage change in another, taking logs of both variables turns that multiplicative relationship into an additive, approximately linear one that a linear model can capture directly.
- B. Standardization centers and rescales a feature using its mean and standard deviation, but it is a linear operation, so it cannot turn a multiplicative, percentage-based growth pattern into a linear one.
- C. Converting spend into quartile bins throws away the continuous, fine-grained growth pattern the model needs to learn and instead forces the relationship into a small number of discrete steps.
- D. Median imputation only fills in missing spend values; it has no effect on the shape of the relationship between spend and signups for the values that are already present.
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.
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.
>>> 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?
log1p takes the natural log of the value plus one, so a 0 count becomes 0.0 and stays in the data while the tail is still pulled in. Plain ln returns NULL at zero, dropping the zeros throws away real outcomes, and standardizing creates negative values that ln also turns into NULL.
“Computes the natural logarithm of the given value plus one.”Source: docs.databricks.com
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?
Correct answer: A — Apply log1p (log of one plus the value) to resolution time, which is defined at zero and still compresses the long right tail of multi-day tickets.
- A. The
log1pfunction adds one before taking the log, which makes it well-defined at zero while still compressing the large values in the long tail, so the auto-closed tickets do not need to be dropped or altered. - B. The natural logarithm is undefined at zero, so applying it directly would produce an error or an invalid result for every auto-closed ticket rather than leaving those rows unchanged.
- C. A square root transformation is defined at zero, but it compresses large values far less aggressively than a logarithm, so it does not reduce a heavy right tail as strongly as the log-based approach.
- D. Dropping the zero-minute tickets removes a real and fairly common outcome from the training data just to make a direct logarithm computable, losing information the model could otherwise learn from.
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 | Use when | Inverse |
|---|---|---|
| ln / log | All values strictly positive | exp |
| log1p | Values non-negative, zeros present | expm1 |
| Shift by a constant, then log | Negative values present | exp, then subtract the same constant |
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.
>>> def func(x):
... return np.log(x)
>>> def inverse_func(x):
... return np.exp(x)The model's log-scale prediction is about 0.0; exp(0.0) is 1, so the back-transformed prediction reads 1 sale instead of 0. expm1(0.0) returns 0.0, which is correct.
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.
An inverse has to undo every step of its forward transform, in reverse order. log1p takes the log of the value plus one, so its inverse is expm1, which subtracts the one again. A shifted log needs exp followed by subtracting the shift. Using plain exp after log1p makes every prediction one unit too high.
“Computes the natural logarithm of the given value plus one.”Source: docs.databricks.com
Sources
(10)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Computes the logarithm of the given value in Base 10.”
↩︎ Right-skewed features that span orders of magnitude - 2.
“Returns the skewness of the values in a group.”
↩︎ Right-skewed features that span orders of magnitude - 3.https://scikit-learn.org/stable/modules/preprocessing.htmlSecondary source
“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 - 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 - 5.https://scikit-learn.org/stable/modules/model_evaluation.htmlSecondary source
“that their variance should be constant (homoschedasticity)”
↩︎ Multiplicative growth and spread that grows with the level - 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 - 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 - 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 - 9.
“Returns exp(expr) - 1.”
↩︎ Choosing the inverse when you choose the transform - 10.https://scikit-learn.org/stable/modules/compose.htmlSecondary source
“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