How do you encode cyclical features like hour-of-day or day-of-week?
mediumAnswer
- Naive integer encoding breaks cyclicity: hour 23 and hour 0 look very far apart, but they're adjacent.
- Encode as two columns: sin(2*pi*x / P) and cos(2*pi*x / P) where P is the period (24, 7, 12, 365).
- Now the distance between 23 and 0 is small in feature space.
- Trees don't need cyclical encoding (they'll find the split), but linear models, distance methods, and neural networks benefit a lot.
- Extract multiple periods too (hour + day + month).
Check yourself — multiple choice
- Use plain integer encoding
- sin/cos with the appropriate period so 23 and 0 are neighbours
- One-hot encoding for every hour
- Cyclical features can't be encoded
sin/cos with the right period preserves circular distance — essential for linear/NN models.
#feature-engineering#encoding#features
Practise Supervised Learning
215 interview questions in this topic.
Related questions
- Ordinal vs nominal encoding — how do you choose?
- What is target encoding and when is it useful?
- How do you turn text into features for a classical model?
- You have a feature with 50,000 unique category values. How do you encode it?
- When should you add interaction features to a linear model?
- How do decision trees handle categorical features?