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?
A store number is a nominal ID stored as an integer. A linear model multiplies its inputs, so it would treat 5893 as larger than 1047 in a meaningful way. Treating the column as categorical, for example by one-hot encoding it, removes that false order. Databricks AutoML handles numeric ID columns the same way. Scaling does not help, because it keeps the same order.
“Numeric columns that contain categorical IDs are treated as a categorical feature.”Source: docs.databricks.com
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)The drop parameter names a category per feature to leave out, so the remaining indicators are no longer co-linear with the intercept. handle_unknown only governs categories unseen during fit, and categories fixes the category list without removing a column.
Source: scikit-learn.org3.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.
| Model family | How it uses an input value | One-hot a nominal feature? |
|---|---|---|
| LinearRegression, LogisticRegression | Multiplies it by a learned weight | Yes. Integer codes force a straight-line effect |
| SVC with an RBF kernel, k-nearest neighbours, k-means | Measures distances between rows | Yes. Integer codes invent unequal gaps |
| Decision trees, random forests, gradient-boosted trees | Compares it to a split threshold | Usually not. OrdinalEncoder or native categorical handling is enough |
| Any classifier's target label | Treats it as a class identifier | No. 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?
A label names the class the model chooses, so integer class IDs carry no false order the model can misuse. The Hugging Face sequence classifier expects those integer IDs, with mappings back to the string names.
“which expects integer IDs as the category labels”Source: docs.databricks.com
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.
No. Sparse output is already the compact form, so dense output stores every zero and makes memory worse. More driver memory only hides a feature space that is still far too wide to be useful. Training one tree instead of a forest shrinks the model, not the encoded data set. The fix is a different representation of ZIP code.
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?
Correct answer: A — One-hot encode contract_type into three binary indicator columns, since logistic regression multiplies each feature by a learned weight and would treat integer codes as ranked magnitudes.
- A. Correct — logistic regression is a linear model that computes weighted sums of feature values, so an unordered categorical feature must become binary indicators; otherwise arbitrary integer codes like 0, 1, 2 would imply a false ordinal relationship between contract lengths.
- B. Incorrect — scikit-learn's
LogisticRegressiondoes not detect or compensate for unordered categories; ordinal integers are treated as ordinary numeric input, so the two-year contract would be modeled as inherently three times the one-year contract. - C. Incorrect — scikit-learn estimators require numeric input and raise an error on raw string columns; Spark's
LogisticRegression(frompyspark.ml) also does not silently one-hot encode string columns without an explicitStringIndexer/OneHotEncoderstage. - D. Incorrect — dropping the feature discards real predictive signal; contract length is a well-known churn driver, and having only three categories is exactly the low-cardinality case where one-hot encoding is cheap and appropriate rather than a reason to remove the column.
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?
Correct answer: A — Push back and use ordinal or native category encoding instead, because tree-based models split on individual feature thresholds and do not assume a linear relationship between encoded values.
- A. Correct — decision trees and gradient boosting choose split points per feature and evaluate categories (or ordinal codes) independently, so they do not suffer from the false-ordering problem that motivates one-hot encoding for linear models; native or ordinal encoding is usually sufficient and keeps the feature space compact.
- B. Incorrect — gradient boosting does not compute a single weighted linear combination of raw feature values the way logistic or linear regression does; each tree instead partitions the feature space with threshold splits, so one-hot encoding is not required to avoid a false numeric ordering.
- C. Incorrect — decision trees are not restricted to binary categorical inputs; a single node can effectively partition many categories through repeated splits, so hashing
regiondown to two buckets discards information for no algorithmic reason. - D. Incorrect —
max_depthand similar hyperparameters control tree structure and regularization, not how categorical values are represented; the model still needsregionencoded as some numeric form (ordinal or one-hot) before it can be dropped into training data at all.
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?
Correct answer: A — Replace one-hot encoding with target encoding or another low-dimensional representation, since ZIP code is the classic high-cardinality case where one-hot encoding inflates the feature space far beyond what is useful.
- A. Correct — scikit-learn's own guidance recommends target encoding for high-cardinality categorical features like ZIP code or region, because one-hot encoding a feature with tens of thousands of categories creates that many additional sparse columns, which is expensive for any downstream model to process.
- B. Incorrect — setting
sparse_output=Falseforces the encoder to materialize a dense array, which uses more memory than the default sparse CSR representation, not less; it does nothing to reduce the underlying 15,000-column dimensionality problem. - C. Incorrect — 15,000 one-hot columns for a single feature is an unusually large and wasteful representation, not a normal ensemble training scenario; adding more driver memory treats a symptom rather than the root cause of an inflated feature space.
- D. Incorrect — reducing
n_estimatorsto a single tree lowers ensemble memory use but does not shrink the width of the training matrix at all; the 15,000-column encoding still has to be constructed and held in memory before any tree can be fit.
Sources2
Sources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Numeric columns that contain categorical IDs are treated as a categorical feature.”
↩︎ Why integer codes mislead some models - 2.https://scikit-learn.org/stable/modules/preprocessing.htmlSecondary source
“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.https://docs.databricks.com/aws/en/sparkr/overviewOfficial docs
“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.
“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.
“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