Cert EspressoLearn. Practise. Find your flow.

A LITTLE FOCUS.
A BIG NEXT STEP.

Your pace. Your space.
Databricks · Databricks Machine Learning Associate

One-hot encoding and log transforms

Databricks Machine Learning Associate · Lesson 10 of 19 · 1:17:15

YouTube loads only after you press play. This chapter opens at its timestamp in the full course. Watch on YouTube ↗

Learning with these videos? Subscribe for new courses and exam-style questions.

In this lesson

Prepare for the Databricks Certified Machine Learning Associate exam. In this lesson: the StringIndexer, the OneHotEncoder and its sparse vectors, when to one-hot encode and when tree models do not need it, and log transforms for skewed features. Includes three original practice questions.

Study notes

The text of this lesson, to read at your own pace. Information as of November 2026.

Strings and long tails

The demand model of Juniper Rides gets three awkward features: the vehicle type, stored as text, the station ID, with two thousand distinct values, and the daily revenue per station, where a few busy stations earn a hundred times more than the rest. A model cannot use text directly, and the long tail of revenue would dominate a linear model. This lesson covers how to index and one-hot encode categories, when one-hot encoding helps, and when a log transform fits.

The StringIndexer

Most Spark ML algorithms need numeric features, so a string column like the vehicle type must first become a number. The StringIndexer maps each string to an index, from zero, and by default the most frequent value gets index zero. It is an estimator: fit learns the list of values from the training data, and the model that it returns transforms any DataFrame. A value that was not seen during fit raises an error by default, and the handleInvalid parameter can skip those rows, or keep them under an extra index. But the index has no real order, since a cargo bike with index two is not twice a scooter, so linear models need one more step.

The OneHotEncoder

The OneHotEncoder turns each index into a binary vector, with at most a single one, in the position of its value, so no false order remains. In Spark, it is an estimator too, and it stores the vectors in a sparse format, which keeps the many zeros cheap. Its handleInvalid parameter is either error, or keep, which adds a position for unseen values. The VectorAssembler, a transformer, then combines the encoded columns and the numeric columns into the single features column that Spark ML algorithms expect. In scikit-learn, the OneHotEncoder works on strings directly, and handle_unknown set to ignore encodes an unseen value as all zeros.

When to one-hot encode

One-hot encoding suits linear and distance based models, like linear or logistic regression, support vector machines, and k nearest neighbors, which would otherwise treat the index as a quantity. Tree based models, like decision trees, random forests, and gradient boosted trees, can split on categories without it, and Spark ML trees use the index directly, as a categorical feature. High cardinality, which means many distinct values, makes one-hot encoding costly: two thousand station IDs would become two thousand sparse columns, which slows training and invites overfitting. For such a feature, group the rare values into an other category, or replace the ID with numeric facts about the station, like its average daily rides. And an ordinal feature, like a battery health grade from one to five, already has a real order, so it can stay as a number.

Log transforms

Some numeric features are strongly skewed to the right, like revenue, ride counts, or durations: most values are small, and a long tail of large ones dominates. Taking the log compresses that tail, brings the distribution closer to symmetric, and turns multiplicative effects into additive ones, which helps linear models. The log only works on positive values, so for a feature that contains zeros, like a ride count, log1p, the log of one plus the value, is the usual choice. A feature with negative values, like a temperature in degrees, should not get a log at all. And tree based models barely change with a log of a feature, since a split depends only on the order of the values, while linear models gain the most.

Recap

Let's recap. The StringIndexer turns strings into indexes, the most frequent first, and handleInvalid decides what happens to unseen values. The OneHotEncoder turns indexes into sparse binary vectors, and the VectorAssembler builds the features column. One-hot encoding suits linear and distance based models, not tree based ones, and high cardinality makes it costly. A log compresses a positive, right skewed feature, with log1p when it contains zeros. And ordinal features can keep their numbers, while negative values never get a log.

Quick checks for this lesson

The 3 questions of this lesson, as plain text. The button above runs them with shuffled choices and the reason behind every choice.

  1. A StringIndexer was fitted on last year’s trips. A new vehicle type, the electric moped, now appears in the scoring data, and the job must keep these rows. Which setting fits?

    • handleInvalid="skip"
    • handleInvalid="error"
    • handleInvalid="keep"
    • stringOrderType="alphabetAsc"
    Show the answer

    handleInvalid="keep"

    Keep puts the unseen values under an extra index, so the rows stay in the output. “handleInvalid="skip"” would drop the rows with the new vehicle type. “handleInvalid="error"” is the default, and would stop the job with an error. And “stringOrderType="alphabetAsc"” only changes how the indexes are ordered.

  2. A team predicts trip demand with a linear regression, and one feature is the city zone, with six values, stored as an index from 0 to 5. What should happen to this feature?

    • One-hot encode it for the linear model
    • Keep the index as a numeric feature
    • Take the log of the index first
    • Drop it: linear models need numbers
    Show the answer

    One-hot encode it for the linear model

    One-hot encoding gives the linear model one coefficient per zone, without a false order. “Keep the index as a numeric feature” would treat zone five as five times zone one. “Take the log of the index first” would keep a false order, only compressed. And “Drop it: linear models need numbers” would lose a useful feature, when encoding it works.

  3. Daily rides per station range from 0 to several thousand, and most stations stay below 20. A data scientist wants a log transform of this feature for a linear model. Which expression fits?

    • F.log("rides")
    • F.exp("rides")
    • F.log10("rides")
    • F.log1p("rides")
    Show the answer

    F.log1p("rides")

    Log1p computes the log of one plus the value, so a station with zero rides gets a defined value of zero. “F.log("rides")” gives no valid value for the stations with zero rides, since the log of zero is undefined. “F.exp("rides")” would stretch the tail, instead of compressing it. And “F.log10("rides")” has the same problem as “F.log("rides")”, only with a base of ten.