So i just learn Markov Chain by usecases. The use case are, we want to know what the next product and user's space will be used. In here i encode the state as [current_balance, age_category, product_1, product_2, product_3, product_4]
.
So if i have [1, 2, 1, 3, 2, 0]
It means, the users have low balance (elm 0), he's a teenager (elm 1), have savings as his first product (elm 2), have credit card as his second product (elm 4), have mobile banking as his third product (elm 3), and doesn't have any deposits (elm 5).
I creaete 3 files
- generator.py to create random users timeline that the product used
- markov.py create markov chain table
- interact to interact with the table
Here how to use it
$ ./generator.py 20000
Number of Users: 20000
User Timeline saved to timeline_20250503-125952.pkl
$ ./markov.py timeline_20250503-125952.pkl
Processing user timelines...
Waiting for all tasks to complete...
Processed 1000 user timelines...
Processed 2000 user timelines...
Processed 3000 user timelines...
...
Processed 35000 user timelines...
Processed 36000 user timelines...
Processing done, waiting for update thread to finish...
Processed 37000 user timelines...
Processed 38000 user timelines...
...
Processed 48000 user timelines...
Processed 49000 user timelines...
Update thread finished.
State table saved to markov_20250503-130007.pkl
$ ./interact.py markov_20250503-130007.pkl
Enter the state (delimited by space): 3 2 1 2 0 0
Normalized table for state (3, 2, 1, 2, 0, 0):
State (2, 3, 1, 2, 3, 0): 0.2692307692307692
State (1, 3, 1, 2, 3, 0): 0.23076923076923078
State (2, 2, 1, 2, 3, 0): 0.11538461538461539
State (1, 2, 1, 2, 3, 0): 0.07692307692307693
State (3, 2, 1, 2, 3, 0): 0.07692307692307693
State (1, 2, 1, 2, 0, 3): 0.038461538461538464
State (1, 3, 1, 2, 0, 3): 0.038461538461538464
State (1, 4, 1, 2, 3, 0): 0.038461538461538464
State (2, 2, 1, 2, 0, 3): 0.038461538461538464
State (2, 4, 1, 2, 3, 0): 0.038461538461538464
State (3, 3, 1, 2, 3, 0): 0.038461538461538464
As you can see on
$ ./interact.py markov_20250503-130007.pkl
Enter the state (delimited by space): 3 2 1 2 0 0
I want to predict the next product a user that currently have high balance, and a teenager, the savings is his first product, and the m-banking is his second product. And the results are here:
State (2, 3, 1, 2, 3, 0): 0.2692307692307692
State (1, 3, 1, 2, 3, 0): 0.23076923076923078
State (2, 2, 1, 2, 3, 0): 0.11538461538461539
State (1, 2, 1, 2, 3, 0): 0.07692307692307693
State (3, 2, 1, 2, 3, 0): 0.07692307692307693
State (1, 2, 1, 2, 0, 3): 0.038461538461538464
State (1, 3, 1, 2, 0, 3): 0.038461538461538464
State (1, 4, 1, 2, 3, 0): 0.038461538461538464
State (2, 2, 1, 2, 0, 3): 0.038461538461538464
State (2, 4, 1, 2, 3, 0): 0.038461538461538464
State (3, 3, 1, 2, 3, 0): 0.038461538461538464
The state (2, 3, 1, 2, 3, 0)
has the highest probability, where the user probably have credit card for the next product (elm 4, denoted 3rd product)