CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 2 · Lesson 26/48

    When to use one-hot encoding: model types and data sets

    Identify and explain the model types or data sets for which one-hot encoding is or is not appropriate.

    12 min read
    2.11% of exam
    5 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Explain why integer codes for a nominal feature mislead some models and not others
    • Decide whether a linear, distance-based or tree-based model needs one-hot encoded inputs
    • Recognise that classification labels and high-cardinality features should not be one-hot encoded, and pick an alternative

    Key concept

    False ordering of integer codes — If you code a nominal category as 0, 1, 2, a model that does arithmetic on its inputs reads those codes as amounts, with 2 being 'more' than 1. One-hot encoding removes that made-up order by giving each category its own 0/1 column. It helps only models that would otherwise take the order seriously.

    1.Why integer codes mislead some models

    A categorical column has to become numbers before most estimators can use it, and the cheapest way is to give each category an integer. A contract_type column with month-to-month, one-year and two-year becomes 0, 1 and 2. The numbers are just labels. Nobody chose them to mean that two-year is twice one-year, but the column now looks like a quantity.

    Whether this matters depends on what the model does with an input value. Some models multiply it or measure differences between values, and they treat the codes as magnitudes. Others only ask whether a value falls above or below a threshold, and they mostly ignore what the gaps mean. A nominal feature with a handful of unordered values is the textbook case for one-hot encoding, but only when it feeds the first kind of model. Ordinal features such as small, medium and large have a real order, and plain integer codes are a fair way to represent them.

    The same problem appears when a column is already numeric but holds IDs. A store number, a product code or a ZIP code stored as an integer looks continuous to a model, yet 90210 is not 'larger' than 10001 in any useful sense. Databricks AutoML checks for this case and does not treat such columns as numbers.

    Checkpoint 1 of 6· Check yourself

    A table has a store_id column stored as an integer (for example 1047, 2210, 5893), and it feeds a linear regression model. How should you handle this column?

    Sources12

    2.Linear and distance-based models need it

    Linear regression and logistic regression multiply every feature by one learned weight. With contract_type coded 0/1/2, the model has to find a single coefficient w where one-year adds w and two-year adds exactly 2w. That forces the effect of the categories into a straight line the data never suggested. One-hot encoding gives each category its own indicator column and its own coefficient, so month-to-month, one-year and two-year can each move churn odds independently. Having only three values is not a reason to drop the feature. A three-category feature encoded this way is the normal case.

    Distance-based models break in a similar way. k-nearest neighbours, k-means and support vector machines with an RBF kernel all compare rows by the gaps between their values. Under integer codes, category 0 is closer to category 1 than to category 2, which is just an accident of the coding. With one-hot vectors, any two different categories are the same distance apart, which is what 'unordered' means.

    Spark and scikit-learn estimators don't do this step for you. A pyspark.ml or scikit-learn LogisticRegression receives a numeric feature vector and treats any integers it finds as magnitudes. String columns have to be encoded explicitly in the pipeline. The automatic encoding Databricks documents for SparkR is part of SparkR's R-formula glm, not something fit does in general.

    Linear models also raise one more issue. The full set of indicator columns for a feature always sums to 1, so those columns are perfectly co-linear with the intercept. An unregularized linear regression can't separate them, and dropping one category per feature fixes that. In scikit-learn the drop parameter of OneHotEncoder does this: it names a category per feature to leave out, so each feature becomes n_categories - 1 columns (drop='first' removes the first category). Two look-alike parameters don't do it. handle_unknown decides what happens to categories first seen at transform time, and categories fixes the list of values up front; neither removes a column. Regularized linear models put up with the redundancy, and trees don't care about it at all. The mechanics are covered in OneHotEncoder fitting, handle_unknown and drop.

    Checkpoint 2 of 6· Fill the gap

    An unregularized LinearRegression needs each categorical feature encoded into n_categories - 1 indicator columns so the covariance matrix stays invertible. Which parameter completes this scikit-learn encoder?

    drop_enc = preprocessing.OneHotEncoder( ? ='first').fit(X)

    Sources32

    3.Tree models and labels usually don't need it

    Decision trees, random forests and gradient-boosted trees ask one kind of question at each node: is this feature at or below a threshold? Those models never assume a linear relationship between the coded values and the target. Two cuts can wall off any single category, and a deeper branch can group whichever categories behave alike. Databricks' own MLlib examples train gradient-boosted trees on categorical-style inputs such as day of week, weather and season.

    One-hot encoding can actually hurt a tree. A single informative column becomes many sparse 0/1 columns, and each one separates a single category from all the rest. A split on one of them only peels off a small slice of rows. Random feature sampling, as in a random forest, then sees fragments of the feature rather than the whole thing. For tree models, ordinal codes or the library's native categorical handling are the usual choice, and a teammate's rule that 'every categorical must be one-hot encoded' is worth pushing back on.

    The target column follows a different rule. A classification label is not a model input, so integer IDs for its classes carry no false order the model can misuse. They just name the classes the model chooses between. Classifiers expect class indices, and Hugging Face text classifiers are a concrete example. Indicator vectors of the target appear inside some loss calculations, but you don't build them yourself as preprocessing.

    Whether one-hot encoding a nominal feature helps, by model family
    Model familyHow it uses an input valueOne-hot a nominal feature?
    LinearRegression, LogisticRegressionMultiplies it by a learned weightYes. Integer codes force a straight-line effect
    SVC with an RBF kernel, k-nearest neighbours, k-meansMeasures distances between rowsYes. Integer codes invent unequal gaps
    Decision trees, random forests, gradient-boosted treesCompares it to a split thresholdUsually not. OrdinalEncoder or native categorical handling is enough
    Any classifier's target labelTreats it as a class identifierNo. Keep integer class IDs

    Checkpoint 3 of 6· Check yourself

    A support-ticket table has a string label column with the values billing, outage and account, and it will fine-tune AutoModelForSequenceClassification. How should the label column be prepared?

    Sources45

    4.High-cardinality features rule it out

    One-hot encoding adds one column per distinct value, so its cost grows with cardinality. A delivery_zip_code feature with 15,000 ZIP codes becomes 15,000 columns. Most of them are nearly all zeros, and many ZIP codes appear too rarely to learn anything from. The data set swells, training slows, and the model gets thousands of weak features in place of one strong one. This is the clearest data-set reason to avoid one-hot encoding, whatever the model type.

    A lower-dimensional encoding works better. Target encoding replaces each category with the average target value for that category, so ZIP code becomes one numeric column. It needs care, though: compute the averages on training folds only, or the label leaks into the feature. Feature hashing maps categories into a fixed number of buckets. Learned embeddings give each category a short dense vector. Grouping rare categories into a single 'other' bucket can bring a medium-cardinality feature back to a size where one-hot encoding is fine.

    Checkpoint 4 of 6· Exam question

    A data scientist at a retail bank is training a scikit-learn LogisticRegression model to predict customer churn using Databricks. One input feature, contract_type, holds three unordered categories: month-to-month, one-year, and two-year. Which preprocessing approach best prepares this feature for the model?

    Checkpoint 5 of 6· Exam question

    An ML engineer is training a sklearn.ensemble.GradientBoostingClassifier on a dataset where the region feature has five unordered categories. A teammate insists every categorical feature must be one-hot encoded before training any model. How should the engineer respond?

    Checkpoint 6 of 6· Exam question

    A team is building a RandomForestRegressor to predict delivery times using a delivery_zip_code feature containing roughly 15,000 unique ZIP codes. Applying OneHotEncoder to this feature during preprocessing produces a dataset that fails to fit in the cluster's memory. What is the most appropriate fix?

    Sources2

    Sources

    (5)

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

    1. 1.
      “Numeric columns that contain categorical IDs are treated as a categorical feature.”
      ↩︎ Why integer codes mislead some models
    2. 2.
      “would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily)”
      ↩︎ Why integer codes mislead some models
      “when using non-regularized regression (LinearRegression), since co-linearity would cause the covariance matrix to be non-invertible”
      ↩︎ Linear and distance-based models need it
      “This parameter allows the user to specify a category for each feature to be dropped.”
      ↩︎ Linear and distance-based models need it
      “The TargetEncoder uses the target mean conditioned on the categorical feature for encoding unordered categories, i.e. nominal categories”
      ↩︎ High-cardinality features rule it out
      “would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily)”
      ↩︎ Key concept
      “This is useful to avoid co-linearity in the input matrix in some classifiers.”
      ↩︎ Exam trap 3
      “would interpret the categories as being ordered, which is often not desired (i.e. the set of browsers was ordered arbitrarily)”
      ↩︎ Prediction
    3. 3.
      “When using SparkML GLM SparkR automatically performs one-hot encoding of categorical features so that it does not need to be done manually.”
      ↩︎ Linear and distance-based models need it
      “When using SparkML GLM SparkR automatically performs one-hot encoding of categorical features so that it does not need to be done manually.”
      ↩︎ Exam trap 1
    4. 4.
      “perform a regression using gradient boosted trees to predict bike rental counts (per hour) from information such as day of the week, weather, season”
      ↩︎ Tree models and labels usually don't need it
    5. 5.
      “which expects integer IDs as the category labels”
      ↩︎ Tree models and labels usually don't need it
      “which expects integer IDs as the category labels”
      ↩︎ Exam trap 2

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