Encode hour of day and day of week as sine and cosine features
Why it matters Time-of-day and day-of-week features drive demand forecasting, traffic prediction for LLM serving and fraud models.
Hour 23 and hour 0 are one hour apart, but as raw numbers they look 23 apart. Mapping each cyclic value onto a circle with sine and cosine fixes that for any model.
Write cyclical_features(hours, weekdays). hours has ints in 0..23 and weekdays ints in 0..6, both length N. Return an (N, 4) float array with columns [sin(2 pi h / 24), cos(2 pi h / 24), sin(2 pi d / 7), cos(2 pi d / 7)].
def cyclical_features(hours, weekdays)Example
cyclical_features([6], [0]) is about [[1.0, 0.0, 0.0, 1.0]].
Understand the idea
Some features repeat in a cycle: hours of the day, days of the week, months. A model sees raw hour 23 and hour 0 as far apart, though they are neighbours. Put each value on a circle instead, like the hand of a clock, and use its x and y position as two features.
Worked example: hour 6 is a quarter of a day, angle = 2 pi * 6 / 24 = pi / 2, so sin = 1 and cos = 0. Hour 0 gives (0, 1) and hour 23 gives (sin(345 deg), cos(345 deg)) = (-0.259, 0.966), which is close to (0, 1). Weekday 0 gives (0, 1).
Rule: x_sin = sin(2 pi v / P), x_cos = cos(2 pi v / P), with P the period (24 hours, 7 days, 12 months).
Traffic forecasts for LLM endpoints, ride demand models and energy load models all use cyclical encodings.
Shapes and data flow
hours, weekdays (N,) -> features (N, 4)