Predictive Analytics
User Behavior
Temporal Data
Machine Learning
Data Science

Predicting a users next action based on current day and time

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Predicting a user's next action from day and time is a sequence-modeling problem with strong temporal structure. The key is to treat time not as a plain integer column, but as a repeating signal that interacts with user history, recent context, and the set of actions available.

Start with the Right Formulation

This is usually a classification task: given the current context, predict the next action label such as view_product, search, checkout, or logout.

A minimal training row might contain:

  • user identifier
  • timestamp
  • previous action
  • current page or screen
  • device type
  • hour of day
  • day of week
  • target next action

The target should be the action that happens after the current event, not the current action itself.

Encode Time as Cyclical Features

Using hour = 23 and hour = 0 as plain integers is misleading because those times are adjacent in reality but far apart numerically. Cyclical encoding fixes that.

python
1import numpy as np
2import pandas as pd
3
4df = pd.DataFrame({
5    "hour": [8, 12, 18, 23],
6    "day_of_week": [0, 2, 4, 6],
7})
8
9df["hour_sin"] = np.sin(2 * np.pi * df["hour"] / 24)
10df["hour_cos"] = np.cos(2 * np.pi * df["hour"] / 24)
11df["dow_sin"] = np.sin(2 * np.pi * df["day_of_week"] / 7)
12df["dow_cos"] = np.cos(2 * np.pi * df["day_of_week"] / 7)
13
14print(df)

These features tell the model that Monday and Sunday are close on a weekly cycle, and midnight is close to 11 PM.

A Strong Baseline Beats a Fancy First Guess

You do not need an LSTM to get useful predictions. A good first model is often gradient boosting or multiclass logistic regression using:

  • cyclical time features
  • previous action
  • recent action counts
  • recency features such as minutes since last event
  • user segment or cohort

That baseline is cheap to train and easy to interpret. Only move to sequential deep learning if user behavior truly depends on longer histories.

Example with Scikit-Learn

python
1import pandas as pd
2from sklearn.compose import ColumnTransformer
3from sklearn.feature_extraction import DictVectorizer
4from sklearn.linear_model import LogisticRegression
5from sklearn.metrics import classification_report
6from sklearn.pipeline import Pipeline
7from sklearn.preprocessing import FunctionTransformer
8
9train_rows = [
10    {"prev_action": "search", "hour_bin": "morning", "day": "mon", "next_action": "view_product"},
11    {"prev_action": "view_product", "hour_bin": "morning", "day": "mon", "next_action": "add_to_cart"},
12    {"prev_action": "search", "hour_bin": "evening", "day": "fri", "next_action": "logout"},
13    {"prev_action": "view_product", "hour_bin": "evening", "day": "fri", "next_action": "search"},
14]
15
16df = pd.DataFrame(train_rows)
17X = df[["prev_action", "hour_bin", "day"]].to_dict(orient="records")
18y = df["next_action"]
19
20model = Pipeline([
21    ("vectorize", DictVectorizer()),
22    ("clf", LogisticRegression(max_iter=1000))
23])
24
25model.fit(X, y)
26pred = model.predict([{"prev_action": "search", "hour_bin": "morning", "day": "mon"}])
27print(pred[0])

This is a small demonstration, but the structure is correct: time features combine with context features to predict the next action class.

When Sequential Models Help

If the previous ten actions matter more than the last one, sequence models may improve results. Then you can use:

  • Markov chains for short transition logic
  • recurrent networks for longer order-sensitive history
  • transformers if you have large-scale event sequences

But time-of-day alone is rarely enough. Real systems perform better when they mix temporal features with session context and recent behavior.

Common Pitfalls

The biggest mistake is leaking future information into training. For example, using session summary statistics that were only known after the predicted action happened will make the model look unrealistically good.

Another mistake is encoding time as raw integers only. That hides the cyclic nature of hours and weekdays.

A third issue is ignoring class imbalance. If most users just view_page, a naive model can get high accuracy while being useless for rarer actions such as purchase.

Summary

  • Treat next-action prediction as a classification problem over event sequences.
  • Encode hour and weekday as cyclical features instead of plain integers.
  • Start with interpretable baselines before moving to deep sequence models.
  • Combine temporal signals with recent user context and previous actions.
  • Guard against leakage and class imbalance during evaluation.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.