-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBPMProject_CustomerBehaviorAnalysis.py
2477 lines (1437 loc) · 77.7 KB
/
BPMProject_CustomerBehaviorAnalysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/Sharif_Logo.png?raw=true" width="250" alt="cognitiveclass.ai logo" />
# </center>
#
# # Process Mining Project - Customer Behavior Analysis Based on Click Data
#
# ## Course Info:
#
# **Student/Analyst:** Sina Aghaee <br>
# **Course:** Business Process Management 1400-1401 <br>
# **Institution:** Sharif University of Technology, Department of Industrial Engineering <br>
# **Instructor:** Dr. Erfan Hassannayebi
#
# <h1>Table of contents</h1>
#
# <div class="alert alert-block alert-info" style="margin-top: 20px">
# <ol>
# <li><a href="#about_dataset">About the Dataset and the Paper</a></li>
# <li><a href="#pre-processing">Pre-processing</a></li>
# <li><a href="#Process_discovery">Challenge 1: Process Discovery</a></li>
# <li><a href="#Customer_behaviour">Challenge 2: Customer Behaviour</a></li>
# <li><a href="#Transition_expensive_channels">Challenge 4: Transition to More Expensive Channels</a></li>
# </ol>
# </div>
# <br>
# <hr>
# <div id="about_dataset">
# <h2>About the Dataset and the Paper</h2>
#
# </div>
#
# Our data belongs to UWV and presented in BPI 2016 Challenge.
#
# <h3>About UWV</h3>
#
# UWV (Employee Insurance Agency) is a Dutch autonomous administrative authority (ZBO) and is commissioned by the Ministry of Social Affairs and Employment (SZW) to implement employee insurances and provide labour market and data services in the Netherlands.
#
# The Dutch employee insurances are provided for via laws such as the WW (Unemployment Insurance Act), the WIA (Work and Income according to Labour Capacity Act, which contains the IVA (Full Invalidity Benefit Regulations), WGA (Return to Work (Partially Disabled) Regulations), the Wajong (Disablement Assistance Act for Handicapped Young Persons), the WAO (Invalidity Insurance Act), the WAZ (Self-employed Persons Disablement Benefits Act), the Wazo (Work and Care Act) and the Sickness Benefits Act.
#
# <h3>Data</h3>
#
# The data in this collection pertains to customer contacts over a period of 8 months and UWV is looking for insights into their customers' journeys. The data is focused on customers in the WW (unemployment benefits) process.
#
# Data has been collected from several different sources, namely:
#
# 1) Click data from the site www.werk.nl collected from visitors that were not logged in:
# * [BPI Challenge 2016: Clicks NOT Logged In](https://data.4tu.nl/articles/dataset/BPI_Challenge_2016_Clicks_NOT_Logged_In/12708596/1)
#
#
# 2) Click data from the customer specific part of the site www.werk.nl (a link is made with the customer that logged in):
# * [BPI Challenge 2016: Clicks Logged In](https://data.4tu.nl/articles/dataset/BPI_Challenge_2016_Clicks_Logged_In/12674816/1)
#
#
# 3) Werkmap Message data, showing when customers contacted the UWV through a digital channel:
# * [BPI Challenge 2016: Questions](https://data.4tu.nl/articles/dataset/BPI_Challenge_2016_Questions/12687320/1)
#
#
# 4) Call data from the call center, showing when customers contacted the call center by phone:
# * [BPI Challenge 2016: Werkmap Messages](https://data.4tu.nl/articles/dataset/BPI_Challenge_2016_Werkmap_Messages/12714569/1)
#
# 5) Complaint data showing when customers complained:
# * [BPI Challenge 2016: Complaints](https://data.4tu.nl/articles/dataset/BPI_Challenge_2016_Complaints/12717647/1)
#
#
# <h3>Paper</h3>
#
# The Following is the paper that we chose as our base paper and we will try to analyze the data in the same way:
# * [Identification of Distinct Usage Patterns and Prediction of Customer Behavior](https://www.win.tue.nl/bpi/lib/exe/fetch.php?media=2016:bpic2016_paper_1.pdf) by Sharam Dadashnia, Tim Niesen, Philip Hake, Peter Fettke, Nijat Mehdiyev and Joerg Evermann
#
# **Note**: The Author of the above article didn't use the Not_Logged_In dataset in the analysis since it doesn't contain any customer ID. We will do the same since this data won't give us much information about customers' behavior over time and in different sessions.
#
#
# <div id="pre-processing">
# <h2>Pre-processing</h2>
#
# </div>
#
# ### Reading and cleaning the data
#
# We will import the required libraries for pre-processing, data analysis, process mining, and discovery in the next cell:
# In[1]:
# The following library and code is to igonre warnings
import warnings
warnings.filterwarnings('ignore')
# python ######################################################################
import sys
import os
import datetime
# basics ######################################################################
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# widgets #####################################################################
import ipywidgets as widgets
from ipywidgets import interact
# process mining ##############################################################
import pm4py
# object.log
from pm4py.objects.log.util import dataframe_utils
from pm4py.objects.log.exporter.xes import exporter as xes_exporter
from pm4py.objects.log.importer.xes import importer as xes_importer
# object.conversion
from pm4py.objects.conversion.dfg import converter as dfg_converter
from pm4py.objects.conversion.process_tree import converter as pt_converter
# algo.discovery
from pm4py.algo.discovery.alpha import variants
from pm4py.algo.discovery.alpha import algorithm as alpha_miner
from pm4py.algo.discovery.dfg import algorithm as dfg_discovery
from pm4py.algo.discovery.heuristics import algorithm as heuristics_miner
from pm4py.algo.discovery.inductive import algorithm as inductive_miner
# algo.filtering
from pm4py.algo.filtering.log.auto_filter.auto_filter import apply_auto_filter
# algo.conformance
from pm4py.algo.conformance.tokenreplay import algorithm as token_replay
# vizualization
from pm4py.visualization.petrinet import visualizer as pn_visualizer
from pm4py.visualization.dfg import visualizer as dfg_visualization
from pm4py.visualization.process_tree import visualizer as pt_visualizer
from pm4py.visualization.heuristics_net import visualizer as hn_visualizer
# statistics
from pm4py.statistics.traces.log import case_statistics
# util
from pm4py.util import vis_utils
# Reading the data and saving it in a datafram:
# In[2]:
clicks_logged_in = pd.read_csv('BPI2016_Clicks_Logged_In.csv', sep = ';', encoding = 'latin', parse_dates=['TIMESTAMP'] )
clicks_logged_in.shape
# There is about 7 milloin Records in clicks_logged_in dataset!!! Now let's check out a sample of records in the dataset, here is the first 10 rows:
# In[3]:
clicks_logged_in.head(10)
# We only need these columns for our analysis and process discovery:
#
# * CustomerID
# * SessionID
# * AgeCategory
# * Gender
# * TIMESTAMP
# * PAGE_NAME
#
# So we will copy these cloumns and save them in a new variable named **"clicks_logged_in_SelectedColumns"**
# In[4]:
clicks_logged_in_SelectedColumns = clicks_logged_in[['CustomerID','SessionID', 'AgeCategory', 'Gender', 'TIMESTAMP', 'PAGE_NAME']].copy()
# Now let's check the types of each column:
# In[5]:
clicks_logged_in_SelectedColumns.dtypes
# Everything seems normal!
# Let's check to see if we have any NA values:
# In[6]:
clicks_logged_in_SelectedColumns.isna().sum()
# Lucky us! there is no NA value in the dataset.
# Let's see how many activites we have in total:
# In[7]:
clicks_logged_in_SelectedColumns['PAGE_NAME'].nunique()
# WOW!!! We have 600 activities!!!! That's too much! We will probably work with the most frequent ones, and since our activities are the web pages that users visited, it makes sense!
# Here we export the cleaned data in CSV format for further analysis(We will use Microsoft Power BI for some visualization, so that's why we export data here and later):
# In[8]:
clicks_logged_in_SelectedColumns.to_csv ('clicks_logged_in_SelectedColumns.csv', index = False)
# ### Segmentation of customer basis with respect to demographic features
#
# In this part, we will segment our data in the same way our chosen article has done (the article's tables only show the result for the first four ); based on the demographic information. We will segment our data into six different data sets. We export all in CSV format for further analysis (Visualization with PowerBI) :
#
# * Segment 1: Age 18-29
# * Segment 2: Age 30-39
# * Segment 3: Age 40-49
# * Segment 4: Age 50-65
# * Segment 5: Females
# * Segment 6: Males
# #### Segment 1: Age 18-29
# In[9]:
clicks_logged_in_SelectedColumns_Age18_29 = clicks_logged_in_SelectedColumns[clicks_logged_in_SelectedColumns['AgeCategory']== '18-29']
# In[10]:
clicks_logged_in_SelectedColumns_Age18_29.head()
# In[11]:
# exporting csv file
clicks_logged_in_SelectedColumns_Age18_29.to_csv ('clicks_logged_in_SelectedColumns_Age18_29.csv', index = False)
# #### Segment 2: Age 30-39
# In[12]:
clicks_logged_in_SelectedColumns_Age30_39 = clicks_logged_in_SelectedColumns[clicks_logged_in_SelectedColumns['AgeCategory']== '30-39']
# In[13]:
clicks_logged_in_SelectedColumns_Age30_39.head()
# In[14]:
# exporting csv file
clicks_logged_in_SelectedColumns_Age30_39.to_csv ('clicks_logged_in_SelectedColumns_Age30_39.csv', index = False)
# #### Segment 3: Age 40-49
# In[15]:
clicks_logged_in_SelectedColumns_Age40_49 = clicks_logged_in_SelectedColumns[clicks_logged_in_SelectedColumns['AgeCategory']== '40-49']
# In[16]:
clicks_logged_in_SelectedColumns_Age40_49.head()
# In[17]:
# exporting csv file
clicks_logged_in_SelectedColumns_Age40_49.to_csv ('clicks_logged_in_SelectedColumns_Age40_49.csv', index = False)
# #### Segment 4: Age 50-65
# In[18]:
clicks_logged_in_SelectedColumns_Age50_65 = clicks_logged_in_SelectedColumns[clicks_logged_in_SelectedColumns['AgeCategory']== '50-65']
# In[19]:
clicks_logged_in_SelectedColumns_Age50_65.head()
# In[20]:
# exporting csv file
clicks_logged_in_SelectedColumns_Age50_65.to_csv ('clicks_logged_in_SelectedColumns_Age50_65.csv', index = False)
# #### Segment 5: Females
# In[21]:
clicks_logged_in_SelectedColumns_Female = clicks_logged_in_SelectedColumns[clicks_logged_in_SelectedColumns['Gender']== 'V']
# In[22]:
clicks_logged_in_SelectedColumns_Female.head()
# In[23]:
# exporting csv file
clicks_logged_in_SelectedColumns_Female.to_csv ('clicks_logged_in_SelectedColumns_Female.csv', index = False)
# #### Segment 6: Males
# In[24]:
clicks_logged_in_SelectedColumns_Male = clicks_logged_in_SelectedColumns[clicks_logged_in_SelectedColumns['Gender']== 'M']
# In[25]:
clicks_logged_in_SelectedColumns_Male.head()
# In[26]:
# exporting csv file
clicks_logged_in_SelectedColumns_Male.to_csv ('clicks_logged_in_SelectedColumns_Male.csv', index = False)
# ### Segmentations Comparison
# in the next cell, we are going to write a code to compare the segments based on age categories:
# In[27]:
# create a dictionary contaning information about each age category
Segments_Comparison = {'Segment': ['Age category 18-29', 'Age category 30-39', 'Age category 40-49', 'Age category 50-65'],
'Number Of Sessions': [clicks_logged_in_SelectedColumns_Age18_29['SessionID'].nunique(), clicks_logged_in_SelectedColumns_Age30_39['SessionID'].nunique(), clicks_logged_in_SelectedColumns_Age40_49['SessionID'].nunique() , clicks_logged_in_SelectedColumns_Age50_65['SessionID'].nunique()] ,
'Number Of Customers': [clicks_logged_in_SelectedColumns_Age18_29['CustomerID'].nunique(), clicks_logged_in_SelectedColumns_Age30_39['CustomerID'].nunique(), clicks_logged_in_SelectedColumns_Age40_49['CustomerID'].nunique() , clicks_logged_in_SelectedColumns_Age50_65['CustomerID'].nunique()] ,
'Number of Events': [clicks_logged_in_SelectedColumns_Age18_29['SessionID'].count(), clicks_logged_in_SelectedColumns_Age30_39['SessionID'].count(), clicks_logged_in_SelectedColumns_Age40_49['SessionID'].count() , clicks_logged_in_SelectedColumns_Age50_65['SessionID'].count()],
}
# convert the dictionary into dataframe and add the sum of each column to the end of dataframe
Segments_Comparison = pd.DataFrame(data=Segments_Comparison)
Segments_Comparison = Segments_Comparison.append(Segments_Comparison[['Number Of Sessions','Number Of Customers','Number of Events' ]].sum(),ignore_index=True)
Segments_Comparison.iloc[4,0] = 'Total'
# we don't want decimals to be diplayed
Segments_Comparison['Number Of Sessions']=Segments_Comparison['Number Of Sessions'].apply('{:,.0f}'.format)
Segments_Comparison['Number Of Customers']=Segments_Comparison['Number Of Customers'].apply('{:,.0f}'.format)
Segments_Comparison['Number of Events']=Segments_Comparison['Number of Events'].apply('{:,.0f}'.format)
Segments_Comparison
# As you can see, the numbers in the above table are precisely the same as the numbers in the following table, which is in our base paper except for the number of events which means the author of the article deleted some records, but they didn't explain which and why.
#
# <br>
#
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/01_Table3.png?raw=true" />
# </center>
# Segmentation info based on Gender:
# In[28]:
# create a dictionary contaning information about each gender category
Segments_Comparison = {'Segment': ['Female' ,'Male'],
'Number Of Sessions': [clicks_logged_in_SelectedColumns_Female['SessionID'].nunique() , clicks_logged_in_SelectedColumns_Male['SessionID'].nunique()] ,
'Number Of Customers': [ clicks_logged_in_SelectedColumns_Female['CustomerID'].nunique() , clicks_logged_in_SelectedColumns_Male['CustomerID'].nunique()] ,
'Number of Events': [clicks_logged_in_SelectedColumns_Female['SessionID'].count() , clicks_logged_in_SelectedColumns_Male['SessionID'].count()],
}
# convert the dictionary into dataframe and add the sum of each column to the end of dataframe
Segments_Comparison = pd.DataFrame(data=Segments_Comparison)
Segments_Comparison=Segments_Comparison.append(Segments_Comparison[['Number Of Sessions','Number Of Customers','Number of Events' ]].sum(),ignore_index=True)
Segments_Comparison.iloc[2,0] = 'Total'
# we don't want decimals to be diplayed
Segments_Comparison['Number Of Sessions']=Segments_Comparison['Number Of Sessions'].apply('{:,.0f}'.format)
Segments_Comparison['Number Of Customers']=Segments_Comparison['Number Of Customers'].apply('{:,.0f}'.format)
Segments_Comparison['Number of Events']=Segments_Comparison['Number of Events'].apply('{:,.0f}'.format)
Segments_Comparison
# ### Activities frequency for all the logged_in dataset
# In the next cell we write a code to find the most frequent activities in all logged in data:
# In[29]:
# counting the repetitions of each activity for all data
activity_counts_all_logged_in = pd.DataFrame(clicks_logged_in_SelectedColumns['PAGE_NAME'].value_counts())
# calculating the relative frequency for all data
activity_counts_all_logged_in['Relative Frequency(%)'] = round(activity_counts_all_logged_in['PAGE_NAME']/len(clicks_logged_in_SelectedColumns)*100,2)
# resting the index of dataframe and renaming the columns
activity_counts_all_logged_in.reset_index(level=0, inplace=True)
activity_counts_all_logged_in=activity_counts_all_logged_in.rename(columns={'PAGE_NAME': 'Absolute Frequency','index': 'Activity' })
# we don't want decimals to be diplayed
activity_counts_all_logged_in['Absolute Frequency']=activity_counts_all_logged_in['Absolute Frequency'].apply('{:,.0f}'.format)
# printing the data for activities with more than one percent Relative Frequency
activity_counts_all_logged_in[activity_counts_all_logged_in['Relative Frequency(%)'] >= 1]
# In the above table, you can see the most frequent activities for all logged-in customers (those with more than one percent relative frequency), as you see only 14 out of 600 hundred webpages visited in more than one percent of the time.
# ### Activities frequency for the segment 1
# Our paper only printed the table for the first segment means age between 18 to 29, so let's check out the frequency of this segment and see how close we are to what our article has done!
# In[30]:
# counting the repetitions of each activity for segment 1: Age 18-29
activity_counts_logged_in_18_29 = pd.DataFrame(clicks_logged_in_SelectedColumns_Age18_29['PAGE_NAME'].value_counts())
# calculating the relative frequency for segment 1: Age 18-29
activity_counts_logged_in_18_29['Relative Frequency(%)'] = round(activity_counts_logged_in_18_29['PAGE_NAME']/len(clicks_logged_in_SelectedColumns_Age18_29)*100,2)
# resting the index of dataframe and renaming the columns
activity_counts_logged_in_18_29.reset_index(level=0, inplace=True)
activity_counts_logged_in_18_29=activity_counts_logged_in_18_29.rename(columns={'PAGE_NAME': 'Absolute Frequency','index': 'Activity' })
# we don't want decimals to be diplayed
activity_counts_logged_in_18_29['Absolute Frequency']=activity_counts_logged_in_18_29['Absolute Frequency'].apply('{:,.0f}'.format)
# printing the data for activities with more than one percent Relative Frequency
activity_counts_logged_in_18_29[activity_counts_logged_in_18_29['Relative Frequency(%)'] >= 1]
# As you see in the above table, the absolute frequencies have a slight difference with the following table. We mentioned this before that the reason is the authors deleted some rows which we dont know why!! However the relative frequency we calculated is the same as the numbers in the articles table.
#
#
# <br>
#
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/02_Table4.png?raw=true" />
# </center>
#
#
# The following chart created by **PowerBI** on the same dataset in seperate analysis:
#
# <br>
#
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/03-Segment1_Frequent_Activities.png?raw=true" />
# </center>
#
#
#
#
# ### Activities frequency for the segment 2
# In[31]:
# counting the repetitions of each activity for segment 2: Age 30-39
activity_counts_logged_in_30_39 = pd.DataFrame(clicks_logged_in_SelectedColumns_Age30_39['PAGE_NAME'].value_counts())
# calculating the relative frequency for segment 2: Age 30-39
activity_counts_logged_in_30_39['Relative Frequency(%)'] = round(activity_counts_logged_in_30_39['PAGE_NAME']/len(clicks_logged_in_SelectedColumns_Age30_39)*100,2)
# resting the index of dataframe and renaming the columns
activity_counts_logged_in_30_39.reset_index(level=0, inplace=True)
activity_counts_logged_in_30_39=activity_counts_logged_in_30_39.rename(columns={'PAGE_NAME': 'Absolute Frequency','index': 'Activity' })
# we don't want decimals to be diplayed
activity_counts_logged_in_30_39['Absolute Frequency']=activity_counts_logged_in_30_39['Absolute Frequency'].apply('{:,.0f}'.format)
# printing the data for activities with more than one percent Relative Frequency
activity_counts_logged_in_30_39[activity_counts_logged_in_30_39['Relative Frequency(%)'] >= 1]
#
# The following chart created by **PowerBI** on the same dataset in seperate analysis:
#
# <br>
#
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/04-Segment2_Frequent_Activities.png?raw=true" />
# </center>
#
#
# ### Activities frequency for the segment 3
# In[32]:
# counting the repetitions of each activity for segment 3: Age 40-49
activity_counts_logged_in_40_49 = pd.DataFrame(clicks_logged_in_SelectedColumns_Age40_49['PAGE_NAME'].value_counts())
# calculating the relative frequency for segment 3: Age 40-49
activity_counts_logged_in_40_49['Relative Frequency(%)'] = round(activity_counts_logged_in_40_49['PAGE_NAME']/len(clicks_logged_in_SelectedColumns_Age40_49)*100,2)
# resting the index of dataframe and renaming the columns
activity_counts_logged_in_40_49.reset_index(level=0, inplace=True)
activity_counts_logged_in_40_49=activity_counts_logged_in_40_49.rename(columns={'PAGE_NAME': 'Absolute Frequency','index': 'Activity' })
# we don't want decimals to be diplayed
activity_counts_logged_in_40_49['Absolute Frequency']=activity_counts_logged_in_40_49['Absolute Frequency'].apply('{:,.0f}'.format)
# printing the data for activities with more than one percent Relative Frequency
activity_counts_logged_in_40_49[activity_counts_logged_in_40_49['Relative Frequency(%)'] >= 1]
#
# The following chart created by **PowerBI** on the same dataset in seperate analysis:
#
# <br>
#
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/05-Segment3_Frequent_Activities.png?raw=true" />
# </center>
#
#
# ### Activities frequency for the segment 4
# In[33]:
# counting the repetitions of each activity for segment 4: Age 50-65
activity_counts_logged_in_50_65 = pd.DataFrame(clicks_logged_in_SelectedColumns_Age50_65['PAGE_NAME'].value_counts())
# calculating the relative frequency for segment 4: Age 50-65
activity_counts_logged_in_50_65['Relative Frequency(%)'] = round(activity_counts_logged_in_50_65['PAGE_NAME']/len(clicks_logged_in_SelectedColumns_Age50_65)*100,2)
# resting the index of dataframe and renaming the columns
activity_counts_logged_in_50_65.reset_index(level=0, inplace=True)
activity_counts_logged_in_50_65=activity_counts_logged_in_50_65.rename(columns={'PAGE_NAME': 'Absolute Frequency','index': 'Activity' })
# we don't want decimals to be diplayed
activity_counts_logged_in_50_65['Absolute Frequency']=activity_counts_logged_in_50_65['Absolute Frequency'].apply('{:,.0f}'.format)
# printing the data for activities with more than one percent Relative Frequency
activity_counts_logged_in_50_65[activity_counts_logged_in_50_65['Relative Frequency(%)'] >= 1]
#
# The following chart created by **PowerBI** on the same dataset in seperate analysis:
#
# <br>
#
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/06-Segment4_Frequent_Activities.png?raw=true" />
# </center>
#
#
# ### Activities frequency for the segment 5
# In[34]:
# counting the repetitions of each activity for segment 5: Female
activity_counts_logged_in_Female = pd.DataFrame(clicks_logged_in_SelectedColumns_Female['PAGE_NAME'].value_counts())
# calculating the relative frequency for segment 5: Female
activity_counts_logged_in_Female['Relative Frequency(%)'] = round(activity_counts_logged_in_Female['PAGE_NAME']/len(clicks_logged_in_SelectedColumns_Female)*100,2)
# resting the index of dataframe and renaming the columns
activity_counts_logged_in_Female.reset_index(level=0, inplace=True)
activity_counts_logged_in_Female=activity_counts_logged_in_Female.rename(columns={'PAGE_NAME': 'Absolute Frequency','index': 'Activity' })
# we don't want decimals to be diplayed
activity_counts_logged_in_Female['Absolute Frequency']=activity_counts_logged_in_Female['Absolute Frequency'].apply('{:,.0f}'.format)
# printing the data for activities with more than one percent Relative Frequency
activity_counts_logged_in_Female[activity_counts_logged_in_Female['Relative Frequency(%)'] >= 1]
# ### Activities frequency for the segment 6
# In[35]:
# counting the repetitions of each activity for segment 6: Male
activity_counts_logged_in_Male = pd.DataFrame(clicks_logged_in_SelectedColumns_Male['PAGE_NAME'].value_counts())
# calculating the relative frequency for segment 6: Male
activity_counts_logged_in_Male['Relative Frequency(%)'] = round(activity_counts_logged_in_Male['PAGE_NAME']/len(clicks_logged_in_SelectedColumns_Female)*100,2)
# resting the index of dataframe and renaming the columns
activity_counts_logged_in_Male.reset_index(level=0, inplace=True)
activity_counts_logged_in_Male=activity_counts_logged_in_Male.rename(columns={'PAGE_NAME': 'Absolute Frequency','index': 'Activity' })
# we don't want decimals to be diplayed
activity_counts_logged_in_Male['Absolute Frequency']=activity_counts_logged_in_Male['Absolute Frequency'].apply('{:,.0f}'.format)
# printing the data for activities with more than one percent Relative Frequency
activity_counts_logged_in_Male[activity_counts_logged_in_Male['Relative Frequency(%)'] >= 1]
# <div id="Process_discovery">
# <h2>Challenge1: Process Discovery: Distinct Usage Patterns for www.werk.nl</h2>
#
#
# </div>
# ## Segment 1: Age 18-29
# In[36]:
# saving the most frequent activites of segment 1 into a list
most_frequent_activites_list_segment1 = activity_counts_logged_in_18_29[activity_counts_logged_in_18_29['Relative Frequency(%)'] >= 1]['Activity'].tolist()
most_frequent_activites_list_segment1
# In[37]:
clicks_logged_in_SelectedColumns_Age18_29.head()
# In[38]:
# copying required columns into new data frames and renaming the columns
segment_1 = clicks_logged_in_SelectedColumns_Age18_29[['SessionID', 'PAGE_NAME', 'TIMESTAMP']].copy()
segment_1=segment_1.rename(columns={'PAGE_NAME': 'activity','SessionID': 'case_id','TIMESTAMP': 'timestamp' })
segment_1.head()
# In[39]:
segment_1.shape
# In[40]:
segment_1_most_frequent = segment_1.copy()
# removing records for non-frequent activities:
segment_1_most_frequent = segment_1_most_frequent[segment_1_most_frequent['activity'].isin(most_frequent_activites_list_segment1)]
## renaming acivity name to "other" for all records with non-frequent activities:
# segment_1_most_frequent.loc[~segment_1_most_frequent['activity'].isin(most_frequent_activites_list_segment1), 'activity'] = 'other'
segment_1_most_frequent.head()
# In[41]:
segment_1_most_frequent.shape
# In[42]:
# creating Event Log
event_log_segment_1 = pm4py.format_dataframe(
segment_1_most_frequent,
case_id = 'case_id',
activity_key = 'activity',
timestamp_key = 'timestamp',
timest_format = '%Y-%m-%d %H:%M:%S%z'
)
# In[43]:
event_log_segment_1.head(7)
# In[44]:
start_activities_segment1 = pm4py.get_start_activities(event_log_segment_1)
end_activities_segment1 = pm4py.get_end_activities(event_log_segment_1)
# In[45]:
print(f'Start activities: {start_activities_segment1}')
print(f'\nEnd activities : {end_activities_segment1}')
# In[46]:
xes_exporter.apply(event_log_segment_1, 'event_log_segment_1.xes')
# In[47]:
log_segment_1 = xes_importer.apply('event_log_segment_1.xes')
# In[48]:
# EventLog
type(log_segment_1)
# In[49]:
# Trace
type(log_segment_1[0])
# In[50]:
# Event
type(log_segment_1[0][0])
# In[51]:
# Start activities
pm4py.get_start_activities(log_segment_1)
# In[52]:
# End activities
pm4py.get_end_activities(log_segment_1)
# In[53]:
# Simplified Interface
heu_net = pm4py.discover_heuristics_net(
log_segment_1, dependency_threshold=0.9999,
and_threshold=0.999,
loop_two_threshold=0.999
)
pm4py.save_vis_heuristics_net(heu_net, file_path='Segment1_behavior_heuristicsminer.png')
pm4py.view_heuristics_net(heu_net)
#
#
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/07-ProcessMap_Segment1.png?raw=true" />
# </center>
#
#
# ## Segment 2: Age 30-39
# In[54]:
# saving the most frequent activites of segment 2 into a list
most_frequent_activites_list_segment2 = activity_counts_logged_in_30_39[activity_counts_logged_in_30_39['Relative Frequency(%)'] >= 1]['Activity'].tolist()
most_frequent_activites_list_segment2
# In[55]:
clicks_logged_in_SelectedColumns_Age30_39.head()
# In[56]:
# copying required columns into new data frames and renaming the columns
segment_2 = clicks_logged_in_SelectedColumns_Age30_39[['SessionID', 'PAGE_NAME', 'TIMESTAMP']].copy()
segment_2=segment_2.rename(columns={'PAGE_NAME': 'activity','SessionID': 'case_id','TIMESTAMP': 'timestamp' })
segment_2.head()
# In[57]:
segment_2.shape
# In[58]:
segment_2_most_frequent = segment_2.copy()
# removing records for non-frequent activities:
segment_2_most_frequent = segment_2_most_frequent[segment_2_most_frequent['activity'].isin(most_frequent_activites_list_segment2)]
## renaming acivity name to "other" for all records with non-frequent activities:
# segment_2_most_frequent.loc[~segment_2_most_frequent['activity'].isin(most_frequent_activites_list_segment2), 'activity'] = 'other'
segment_2_most_frequent.head()
# In[59]:
segment_2_most_frequent.shape
# In[60]:
# creating Event Log
event_log_segment_2 = pm4py.format_dataframe(
segment_2_most_frequent,
case_id = 'case_id',
activity_key = 'activity',
timestamp_key = 'timestamp',
timest_format = '%Y-%m-%d %H:%M:%S%z'
)
# In[61]:
event_log_segment_2.head(7)
# In[62]:
start_activities_2 = pm4py.get_start_activities(event_log_segment_2)
end_activities_2 = pm4py.get_end_activities(event_log_segment_2)
# In[63]:
print(f'Start activities: {start_activities_2}')
print(f'\nEnd activities : {end_activities_2}')
# In[64]:
xes_exporter.apply(event_log_segment_2, 'event_log_segment_2.xes')
# In[65]:
log_segment_2 = xes_importer.apply('event_log_segment_2.xes')
# In[66]:
# Simplified Interface
heu_net = pm4py.discover_heuristics_net(
log_segment_2, dependency_threshold=0.9999,
and_threshold=0.999,
loop_two_threshold=0.999
)
pm4py.save_vis_heuristics_net(heu_net, file_path='Segment2_behavior_heuristicsminer.png')
pm4py.view_heuristics_net(heu_net)
#
#
# <center>
# <img src="https://github.com/sinaaghaee/ProcessMiningProject-CustomerBehaviorAnalysis/blob/main/Images/08-ProcessMap_Segment2.png?raw=true" />
# </center>
#
#
# ## Segment 3: Age 40-49
# In[67]:
# saving the most frequent activites of segment 3 into a list
most_frequent_activites_list_segment3 = activity_counts_logged_in_40_49[activity_counts_logged_in_40_49['Relative Frequency(%)'] >= 1]['Activity'].tolist()
most_frequent_activites_list_segment3
# In[68]:
# copying required columns into new data frames and renaming the columns
segment_3 = clicks_logged_in_SelectedColumns_Age40_49[['SessionID', 'PAGE_NAME', 'TIMESTAMP']].copy()
segment_3=segment_3.rename(columns={'PAGE_NAME': 'activity','SessionID': 'case_id','TIMESTAMP': 'timestamp' })
segment_3.head()
# In[69]:
segment_3.shape
# In[70]:
segment_3_most_frequent = segment_3.copy()
# removing records for non-frequent activities:
segment_3_most_frequent = segment_3_most_frequent[segment_3_most_frequent['activity'].isin(most_frequent_activites_list_segment3)]
## renaming acivity name to "other" for all records with non-frequent activities:
# segment_3_most_frequent.loc[~segment_3_most_frequent['activity'].isin(most_frequent_activites_list_segment3), 'activity'] = 'other'
segment_3_most_frequent.head()
# In[71]:
segment_3_most_frequent.shape
# In[72]:
# creating Event Log
event_log_segment_3 = pm4py.format_dataframe(
segment_3_most_frequent,
case_id = 'case_id',
activity_key = 'activity',
timestamp_key = 'timestamp',
timest_format = '%Y-%m-%d %H:%M:%S%z'
)
# In[73]:
event_log_segment_3.head(7)
# In[74]:
start_activities_3 = pm4py.get_start_activities(event_log_segment_3)
end_activities_3 = pm4py.get_end_activities(event_log_segment_3)
# In[75]:
print(f'Start activities: {start_activities_3}')
print(f'\nEnd activities : {end_activities_3}')
# In[76]:
xes_exporter.apply(event_log_segment_3, 'event_log_segment_3.xes')
# In[77]:
log_segment_3 = xes_importer.apply('event_log_segment_3.xes')
# In[78]: