├── workshop-paper-source ├── paper.pdf ├── figure-1.png ├── figure-2.png ├── figure-3.png ├── figure-1-draw-io.xml ├── figure-2-draw-io.xml ├── figure-3-draw-io.xml └── paper.tex ├── 09-create-submission-one-test-file.py ├── 09-runner-all-files.py ├── 07-runner-all-files.py ├── README.md ├── 07-process-test-file.py ├── 04-create-samples.ipynb ├── 05-track-weights.ipynb ├── 08-predict-each-len-test-set.py ├── LICENSE ├── 06-predict-each-len-val-set.py ├── 05-train-each-len.py ├── 03-train-data-exploration.ipynb └── 01-dataset-sample-rows.ipynb /workshop-paper-source/paper.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sainathadapa/spotify-sequential-skip-prediction/HEAD/workshop-paper-source/paper.pdf -------------------------------------------------------------------------------- /workshop-paper-source/figure-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sainathadapa/spotify-sequential-skip-prediction/HEAD/workshop-paper-source/figure-1.png -------------------------------------------------------------------------------- /workshop-paper-source/figure-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sainathadapa/spotify-sequential-skip-prediction/HEAD/workshop-paper-source/figure-2.png -------------------------------------------------------------------------------- /workshop-paper-source/figure-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sainathadapa/spotify-sequential-skip-prediction/HEAD/workshop-paper-source/figure-3.png -------------------------------------------------------------------------------- /09-create-submission-one-test-file.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import pandas as pd 3 | 4 | one_file = sys.argv[1] 5 | 6 | df = pd.concat([ 7 | pd.read_pickle('./pred/{}-{}.pkl'.format(one_file, i)) 8 | for i in range(10, 21) 9 | ]) 10 | 11 | sid_index = pd.read_csv('./data/test_set/log_input_{}'.format(one_file))\ 12 | .reset_index(drop=False)\ 13 | .rename(columns={'index': 'sid_index'})\ 14 | .groupby('session_id')['sid_index'].first().reset_index() 15 | 16 | df.pred = (df.pred >= 0.5).astype('int64').astype('str') 17 | df.sort_values(['session_id', 'session_position'], inplace=True) 18 | tosave = df.groupby('session_id')['pred'].apply(lambda x: ''.join(x.values)).reset_index() 19 | tosave = pd.merge(tosave, sid_index, on='session_id', how='inner').sort_values('sid_index') 20 | tosave.loc[:, ['pred']].to_csv('./s/{}'.format(one_file), index=False, header=False) 21 | -------------------------------------------------------------------------------- /09-runner-all-files.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import time 3 | from glob import glob 4 | import random 5 | 6 | 7 | test_files = sorted(glob('./data/test_set/log_input_*.csv.gz')) 8 | test_files = [x[-28:] for x in test_files] 9 | 10 | commands_to_run = ['/home/sai/.conda/envs/myenv/bin/python 76-05-submission-one-test-file.py {}'.format(x) 11 | for x in test_files] 12 | random.shuffle(commands_to_run) 13 | 14 | max_procs = 16 15 | processes = [] 16 | while (len(processes) > 0) or (len(commands_to_run) > 0): 17 | 18 | if (len(processes) < max_procs) & (len(commands_to_run) > 0): 19 | this_cmd = commands_to_run.pop() 20 | print(this_cmd) 21 | this_proc = subprocess.Popen(this_cmd, shell=True) 22 | processes.append(this_proc) 23 | 24 | for i in range(len(processes)): 25 | this_proc = processes[i] 26 | if this_proc.poll() is not None: 27 | return_code = this_proc.poll() 28 | print('Process exited with code: ' + str(return_code)) 29 | del processes[i] 30 | break 31 | 32 | time.sleep(1) 33 | -------------------------------------------------------------------------------- /07-runner-all-files.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import time 3 | from glob import glob 4 | import random 5 | 6 | 7 | test_files = sorted(glob('./data/test_set/log_input_*.csv.gz')) 8 | test_files = [x[-28:] for x in test_files] 9 | 10 | commands_to_run = ['/home/sai/.conda/envs/myenv/bin/python 07-process-test-file.py {} {}'.format(x, y) 11 | for x in test_files 12 | for y in range(10, 21)] 13 | random.shuffle(commands_to_run) 14 | 15 | max_procs = 48 16 | processes = [] 17 | while (len(processes) > 0) or (len(commands_to_run) > 0): 18 | 19 | if (len(processes) < max_procs) & (len(commands_to_run) > 0): 20 | this_cmd = commands_to_run.pop() 21 | print(this_cmd) 22 | this_proc = subprocess.Popen(this_cmd, shell=True) 23 | processes.append(this_proc) 24 | 25 | for i in range(len(processes)): 26 | this_proc = processes[i] 27 | if this_proc.poll() is not None: 28 | return_code = this_proc.poll() 29 | print('Process exited with code: ' + str(return_code)) 30 | del processes[i] 31 | break 32 | 33 | time.sleep(1) 34 | -------------------------------------------------------------------------------- /workshop-paper-source/figure-1-draw-io.xml: -------------------------------------------------------------------------------- 1 | 5VjLcpswFP0aL5sBZB5Zxq6bdiaZSep2mi5VUECN4FIhv/r1lYwAg4ibTGyTTDYe6eiBdO45V7JGaJquLznOk2uICBs5VrQeoY8jxzkPkPxVwKYEXOSXQMxpVEJ2A8zpX6JBS6MLGpGi1VEAMEHzNhhClpFQtDDMOaza3e6Btb+a45gYwDzEzER/0EgkJRq4VoN/JjROqi/blm5JcdVZA0WCI1jtQGg2QlMOIMpSup4SprireCnHfXqktV4YJ5l4yoBEzG5vL5fe8ut3+MI248mfcfoh0GsTm2rDJJL711XgIoEYMsxmDTrhsMgioma1ZC0RKZNFWxbJmoq7nfJP1eXMVbVM8M2dHrGtlG2OavxNhNjoyOOFAAk1H74CyPWU5VLV+h5lQEMFLHhI9my7UhLmMRF7+nl1nKS+CaRErlyO44RhQZftdWCttLju1wRDFnQ8nhEbPe8Ss4X+UkGKgkImQQaxUjPBYsGlPbpBFGQt2rEpBIcHMgUGXCIZZCqS95SxDoQZjTNZDSWnROKTJeGCSj9c6IaURtFWBquECjLP8ZbolTS/IQ29fjkBWe8PmUlxNcDX7tHpo84Lq8aMYw0lOz6sTHfwoJwf3zDOPsf4AznGOZFjtkMvOMebnQ450EwUOzPfKKBRiYM6KpEstVLh//q7VkcY5QoamdRbeYGdT5BrO9I5syy7LR80HlfADeFU7kmZfDv5KxaVP2Qadow0bBdKSwlm92rxHIcP7zMX+wPnYts2yH4fyRi9Bd8gwzdOFu3zjceUT35xWYpFTdh7cBJCQzvpBNca42jy22byLO8VHU3eEy1moyE95hkem9Cr+bdrI5rtWPWJfCd+B1B4daOqzwrHVHjQo/DxsRRe/wsf6J/uQCeF/1QZu0PK2H8zMg4GlrFtnqp7SLJPQhLyUZskFBgk2ZZrsoSOxpJ7YJZ6rhTHIK7nQn1a4hzzzSmEVNKi/vA0r099d7Uuwkkub3WSCZk/1KCXOLmH/ggXSR29Q8TC8zoi7omF02P14PmxkNXm2bd8XmjeztHsHw== -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WSDM Cup 2019 - Spotify - Sequential Skip Prediction Challenge - 7th place solution 2 | 3 | You can find a report about my solution [here](workshop-paper-source/paper.pdf) 4 | 5 | To know more about the challenge, refer the following links: 6 | - https://www.crowdai.org/challenges/spotify-sequential-skip-prediction-challenge 7 | - http://www.wsdm-conference.org/2019/wsdm-cup-2019.php 8 | 9 | This repository's contents are shared under the Apache License 2.0. 10 | 11 | To reproduce, follow the steps in order: 12 | 1. Download the dataset from the CrowdAI website. 13 | 2. (Optional) Create sample datasets using the [04-create-samples.ipynb](04-create-samples.ipynb) notebook. 14 | 3. Train the models using the [05-train-each-len.py](05-train-each-len.py) script. 15 | 4. (Optional) Evaluate the models on the validation set using [06-predict-each-len-val-set.py](06-predict-each-len-val-set.py). 16 | 5. Process the test data using the [07-process-test-file.py](07-process-test-file.py). 17 | 6. Finally, the submission file can be created by using the [09-create-submission-one-test-file.py](09-create-submission-one-test-file.py) script. 18 | 19 | ## Citing 20 | 21 | ``` 22 | @article{adapa2019sequential, 23 | title={Sequential modeling of Sessions using Recurrent Neural Networks for Skip Prediction}, 24 | author={Adapa, Sainath}, 25 | journal={arXiv preprint arXiv:1904.10273}, 26 | year={2019} 27 | } 28 | ``` 29 | -------------------------------------------------------------------------------- /workshop-paper-source/figure-2-draw-io.xml: -------------------------------------------------------------------------------- 1 | 7Zpbc9soFMc/jWe2D9lB6OrHxknamU22nTrby750qEQstVh4Eb710y+SwLogx85Ylmy3T5YPCKFz/r8DAgbmaLp6w9AsfKABJgMIgtXAvBlAaFjQET+pZZ1bXBPkhgmLAlmpMIyjn1gaVbV5FOCkUpFTSng0qxp9GsfY5xUbYowuq9WeKKk+dYYmWDOMfUR066co4GFu9WxQ2N/iaBKqJxtAlkyRqiwNSYgCuiyZzNuBOWKU8vxquhphkjpP+SW/725L6aZjDMd8nxvG7x4ex+8+3IB//7u5soL366/J5Mq2ZOf4Wr0xDoQD5F/KeEgnNEbktrBeMzqPA5w2C8S/kE+JuDTEJV5F/HPp+kta5U87/Rdztv4s78j+FGXfMedrGXk051SYiufeUzpTLcbB6zSiabVkHfu56S4iRLYboCTMupXW1t0jPZa+X8kgnfUG0ykW3RIVGCaIR4uqAJDU0WRTb3PrexqJR0AgNW8CT7xWdpPUvOO41UYSOmc+lveVQ1ZvytrZFEdsgrnWlLgovVNhyjTxAn1AL3/cApG5dMh1dD9+fNBkUxXFMow4Hs+Qn5YuRWqoCmVrcBaYcbx6NjyyFJqabyzpm2UBqivhC0uMOmB7SCv+e6mzPHgMmEAFJrdCk1GlSRbuwGRf3vbDKdfyM16x5AiQK3UPrbUH6GHRNI+fGuFzuRGedTQd+6Siqfp9eomsIcn3nsiOMis490SmFL1T+kpr3Uv/b3cdfP1EP0YELv4afXycw8XyyulmirdvNBp9c0hEWp/B2Wp2r3h0u510KaGdXq6ybFvLVY6y9JWtDOPwkfr7fDpT9RHza5rfDNDFt8wXWZYILXCVpmIaY2Ur5alSIvtGqP+jksiMF6PTEMGdKWnY+tyqGR3xfV8TiGfW4r7l46cteFx9oDeStIecIeF6CJ4w4nOGE00zggFeDXzCGf2BR5RQVkT3ScStZkIkmsTiry/igoX9OiUq8hF5LQumURBkqmtCtKrEFiiFth6Eocao1cAoPB6jh08pLp1RA7Q+Zd6yrOD1DakHNEhhHDRC6pAUym9MXE34xr+XiK3paGGxYN/Y2r+x3Ymt2w221hDU9VEP/LGx1SemBFUG1z+iOKU3Ypk1ROTp1S9Ks+UatRTraSw7nbIMvM5YhucKc2fzZKO+6NM1y4ZxbDnssRl0skLZufQw7HFWd+CQPvwd907i3vq04KC4q46Xxm6fTsUgmGalBCdJROOsMzMxUAu3iC6lhksdng3HqidgdeSgt8m2OjpwbDIljYrNs5iG7wbT2xPME9tmHOo77HeiJUDQWmAiZtQf8P0/6YN90ZcMyleaSl60DNzAZgs86dvxrjr609u6MDj2mtMl89TjapQLNnsKHe24bF72zCnU95JdaPe+PwMO34H8lTnsbXmpDw7di+BQ3yftlsPGcwBQc62OZaF36YzK2QltM3n3Lr7uotLr2w2vr2yHqtmq7eGD/ZZXdjbkubWG2kOiMWr6wPRWfCjhOAsc4jj7ess6LLIPBDfYp0GKygl/uGkc7aWbzeEMqJ2JbTqC0NKnm/hbHNHOY1ocdDdv/wc= -------------------------------------------------------------------------------- /workshop-paper-source/figure-3-draw-io.xml: -------------------------------------------------------------------------------- 1 | 7Vzbkto4EP0aqpKHTEm+4sfMLbtVM5VUyNYm+5JSbA04YyzWFjPDfn1kI2FL4uKJr8A+gdtCyH36dEtHgpF5NX/5kKDF7J4EOBoZIHgZmdcjw4CW4bCXzLJaW1zXWxumSRjwRoVhEv6HuRFw6zIMcCo1pIRENFzIRp/EMfapZENJQp7lZg8kkr91gaZYM0x8FOnWv8OAztbWsQ0K+x84nM7EN0PA78yRaMwN6QwF5LlkMm9G5lVCCF2/m79c4ShznvDL+nO3O+5uBpbgmFb5wOTj/ZfJx8/X4J9/r99ZwafV93T6znD54OhKPDEOmAP4JUnojExJjKKbwnqZkGUc4KxbwK5mdB6xt5C9xS8h/ZqZL2x+9Y03YmNMVqVb2eU3/qmfmNIVRx4tKWGm4nvvCFnwdvoDcx+kZJn4eN9TjnnkoGSK6Z6GJscq80HpK7hDP2Ayx2zgrEGCI0TDJzlIEI+16abd5qOfSMgGbQDOC9PlXyRY4TlyF+uR8k8VoLI3pWEUphzqV8BuW23ADsugFzh/LcdAca8q7DgO3mdEzpqlq9hfm27D7InzfgOUzvJh7Q2S1iEdy5CObVfuYh2lGqRaR5ZxoKOWY0OQ5QlFS+6My/Bu8uVeCxk5IJ5nIcWTBcqZ+MyqgRwkO4F5wgnFL3uhES6GimdM7pnnIjMLYs1KSdkBu8GUvPdqV3nnkD1FUjycPd2mqVYLnXEr6LwuyUm5qZTJ/AilaSjnsoGhaY0HhaYYdyktDTIpuRboNymZzlkkpcZzzY6ybtkSvI6l4NZyNRbPWQr7W9YTiNAKJ+z1zSSczgnrgo3IZ8/JnpXEb+ux4oHloysSkYRdxyTG7RDFcXomigc0NzVeH1y5QFwYGlUaLAo/l/OFGD1K/H2w9ZD9d/DLUfgFbbmLHdPmpvhl6WUFptn4FgkOQj9jkxYlLOCpDH5KE/KIFc5soRGKwmmcIc3wYPQ1LzP6hD6K3vMb8zAI8jjbRlE59pqgpGHKzgeWRklrCyWNtihpHdG69Pdrl2VWJKExrCmYGHeJK3/GIQ1RlEOGKM4UtoTMsyHHPgmyCnWq3DGEsqku00vccTrljn0O8z7LGVgBs8b9SnljoxXY98xioJwz+c0DIl3VyKgm5jUXJgNLsWOz/QJo7KuAxlGjKSaTA0FTjHt4UqomMvctpVpnsRFlVd2IshvfiKqFjttBWmpqXt5UzqkKlTMs1dvSt28GmXF610mts9i8aT6R7JgG2/3qpLau4xypTqoSpXed1G1lYflanbQPEbT51L6DPG6/IqgtgrQgjxEHZyKCWqbifOBofOtUBHWg5uwB861Gaaq6quvqVNYmhYpFkQpx2zTUl4vpY7j4XtiyA4xJXtXyPQqaIP8x6zXO7oRJbpyh6OF02Qo9RXYFtsZWCDulayt7FkObRwplZTA101YCwfXsC6Vqtq28tgP8kSuvlQNFiGMDWTeLcQ9Pq7NNJeWZzoWe9DpdEjhnccZIpLLDOc8bVijrZ4YGGciu6fUeyOOzCOTG43NHTXahBLBTANxRTRZPevwykEoWx+6dLK6usfGFyDnoBLatBDcAWwDpVCmAsP6+jK6XlRPanrSVMipTMfXkkOW20tyzNDn9ERG2Vm38vPvB2ux1dZBROSgMQcfqgaurB1BSCd7kMkGKfZJre5lO8DbTDTCiywSnp8tcE7gXKjjmllxqd0rd+qvHU6cuBI0f56i2edU5d8d6ZV0L8IK7BUmdKCPlDzaZcaZ0495TpK0qzDNUvL7rbf2tsNMnbVcCoLLYgAB2TFpdMVJ0+XNkrTpNZqzteT8NgvqL/Kqs1ffRjoS2XU2TDQ+MemUthG1HQ4XTbYONk4NSktfj5K1m7a5/3ut/3Hup//V+5amfbfHJnBVBmi+G0zQXrdhgFqxQM7eg01axDEVWhADox8s6Ls/1f4dbiZivU+WPhZdVjykP7Icunn5MWRbqP+O7v0aDV+nVH7V7UJ/sdqrRQ9C2rnTKbOpNcRp7Tsc7ZZtHPXIGqselPWj3vU8GQf3jEefMwZ4EpD44eOjfXY6Dg+pe9RA4aOiSuk7KItq5M6RDcFVOvxwM0pID7C0OELa6sWyosopbTVY52JPtKR39NifYZfFvp+vmxX/Gmje/AA== -------------------------------------------------------------------------------- /07-process-test-file.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import pickle 3 | import pandas as pd 4 | 5 | one_file = sys.argv[1] 6 | track_len = int(sys.argv[2]) 7 | 8 | track_features = pd.read_pickle('./data/track_features.pkl.gz') 9 | track_ids_slnos = pd.read_pickle('./data/track_ids_slnos.pkl.gz') 10 | 11 | 12 | def process_for_feats(for_feats): 13 | for_feats.skip_1 = for_feats.skip_1.astype('int64') 14 | for_feats.skip_2 = for_feats.skip_2.astype('int64') 15 | for_feats.skip_3 = for_feats.skip_3.astype('int64') 16 | for_feats.not_skipped = for_feats.not_skipped.astype('int64') 17 | for_feats.hist_user_behavior_is_shuffle = for_feats.hist_user_behavior_is_shuffle.astype('int64') 18 | for_feats.premium = for_feats.premium.astype('int64') 19 | 20 | for_feats.date = pd.to_datetime(for_feats.date) 21 | for_feats['wkdy'] = for_feats.date.dt.dayofweek 22 | for_feats['day'] = for_feats.date.dt.day 23 | for_feats['month'] = for_feats.date.dt.month 24 | for_feats['year'] = for_feats.date.dt.year 25 | for_feats.drop(columns=['date'], inplace=True) 26 | 27 | for_feats.drop(columns=['track_id_clean'], inplace=True) 28 | 29 | where_to_replace = for_feats.hist_user_behavior_reason_start.isin([ 30 | 'endplay', 'popup', 'uriopen', 'clickside' 31 | ]).copy() 32 | for_feats.loc[where_to_replace, 'hist_user_behavior_reason_start'] = 'merged' 33 | 34 | where_to_replace = for_feats.hist_user_behavior_reason_end.isin([ 35 | 'clickrow', 'appload', 'popup', 'uriopen', 'clickside', 'logout' 36 | ]).copy() 37 | for_feats.loc[where_to_replace, 'hist_user_behavior_reason_end'] = 'merged' 38 | 39 | for_feats.sort_values(['session_id', 'session_position'], inplace=True) 40 | 41 | return for_feats.reset_index(drop=True) 42 | 43 | 44 | tmp = pd.read_csv('./data/test_set/log_prehistory_{}'.format(one_file)) 45 | tmp = tmp.loc[lambda x: x.session_length == track_len] 46 | tmp = pd.merge(tmp, track_ids_slnos, on=['track_id_clean'], how='inner') 47 | tmp.sort_values(['session_id', 'session_position'], inplace=True) 48 | tmp.reset_index(drop=True, inplace=True) 49 | train_feats = process_for_feats(tmp) 50 | 51 | tmp = pd.read_csv('./data/test_set/log_input_{}'.format(one_file)) 52 | tmp = tmp.loc[lambda x: x.session_length == track_len] 53 | tmp = pd.merge(tmp, track_ids_slnos, on=['track_id_clean'], how='inner') 54 | tmp.sort_values(['session_id', 'session_position'], inplace=True) 55 | tmp.reset_index(drop=True, inplace=True) 56 | train_df = tmp 57 | 58 | cols_to_select = [ 59 | 'context_switch', 60 | 'context_type', 61 | 'day', 62 | 'hist_user_behavior_is_shuffle', 63 | 'hist_user_behavior_n_seekback', 64 | 'hist_user_behavior_n_seekfwd', 65 | 'hist_user_behavior_reason_end', 66 | 'hist_user_behavior_reason_start', 67 | 'hour_of_day', 68 | 'long_pause_before_play', 69 | 'month', 70 | 'no_pause_before_play', 71 | 'not_skipped', 72 | 'premium', 73 | 'session_position', 74 | 'short_pause_before_play', 75 | 'skip_1', 76 | 'skip_2', 77 | 'skip_3', 78 | 'wkdy'] 79 | 80 | train_feats_dummies = pd.get_dummies(train_feats.loc[:, cols_to_select]) 81 | 82 | train_feats.reset_index(drop=False, inplace=True) 83 | train_feats['index'] += 1 84 | train_feats.set_index('index', inplace=True, drop=True, verify_integrity=True) 85 | 86 | train_seq = train_feats.reset_index().groupby('session_id')['index'].apply(lambda x: x.tolist()).tolist() 87 | train_track_seq = train_feats.groupby('session_id')['track_slno'].apply(lambda x: x.tolist()).tolist() 88 | train_pre_pred = train_feats.groupby('session_id')['skip_2'].apply(lambda x: x.tolist()).tolist() 89 | train_to_pred_tracks = train_df.groupby('session_id')['track_slno'].apply(lambda x: x.tolist()).tolist() 90 | 91 | with open('./tmp/{}-{}.pkl'.format(one_file, track_len), 'wb') as f: 92 | pickle.dump(( 93 | train_feats, train_feats_dummies, 94 | track_features, train_seq, 95 | train_track_seq, train_to_pred_tracks, 96 | train_df, train_pre_pred), f) 97 | -------------------------------------------------------------------------------- /04-create-samples.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import pandas as pd\n", 10 | "from joblib import Parallel, delayed" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "df = pd.read_pickle('./data/all_session_ids.pkl.gz')\n", 20 | "df.shape" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "# Random samples" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## Set 1" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "sample_ids = df.sample(frac=0.01)" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "sample_ids.shape" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": null, 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "sample_ids_dict = sample_ids.groupby('filepath')['session_id'].apply(lambda x: list(x)).to_dict()" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "def load_one_file(x, y):\n", 71 | " return pd.read_csv(x)\\\n", 72 | " .loc[lambda k: k.session_id.isin(y)]\\\n", 73 | " .copy()" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": null, 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [ 82 | "sample_data = Parallel(n_jobs=14)(delayed(load_one_file)(filepath, one_sample_set)\n", 83 | " for filepath, one_sample_set in sample_ids_dict.items())" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "sample_data = pd.concat(sample_data)" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [ 101 | "sample_data.shape" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": null, 107 | "metadata": {}, 108 | "outputs": [], 109 | "source": [ 110 | "sample_data.to_pickle('./data/training_set_sample_data_1.pkl')" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "## Set 2" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "metadata": {}, 124 | "outputs": [], 125 | "source": [ 126 | "sample_ids = df\\\n", 127 | " .loc[lambda x: ~x.session_id.isin(sample_ids.session_id.tolist())]\\\n", 128 | " .sample(n=1249507)\n", 129 | "sample_ids.shape" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": null, 135 | "metadata": {}, 136 | "outputs": [], 137 | "source": [ 138 | "sample_ids_dict = sample_ids.groupby('filepath')['session_id'].apply(lambda x: list(x)).to_dict()" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": null, 144 | "metadata": {}, 145 | "outputs": [], 146 | "source": [ 147 | "sample_data = Parallel(n_jobs=14)(delayed(load_one_file)(filepath, one_sample_set)\n", 148 | " for filepath, one_sample_set in sample_ids_dict.items())\n", 149 | "sample_data = pd.concat(sample_data)" 150 | ] 151 | }, 152 | { 153 | "cell_type": "code", 154 | "execution_count": null, 155 | "metadata": {}, 156 | "outputs": [], 157 | "source": [ 158 | "sample_data.to_pickle('./data/training_set_sample_data_2.pkl')" 159 | ] 160 | }, 161 | { 162 | "cell_type": "markdown", 163 | "metadata": {}, 164 | "source": [ 165 | "# Create samples of particular length" 166 | ] 167 | }, 168 | { 169 | "cell_type": "markdown", 170 | "metadata": {}, 171 | "source": [ 172 | "Note: Overall random sample set 2 is not being included in the following samples" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": null, 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "sample_ids = pd.read_pickle('./data/training_set_sample_ids_2.pkl.gz')" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "for a_len in range(10, 21):\n", 191 | " this_sample_ids = df\\\n", 192 | " .loc[lambda x: ~x.session_id.isin(sample_ids.session_id.tolist())]\\\n", 193 | " .loc[lambda x: x.session_length == str(a_len)]\\\n", 194 | " .sample(n=2499014)\n", 195 | " sample_ids_dict = this_sample_ids.groupby('filepath')['session_id'].apply(lambda x: list(x)).to_dict()\n", 196 | " sample_data = Parallel(n_jobs=14)(delayed(load_one_file)(filepath, one_sample_set)\n", 197 | " for filepath, one_sample_set in sample_ids_dict.items())\n", 198 | " sample_data = pd.concat(sample_data)\n", 199 | " sample_data.to_pickle('./data/final_samples/training_set_sample_data_l{}.pkl'.format(a_len))" 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": null, 205 | "metadata": {}, 206 | "outputs": [], 207 | "source": [] 208 | } 209 | ], 210 | "metadata": { 211 | "kernelspec": { 212 | "display_name": "Python 3", 213 | "language": "python", 214 | "name": "python3" 215 | }, 216 | "language_info": { 217 | "codemirror_mode": { 218 | "name": "ipython", 219 | "version": 3 220 | }, 221 | "file_extension": ".py", 222 | "mimetype": "text/x-python", 223 | "name": "python", 224 | "nbconvert_exporter": "python", 225 | "pygments_lexer": "ipython3", 226 | "version": "3.6.6" 227 | }, 228 | "toc": { 229 | "base_numbering": 1, 230 | "nav_menu": {}, 231 | "number_sections": true, 232 | "sideBar": true, 233 | "skip_h1_title": false, 234 | "title_cell": "Table of Contents", 235 | "title_sidebar": "Contents", 236 | "toc_cell": false, 237 | "toc_position": {}, 238 | "toc_section_display": true, 239 | "toc_window_display": true 240 | } 241 | }, 242 | "nbformat": 4, 243 | "nbformat_minor": 2 244 | } 245 | -------------------------------------------------------------------------------- /05-track-weights.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import numpy as np\n", 10 | "import pandas as pd" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 2, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "def evaluate(submission,groundtruth):\n", 20 | " ap_sum = 0.0\n", 21 | " first_pred_acc_sum = 0.0\n", 22 | " counter = 0\n", 23 | " for sub, tru in zip(submission, groundtruth):\n", 24 | " if len(sub) != len(tru):\n", 25 | " raise Exception('Line {} should contain {} predictions, but instead contains '\n", 26 | " '{}'.format(counter+1,len(tru),len(sub)))\n", 27 | " ap_sum += ave_pre(sub,tru,counter)\n", 28 | " first_pred_acc_sum += sub[0] == tru[0]\n", 29 | " counter+=1\n", 30 | " ap = ap_sum/counter\n", 31 | " first_pred_acc = first_pred_acc_sum/counter\n", 32 | " return ap,first_pred_acc\n", 33 | "def ave_pre(submission,groundtruth,counter):\n", 34 | " s = 0.0\n", 35 | " t = 0.0\n", 36 | " c = 1.0\n", 37 | " for x, y in zip(submission, groundtruth):\n", 38 | " if x != 0 and x != 1:\n", 39 | " raise Exception('Invalid prediction in line {}, should be 0 or 1'.format(counter))\n", 40 | " if x==y:\n", 41 | " s += 1.0\n", 42 | " t += s / c\n", 43 | " c += 1\n", 44 | " return t/len(groundtruth)" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 3, 50 | "metadata": {}, 51 | "outputs": [ 52 | { 53 | "data": { 54 | "text/plain": [ 55 | "array([1.7157535 , 1.42285967, 1.22759711, 1.08115019, 0.96399265,\n", 56 | " 0.86636138, 0.78267742, 0.70945396, 0.64436644, 0.58578768])" 57 | ] 58 | }, 59 | "execution_count": 3, 60 | "metadata": {}, 61 | "output_type": "execute_result" 62 | } 63 | ], 64 | "source": [ 65 | "l = 10\n", 66 | "tmp = [\n", 67 | " ave_pre(\n", 68 | " [1 for _ in range(l)],\n", 69 | " [0 if i==j else 1 for j in range(l)],\n", 70 | " None)\n", 71 | " for i in range(l)]\n", 72 | "tmp = 1 - np.array(tmp)\n", 73 | "tmp * l / np.sum(tmp)" 74 | ] 75 | }, 76 | { 77 | "cell_type": "code", 78 | "execution_count": 4, 79 | "metadata": {}, 80 | "outputs": [ 81 | { 82 | "data": { 83 | "text/plain": [ 84 | "array([1.6782454 , 1.38162748, 1.18388219, 1.03557323, 0.91692605,\n", 85 | " 0.81805341, 0.73330543, 0.65915095, 0.59323586])" 86 | ] 87 | }, 88 | "execution_count": 4, 89 | "metadata": {}, 90 | "output_type": "execute_result" 91 | } 92 | ], 93 | "source": [ 94 | "l = 9\n", 95 | "tmp = [\n", 96 | " ave_pre(\n", 97 | " [1 for _ in range(l)],\n", 98 | " [0 if i==j else 1 for j in range(l)],\n", 99 | " None)\n", 100 | " for i in range(l)]\n", 101 | "tmp = 1 - np.array(tmp)\n", 102 | "tmp * l / np.sum(tmp)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": 5, 108 | "metadata": {}, 109 | "outputs": [ 110 | { 111 | "data": { 112 | "text/plain": [ 113 | "array([1.63699919, 1.33584297, 1.13507215, 0.98449404, 0.86403155,\n", 114 | " 0.76364614, 0.67760151, 0.60231245])" 115 | ] 116 | }, 117 | "execution_count": 5, 118 | "metadata": {}, 119 | "output_type": "execute_result" 120 | } 121 | ], 122 | "source": [ 123 | "l = 8\n", 124 | "tmp = [\n", 125 | " ave_pre(\n", 126 | " [1 for _ in range(l)],\n", 127 | " [0 if i==j else 1 for j in range(l)],\n", 128 | " None)\n", 129 | " for i in range(l)]\n", 130 | "tmp = 1 - np.array(tmp)\n", 131 | "tmp * l / np.sum(tmp)" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": 6, 137 | "metadata": {}, 138 | "outputs": [ 139 | { 140 | "data": { 141 | "text/plain": [ 142 | "array([1.59110833, 1.28428303, 1.07973283, 0.92632018, 0.80359006,\n", 143 | " 0.70131497, 0.61365059])" 144 | ] 145 | }, 146 | "execution_count": 6, 147 | "metadata": {}, 148 | "output_type": "execute_result" 149 | } 150 | ], 151 | "source": [ 152 | "l = 7\n", 153 | "tmp = [\n", 154 | " ave_pre(\n", 155 | " [1 for _ in range(l)],\n", 156 | " [0 if i==j else 1 for j in range(l)],\n", 157 | " None)\n", 158 | " for i in range(l)]\n", 159 | "tmp = 1 - np.array(tmp)\n", 160 | "tmp * l / np.sum(tmp)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": 7, 166 | "metadata": {}, 167 | "outputs": [ 168 | { 169 | "data": { 170 | "text/plain": [ 171 | "array([1.53926702, 1.22513089, 1.01570681, 0.85863874, 0.73298429,\n", 172 | " 0.62827225])" 173 | ] 174 | }, 175 | "execution_count": 7, 176 | "metadata": {}, 177 | "output_type": "execute_result" 178 | } 179 | ], 180 | "source": [ 181 | "l = 6\n", 182 | "tmp = [\n", 183 | " ave_pre(\n", 184 | " [1 for _ in range(l)],\n", 185 | " [0 if i==j else 1 for j in range(l)],\n", 186 | " None)\n", 187 | " for i in range(l)]\n", 188 | "tmp = 1 - np.array(tmp)\n", 189 | "tmp * l / np.sum(tmp)" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": 8, 195 | "metadata": {}, 196 | "outputs": [ 197 | { 198 | "data": { 199 | "text/plain": [ 200 | "array([1.47948164, 1.15550756, 0.93952484, 0.7775378 , 0.64794816])" 201 | ] 202 | }, 203 | "execution_count": 8, 204 | "metadata": {}, 205 | "output_type": "execute_result" 206 | } 207 | ], 208 | "source": [ 209 | "l = 5\n", 210 | "tmp = [\n", 211 | " ave_pre(\n", 212 | " [1 for _ in range(l)],\n", 213 | " [0 if i==j else 1 for j in range(l)],\n", 214 | " None)\n", 215 | " for i in range(l)]\n", 216 | "tmp = 1 - np.array(tmp)\n", 217 | "tmp * l / np.sum(tmp)" 218 | ] 219 | }, 220 | { 221 | "cell_type": "code", 222 | "execution_count": null, 223 | "metadata": {}, 224 | "outputs": [], 225 | "source": [] 226 | } 227 | ], 228 | "metadata": { 229 | "kernelspec": { 230 | "display_name": "Python 3", 231 | "language": "python", 232 | "name": "python3" 233 | }, 234 | "language_info": { 235 | "codemirror_mode": { 236 | "name": "ipython", 237 | "version": 3 238 | }, 239 | "file_extension": ".py", 240 | "mimetype": "text/x-python", 241 | "name": "python", 242 | "nbconvert_exporter": "python", 243 | "pygments_lexer": "ipython3", 244 | "version": "3.6.7" 245 | }, 246 | "toc": { 247 | "base_numbering": 1, 248 | "nav_menu": {}, 249 | "number_sections": true, 250 | "sideBar": true, 251 | "skip_h1_title": false, 252 | "title_cell": "Table of Contents", 253 | "title_sidebar": "Contents", 254 | "toc_cell": false, 255 | "toc_position": {}, 256 | "toc_section_display": true, 257 | "toc_window_display": false 258 | } 259 | }, 260 | "nbformat": 4, 261 | "nbformat_minor": 2 262 | } 263 | -------------------------------------------------------------------------------- /08-predict-each-len-test-set.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import pickle 4 | import numpy as np 5 | import pandas as pd 6 | from glob import glob 7 | from keras.utils import Sequence 8 | from keras.models import Model 9 | import keras.layers as kl 10 | import keras.optimizers as ko 11 | import keras.backend as K 12 | 13 | 14 | cuda_dev = sys.argv[1] 15 | track_len = int(sys.argv[2]) 16 | 17 | os.environ["CUDA_VISIBLE_DEVICES"] = cuda_dev 18 | 19 | session_embed_mat_sizes = { 20 | 10: 12495071, 21 | 11: 12495071, 22 | 12: 14994085, 23 | 13: 14994085, 24 | 14: 17493099, 25 | 15: 17493099, 26 | 16: 19992113, 27 | 17: 19992113, 28 | 18: 19992113, 29 | 19: 22491127, 30 | 20: 24990141 31 | } 32 | 33 | session_embed_mat = np.zeros((session_embed_mat_sizes[track_len], 38)) 34 | track_embed_mat = np.zeros((3706389, 29)) 35 | 36 | session_embed = kl.Embedding( 37 | input_dim=session_embed_mat.shape[0], 38 | output_dim=session_embed_mat.shape[1], 39 | weights=[session_embed_mat], 40 | trainable=False, 41 | mask_zero=False, 42 | name='session_embed') 43 | 44 | track_embed = kl.Embedding( 45 | input_dim=track_embed_mat.shape[0], 46 | output_dim=track_embed_mat.shape[1], 47 | weights=[track_embed_mat], 48 | trainable=False, 49 | mask_zero=False, 50 | name='track_embed') 51 | 52 | session_bn = kl.BatchNormalization(name='bn1') 53 | session_transformer = kl.Dense(64, activation='relu', name='session_transformer') 54 | 55 | session_input = kl.Input(shape=(None,), dtype='int64', name='session_input') 56 | x1 = session_embed(session_input) 57 | x1 = session_bn(x1) 58 | x1 = session_transformer(x1) 59 | x1.shape 60 | 61 | track_bn = kl.BatchNormalization(name='track_bn') 62 | track_transformer = kl.Dense(64, activation='relu', name='track_transformer') 63 | 64 | prehist_tracks_input = kl.Input(shape=(None,), dtype='int64', name='prehist_tracks_input') 65 | x2 = track_embed(prehist_tracks_input) 66 | x2 = track_bn(x2) 67 | x2 = track_transformer(x2) 68 | 69 | topred_tracks_input = kl.Input(shape=(None,), dtype='int64', name='topred_tracks_input') 70 | x3 = track_embed(topred_tracks_input) 71 | x3 = track_bn(x3) 72 | x3 = track_transformer(x3) 73 | 74 | x = kl.concatenate([x1, x2], axis=-1) 75 | lstm1 = kl.Bidirectional(kl.CuDNNLSTM(64, return_sequences=False, return_state=False, name='lstm1')) 76 | prehist_sc_1 = lstm1(x) 77 | 78 | x = kl.concatenate([x2, x3], axis=1) 79 | lstm2 = kl.Bidirectional(kl.CuDNNLSTM(64, return_sequences=False, return_state=False, name='lstm2')) 80 | prehist_sc_2 = lstm2(x) 81 | 82 | prehist_sc = kl.concatenate([prehist_sc_1, prehist_sc_2]) 83 | 84 | 85 | def repeat_vector(args): 86 | layer_to_repeat = args[0] 87 | sequence_layer = args[1] 88 | return kl.RepeatVector(K.shape(sequence_layer)[1])(layer_to_repeat) 89 | 90 | 91 | prehist_sc_rep = kl.Lambda(repeat_vector, output_shape=(None, 256))([ 92 | prehist_sc, 93 | x2 94 | ]) 95 | 96 | x = kl.concatenate([ 97 | prehist_sc_rep, 98 | x2 99 | ]) 100 | 101 | base_transformer = kl.Dense(256, activation='relu', name='base_transformer') 102 | encoder_2 = kl.Bidirectional(kl.CuDNNLSTM(256, return_sequences=False, return_state=True, name='encoder_2')) 103 | x = base_transformer(x) 104 | _, fwd_sh, fwd_sc, bck_sh, bck_sc = encoder_2(x) 105 | 106 | fwd_sh = kl.Dropout(0.2)(fwd_sh) 107 | fwd_sc = kl.Dropout(0.2)(fwd_sc) 108 | bck_sh = kl.Dropout(0.2)(bck_sh) 109 | bck_sc = kl.Dropout(0.2)(bck_sc) 110 | 111 | topred_prev_pred_input = kl.Input(shape=(1, 1), dtype='float32', name='topred_prev_pred_input') 112 | 113 | decoder_2 = kl.Bidirectional(kl.CuDNNLSTM(256, return_sequences=True, return_state=True, name='decoder_2')) 114 | decoder_3 = kl.CuDNNLSTM(64, return_sequences=True, return_state=True, name='decoder_3') 115 | decoder_4 = kl.Dropout(0.5) 116 | decoder_5 = kl.Dense(1, activation='sigmoid', name='decoder_5') 117 | 118 | all_ouputs = [] 119 | x = kl.concatenate([ 120 | kl.RepeatVector(1)(prehist_sc), 121 | kl.RepeatVector(1)(kl.Lambda(lambda x: x[:, 0])(x3)) 122 | ]) 123 | x = base_transformer(x) 124 | x, fwd_sh, fwd_sc, bck_sh, bck_sc = decoder_2(x, initial_state=[fwd_sh, fwd_sc, bck_sh, bck_sc]) 125 | x = kl.concatenate([x, topred_prev_pred_input]) 126 | x, sh, sc = decoder_3(x) 127 | x = decoder_4(x) 128 | oup = decoder_5(x) 129 | all_ouputs.append(oup) 130 | 131 | for i in range(1, int(np.ceil(track_len / 2))): 132 | x = kl.concatenate([ 133 | kl.RepeatVector(1)(prehist_sc), 134 | kl.RepeatVector(1)(kl.Lambda(lambda x: x[:, i])(x3)) 135 | ]) 136 | x = base_transformer(x) 137 | x, fwd_sh, fwd_sc, bck_sh, bck_sc = decoder_2(x, initial_state=[fwd_sh, fwd_sc, bck_sh, bck_sc]) 138 | x = kl.concatenate([x, oup]) 139 | x, sh, sc = decoder_3(x, initial_state=[sh, sc]) 140 | x = decoder_4(x) 141 | oup = decoder_5(x) 142 | all_ouputs.append(oup) 143 | 144 | out_combined = kl.Lambda(lambda x: K.concatenate(x, axis=1))(all_ouputs) 145 | 146 | model = Model(inputs=[session_input, 147 | prehist_tracks_input, 148 | topred_tracks_input, 149 | topred_prev_pred_input], 150 | outputs=[out_combined]) 151 | model.compile(optimizer=ko.RMSprop(lr=0.01), loss='binary_crossentropy', metrics=['accuracy']) 152 | 153 | model.load_weights('./model_weights_76_l{}.hdf5'.format(track_len)) 154 | 155 | 156 | class TestGenerator(Sequence): 157 | def __init__(self, 158 | session_seq, 159 | prehist_track_seq, 160 | prehist_pred_seq, 161 | topred_track_seq, 162 | batch_size): 163 | 164 | self.session_seq = session_seq 165 | self.prehist_track_seq = prehist_track_seq 166 | self.prehist_pred_seq = prehist_pred_seq 167 | self.topred_track_seq = topred_track_seq 168 | self.batch_size = batch_size 169 | 170 | self.indices = list(range(len(self.session_seq))) 171 | 172 | def __len__(self): 173 | return int(np.ceil(len(self.session_seq) / self.batch_size)) 174 | 175 | def __getitem__(self, i): 176 | start = self.batch_size * i 177 | end = min(start + self.batch_size, len(self.session_seq)) 178 | this_batch_ids = self.indices[start:end] 179 | 180 | x1_batch = np.array([self.session_seq[i] for i in this_batch_ids]) 181 | x2_batch = np.array([self.prehist_track_seq[i] for i in this_batch_ids]) 182 | x3_batch = np.array([self.topred_track_seq[i] for i in this_batch_ids]) 183 | x4_batch = np.array([ 184 | [self.prehist_pred_seq[i][0]] + self.prehist_pred_seq[i][:-1] 185 | for i in this_batch_ids 186 | ]) 187 | x4_batch = np.expand_dims(x4_batch, -1).astype('float32') 188 | x5_batch = np.array([ 189 | [self.prehist_pred_seq[i][-1]] 190 | for i in this_batch_ids 191 | ]) 192 | x5_batch = np.expand_dims(x5_batch, -1).astype('float32') 193 | return [ 194 | x1_batch, 195 | x2_batch, 196 | x3_batch, 197 | x5_batch 198 | ] 199 | 200 | 201 | test_files = sorted(glob('./data/test_set/log_input_*.csv.gz')) 202 | test_files = [x[-28:] for x in test_files] 203 | 204 | cols_order = [ 205 | 'context_switch', 206 | 'context_type_catalog', 207 | 'context_type_charts', 208 | 'context_type_editorial_playlist', 209 | 'context_type_personalized_playlist', 210 | 'context_type_radio', 211 | 'context_type_user_collection', 212 | 'day', 213 | 'hist_user_behavior_is_shuffle', 214 | 'hist_user_behavior_n_seekback', 215 | 'hist_user_behavior_n_seekfwd', 216 | 'hist_user_behavior_reason_end_backbtn', 217 | 'hist_user_behavior_reason_end_endplay', 218 | 'hist_user_behavior_reason_end_fwdbtn', 219 | 'hist_user_behavior_reason_end_merged', 220 | 'hist_user_behavior_reason_end_remote', 221 | 'hist_user_behavior_reason_end_trackdone', 222 | 'hist_user_behavior_reason_start_appload', 223 | 'hist_user_behavior_reason_start_backbtn', 224 | 'hist_user_behavior_reason_start_clickrow', 225 | 'hist_user_behavior_reason_start_fwdbtn', 226 | 'hist_user_behavior_reason_start_merged', 227 | 'hist_user_behavior_reason_start_playbtn', 228 | 'hist_user_behavior_reason_start_remote', 229 | 'hist_user_behavior_reason_start_trackdone', 230 | 'hist_user_behavior_reason_start_trackerror', 231 | 'hour_of_day', 232 | 'long_pause_before_play', 233 | 'month', 234 | 'no_pause_before_play', 235 | 'not_skipped', 236 | 'premium', 237 | 'session_position', 238 | 'short_pause_before_play', 239 | 'skip_1', 240 | 'skip_2', 241 | 'skip_3', 242 | 'wkdy'] 243 | 244 | 245 | for one_file in test_files: 246 | print(one_file) 247 | 248 | with open('./tmp/{}-{}.pkl'.format(one_file, track_len), 'rb') as f: 249 | train_feats, train_feats_dummies,\ 250 | track_features, train_seq,\ 251 | train_track_seq, train_to_pred_tracks,\ 252 | train_df, train_pre_pred = pickle.load(f) 253 | 254 | test_generator = TestGenerator( 255 | session_seq=train_seq, 256 | prehist_track_seq=train_track_seq, 257 | prehist_pred_seq=train_pre_pred, 258 | topred_track_seq=train_to_pred_tracks, 259 | batch_size=2048) 260 | 261 | assert model.layers[3].name == 'session_embed' 262 | 263 | session_embed_mat = np.concatenate([ 264 | np.zeros((1, 38)), 265 | train_feats_dummies.loc[:, cols_order].values, 266 | np.zeros((session_embed_mat_sizes[track_len] - 1 - train_feats_dummies.shape[0], 38)) 267 | ]) 268 | 269 | model.layers[3].set_weights([session_embed_mat]) 270 | 271 | preds = model.predict_generator( 272 | test_generator, 273 | steps=len(test_generator), 274 | workers=1, 275 | use_multiprocessing=False 276 | ) 277 | 278 | preds_flat = [] 279 | for i in range(preds.shape[0]): 280 | for j in range(preds.shape[1]): 281 | preds_flat.append(preds[i, j, 0]) 282 | 283 | assert len(preds_flat) == train_df.shape[0] 284 | train_df['pred'] = pd.Series(preds_flat, index=train_df.index) 285 | train_df.to_pickle('pred/{}-{}.pkl'.format(one_file, track_len)) 286 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /06-predict-each-len-val-set.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import numpy as np 4 | import pandas as pd 5 | from keras.utils import Sequence 6 | from keras.models import Model 7 | import keras.layers as kl 8 | import keras.optimizers as ko 9 | import keras.backend as K 10 | 11 | cuda_dev = sys.argv[1] 12 | track_len = int(sys.argv[2]) 13 | 14 | os.environ["CUDA_VISIBLE_DEVICES"] = cuda_dev 15 | 16 | track_features = pd.read_pickle('./data/track_features.pkl.gz') 17 | track_ids_slnos = pd.read_pickle('./data/track_ids_slnos.pkl.gz') 18 | 19 | 20 | def prepare_data_1(traindf): 21 | for_feats = traindf.loc[ 22 | lambda x: x.session_position <= (x.session_length/2) 23 | ].copy() 24 | 25 | for_feats.skip_1 = for_feats.skip_1.astype('int64') 26 | for_feats.skip_2 = for_feats.skip_2.astype('int64') 27 | for_feats.skip_3 = for_feats.skip_3.astype('int64') 28 | for_feats.not_skipped = for_feats.not_skipped.astype('int64') 29 | for_feats.hist_user_behavior_is_shuffle = for_feats.hist_user_behavior_is_shuffle.astype('int64') 30 | for_feats.premium = for_feats.premium.astype('int64') 31 | 32 | for_feats.date = pd.to_datetime(for_feats.date) 33 | for_feats['wkdy'] = for_feats.date.dt.dayofweek 34 | for_feats['day'] = for_feats.date.dt.day 35 | for_feats['month'] = for_feats.date.dt.month 36 | for_feats['year'] = for_feats.date.dt.year 37 | for_feats.drop(columns=['date'], inplace=True) 38 | 39 | for_feats.drop(columns=['track_id_clean'], inplace=True) 40 | 41 | where_to_replace = for_feats.hist_user_behavior_reason_start.isin([ 42 | 'endplay', 'popup', 'uriopen', 'clickside' 43 | ]).copy() 44 | for_feats.loc[where_to_replace, 'hist_user_behavior_reason_start'] = 'merged' 45 | 46 | where_to_replace = for_feats.hist_user_behavior_reason_end.isin([ 47 | 'clickrow', 'appload', 'popup', 'uriopen', 'clickside', 'logout' 48 | ]).copy() 49 | for_feats.loc[where_to_replace, 'hist_user_behavior_reason_end'] = 'merged' 50 | 51 | for_feats.sort_values(['session_id', 'session_position'], inplace=True) 52 | 53 | traindf = traindf.loc[ 54 | lambda x: x.session_position > (x.session_length/2) 55 | ].sort_values(['session_id', 'session_position']) 56 | 57 | traindf = traindf.loc[:, [ 58 | 'session_id', 'session_position', 'session_length', 59 | 'track_id_clean', 'track_slno', 'skip_2' 60 | ]].copy() 61 | 62 | traindf.sort_values(['session_id', 'session_position'], inplace=True) 63 | 64 | return (traindf.reset_index(drop=True), 65 | for_feats.reset_index(drop=True)) 66 | 67 | 68 | tmp = pd.read_pickle('./data/training_set_sample_data_2.pkl.gz') 69 | tmp = tmp.loc[lambda x: x.session_length == track_len] 70 | tmp.sort_values(['session_id', 'session_position'], inplace=True) 71 | tmp.reset_index(drop=True, inplace=True) 72 | tmp = pd.merge(tmp, track_ids_slnos, on=['track_id_clean'], how='inner') 73 | tmp.sort_values(['session_id', 'session_position'], inplace=True) 74 | train_df, train_feats = prepare_data_1(tmp) 75 | 76 | cols_to_select = [ 77 | 'context_switch', 78 | 'context_type', 79 | 'day', 80 | 'hist_user_behavior_is_shuffle', 81 | 'hist_user_behavior_n_seekback', 82 | 'hist_user_behavior_n_seekfwd', 83 | 'hist_user_behavior_reason_end', 84 | 'hist_user_behavior_reason_start', 85 | 'hour_of_day', 86 | 'long_pause_before_play', 87 | 'month', 88 | 'no_pause_before_play', 89 | 'not_skipped', 90 | 'premium', 91 | 'session_position', 92 | 'short_pause_before_play', 93 | 'skip_1', 94 | 'skip_2', 95 | 'skip_3', 96 | 'wkdy'] 97 | 98 | train_feats_dummies = pd.get_dummies(train_feats.loc[:, cols_to_select]) 99 | 100 | train_feats.reset_index(drop=False, inplace=True) 101 | train_feats['index'] += 1 102 | train_feats.set_index('index', inplace=True, drop=True, verify_integrity=True) 103 | 104 | train_seq = train_feats.reset_index().groupby('session_id')['index'].apply(lambda x: x.tolist()).tolist() 105 | train_track_seq = train_feats.groupby('session_id')['track_slno'].apply(lambda x: x.tolist()).tolist() 106 | train_df.skip_2 = train_df.skip_2.astype('int64') 107 | train_pre_pred = train_feats.groupby('session_id')['skip_2'].apply(lambda x: x.tolist()).tolist() 108 | train_to_pred_y = train_df.groupby('session_id')['skip_2'].apply(lambda x: x.tolist()).tolist() 109 | train_to_pred_tracks = train_df.groupby('session_id')['track_slno'].apply(lambda x: x.tolist()).tolist() 110 | 111 | cols_order = [ 112 | 'context_switch', 113 | 'context_type_catalog', 114 | 'context_type_charts', 115 | 'context_type_editorial_playlist', 116 | 'context_type_personalized_playlist', 117 | 'context_type_radio', 118 | 'context_type_user_collection', 119 | 'day', 120 | 'hist_user_behavior_is_shuffle', 121 | 'hist_user_behavior_n_seekback', 122 | 'hist_user_behavior_n_seekfwd', 123 | 'hist_user_behavior_reason_end_backbtn', 124 | 'hist_user_behavior_reason_end_endplay', 125 | 'hist_user_behavior_reason_end_fwdbtn', 126 | 'hist_user_behavior_reason_end_merged', 127 | 'hist_user_behavior_reason_end_remote', 128 | 'hist_user_behavior_reason_end_trackdone', 129 | 'hist_user_behavior_reason_start_appload', 130 | 'hist_user_behavior_reason_start_backbtn', 131 | 'hist_user_behavior_reason_start_clickrow', 132 | 'hist_user_behavior_reason_start_fwdbtn', 133 | 'hist_user_behavior_reason_start_merged', 134 | 'hist_user_behavior_reason_start_playbtn', 135 | 'hist_user_behavior_reason_start_remote', 136 | 'hist_user_behavior_reason_start_trackdone', 137 | 'hist_user_behavior_reason_start_trackerror', 138 | 'hour_of_day', 139 | 'long_pause_before_play', 140 | 'month', 141 | 'no_pause_before_play', 142 | 'not_skipped', 143 | 'premium', 144 | 'session_position', 145 | 'short_pause_before_play', 146 | 'skip_1', 147 | 'skip_2', 148 | 'skip_3', 149 | 'wkdy'] 150 | 151 | 152 | session_embed_mat_sizes = { 153 | 10: 12495071, 154 | 11: 12495071, 155 | 12: 14994085, 156 | 13: 14994085, 157 | 14: 17493099, 158 | 15: 17493099, 159 | 16: 19992113, 160 | 17: 19992113, 161 | 18: 19992113, 162 | 19: 22491127, 163 | 20: 22491127 164 | } 165 | 166 | session_embed_mat = np.concatenate([ 167 | np.zeros((1, 38)), 168 | train_feats_dummies.loc[:, cols_order].values, 169 | np.zeros((session_embed_mat_sizes[track_len] - 1 - train_feats_dummies.shape[0], 38)) 170 | ]) 171 | 172 | track_embed_mat = np.concatenate([ 173 | np.zeros((1, 29)), 174 | track_features.values 175 | ]) 176 | 177 | session_embed = kl.Embedding( 178 | input_dim=session_embed_mat.shape[0], 179 | output_dim=session_embed_mat.shape[1], 180 | weights=[session_embed_mat], 181 | trainable=False, 182 | mask_zero=False, 183 | name='session_embed') 184 | 185 | track_embed = kl.Embedding( 186 | input_dim=track_embed_mat.shape[0], 187 | output_dim=track_embed_mat.shape[1], 188 | weights=[track_embed_mat], 189 | trainable=False, 190 | mask_zero=False, 191 | name='track_embed') 192 | 193 | session_bn = kl.BatchNormalization(name='bn1') 194 | session_transformer = kl.Dense(64, activation='relu', name='session_transformer') 195 | 196 | session_input = kl.Input(shape=(None,), dtype='int64', name='session_input') 197 | x1 = session_embed(session_input) 198 | x1 = session_bn(x1) 199 | x1 = session_transformer(x1) 200 | x1.shape 201 | 202 | track_bn = kl.BatchNormalization(name='track_bn') 203 | track_transformer = kl.Dense(64, activation='relu', name='track_transformer') 204 | 205 | prehist_tracks_input = kl.Input(shape=(None,), dtype='int64', name='prehist_tracks_input') 206 | x2 = track_embed(prehist_tracks_input) 207 | x2 = track_bn(x2) 208 | x2 = track_transformer(x2) 209 | 210 | topred_tracks_input = kl.Input(shape=(None,), dtype='int64', name='topred_tracks_input') 211 | x3 = track_embed(topred_tracks_input) 212 | x3 = track_bn(x3) 213 | x3 = track_transformer(x3) 214 | 215 | x = kl.concatenate([x1, x2], axis=-1) 216 | lstm1 = kl.Bidirectional(kl.CuDNNLSTM(64, return_sequences=False, return_state=False, name='lstm1')) 217 | prehist_sc_1 = lstm1(x) 218 | 219 | x = kl.concatenate([x2, x3], axis=1) 220 | lstm2 = kl.Bidirectional(kl.CuDNNLSTM(64, return_sequences=False, return_state=False, name='lstm2')) 221 | prehist_sc_2 = lstm2(x) 222 | 223 | prehist_sc = kl.concatenate([prehist_sc_1, prehist_sc_2]) 224 | 225 | 226 | def repeat_vector(args): 227 | layer_to_repeat = args[0] 228 | sequence_layer = args[1] 229 | return kl.RepeatVector(K.shape(sequence_layer)[1])(layer_to_repeat) 230 | 231 | 232 | prehist_sc_rep = kl.Lambda(repeat_vector, output_shape=(None, 256))([ 233 | prehist_sc, 234 | x2 235 | ]) 236 | 237 | x = kl.concatenate([ 238 | prehist_sc_rep, 239 | x2 240 | ]) 241 | 242 | base_transformer = kl.Dense(256, activation='relu', name='base_transformer') 243 | encoder_2 = kl.Bidirectional(kl.CuDNNLSTM(256, return_sequences=False, return_state=True, name='encoder_2')) 244 | x = base_transformer(x) 245 | _, fwd_sh, fwd_sc, bck_sh, bck_sc = encoder_2(x) 246 | 247 | fwd_sh = kl.Dropout(0.2)(fwd_sh) 248 | fwd_sc = kl.Dropout(0.2)(fwd_sc) 249 | bck_sh = kl.Dropout(0.2)(bck_sh) 250 | bck_sc = kl.Dropout(0.2)(bck_sc) 251 | 252 | topred_prev_pred_input = kl.Input(shape=(1, 1), dtype='float32', name='topred_prev_pred_input') 253 | 254 | decoder_2 = kl.Bidirectional(kl.CuDNNLSTM(256, return_sequences=True, return_state=True, name='decoder_2')) 255 | decoder_3 = kl.CuDNNLSTM(64, return_sequences=True, return_state=True, name='decoder_3') 256 | decoder_4 = kl.Dropout(0.5) 257 | decoder_5 = kl.Dense(1, activation='sigmoid', name='decoder_5') 258 | 259 | all_ouputs = [] 260 | x = kl.concatenate([ 261 | kl.RepeatVector(1)(prehist_sc), 262 | kl.RepeatVector(1)(kl.Lambda(lambda x: x[:, 0])(x3)) 263 | ]) 264 | x = base_transformer(x) 265 | x, fwd_sh, fwd_sc, bck_sh, bck_sc = decoder_2(x, initial_state=[fwd_sh, fwd_sc, bck_sh, bck_sc]) 266 | x = kl.concatenate([x, topred_prev_pred_input]) 267 | x, sh, sc = decoder_3(x) 268 | x = decoder_4(x) 269 | oup = decoder_5(x) 270 | all_ouputs.append(oup) 271 | 272 | for i in range(1, int(np.ceil(track_len / 2))): 273 | x = kl.concatenate([ 274 | kl.RepeatVector(1)(prehist_sc), 275 | kl.RepeatVector(1)(kl.Lambda(lambda x: x[:, i])(x3)) 276 | ]) 277 | x = base_transformer(x) 278 | x, fwd_sh, fwd_sc, bck_sh, bck_sc = decoder_2(x, initial_state=[fwd_sh, fwd_sc, bck_sh, bck_sc]) 279 | x = kl.concatenate([x, oup]) 280 | x, sh, sc = decoder_3(x, initial_state=[sh, sc]) 281 | x = decoder_4(x) 282 | oup = decoder_5(x) 283 | all_ouputs.append(oup) 284 | 285 | out_combined = kl.Lambda(lambda x: K.concatenate(x, axis=1))(all_ouputs) 286 | 287 | model = Model(inputs=[session_input, 288 | prehist_tracks_input, 289 | topred_tracks_input, 290 | topred_prev_pred_input], 291 | outputs=[out_combined]) 292 | model.compile(optimizer=ko.RMSprop(lr=0.01), loss='binary_crossentropy', metrics=['accuracy']) 293 | 294 | model.load_weights('./model_weights_76_l{}.hdf5'.format(track_len)) 295 | 296 | 297 | class TestGenerator(Sequence): 298 | def __init__(self, 299 | session_seq, 300 | prehist_track_seq, 301 | prehist_pred_seq, 302 | topred_track_seq, 303 | batch_size): 304 | 305 | self.session_seq = session_seq 306 | self.prehist_track_seq = prehist_track_seq 307 | self.prehist_pred_seq = prehist_pred_seq 308 | self.topred_track_seq = topred_track_seq 309 | self.batch_size = batch_size 310 | 311 | self.indices = list(range(len(self.session_seq))) 312 | 313 | def __len__(self): 314 | return int(np.ceil(len(self.session_seq) / self.batch_size)) 315 | 316 | def __getitem__(self, i): 317 | start = self.batch_size * i 318 | end = min(start + self.batch_size, len(self.session_seq)) 319 | this_batch_ids = self.indices[start:end] 320 | 321 | x1_batch = np.array([self.session_seq[i] for i in this_batch_ids]) 322 | x2_batch = np.array([self.prehist_track_seq[i] for i in this_batch_ids]) 323 | x3_batch = np.array([self.topred_track_seq[i] for i in this_batch_ids]) 324 | x4_batch = np.array([ 325 | [self.prehist_pred_seq[i][0]] + self.prehist_pred_seq[i][:-1] 326 | for i in this_batch_ids 327 | ]) 328 | x4_batch = np.expand_dims(x4_batch, -1).astype('float32') 329 | x5_batch = np.array([ 330 | [self.prehist_pred_seq[i][-1]] 331 | for i in this_batch_ids 332 | ]) 333 | x5_batch = np.expand_dims(x5_batch, -1).astype('float32') 334 | return [ 335 | x1_batch, 336 | x2_batch, 337 | x3_batch, 338 | x5_batch 339 | ] 340 | 341 | 342 | test_generator = TestGenerator( 343 | session_seq=train_seq, 344 | prehist_track_seq=train_track_seq, 345 | prehist_pred_seq=train_pre_pred, 346 | topred_track_seq=train_to_pred_tracks, 347 | batch_size=2048) 348 | 349 | assert model.layers[3].name == 'session_embed' 350 | assert model.layers[4].name == 'track_embed' 351 | 352 | model.layers[3].set_weights([session_embed_mat]) 353 | model.layers[4].set_weights([track_embed_mat]) 354 | 355 | preds = model.predict_generator( 356 | test_generator, 357 | steps=len(test_generator), 358 | workers=1, 359 | use_multiprocessing=False 360 | ) 361 | 362 | preds_flat = [] 363 | for i in range(preds.shape[0]): 364 | for j in range(preds.shape[1]): 365 | preds_flat.append(preds[i, j, 0]) 366 | 367 | assert len(preds_flat) == train_df.shape[0] 368 | train_df['pred'] = pd.Series(preds_flat, index=train_df.index) 369 | train_df.to_pickle('76-l{}-eval-preds.pkl'.format(track_len)) 370 | -------------------------------------------------------------------------------- /05-train-each-len.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import random 4 | import numpy as np 5 | import pandas as pd 6 | import keras.layers as kl 7 | import keras.optimizers as ko 8 | import keras.callbacks as kc 9 | import keras.backend as K 10 | from keras.utils import Sequence 11 | from keras.models import Model 12 | 13 | cuda_dev = sys.argv[1] 14 | track_len = int(sys.argv[2]) 15 | 16 | os.environ["CUDA_VISIBLE_DEVICES"] = cuda_dev 17 | 18 | track_features = pd.read_pickle('./data/track_features.pkl.gz') 19 | track_ids_slnos = pd.read_pickle('./data/track_ids_slnos.pkl.gz') 20 | 21 | 22 | def prepare_data_1(traindf): 23 | for_feats = traindf.loc[ 24 | lambda x: x.session_position <= (x.session_length/2) 25 | ].copy() 26 | 27 | for_feats.skip_1 = for_feats.skip_1.astype('int64') 28 | for_feats.skip_2 = for_feats.skip_2.astype('int64') 29 | for_feats.skip_3 = for_feats.skip_3.astype('int64') 30 | for_feats.not_skipped = for_feats.not_skipped.astype('int64') 31 | for_feats.hist_user_behavior_is_shuffle = for_feats.hist_user_behavior_is_shuffle.astype('int64') 32 | for_feats.premium = for_feats.premium.astype('int64') 33 | 34 | for_feats.date = pd.to_datetime(for_feats.date) 35 | for_feats['wkdy'] = for_feats.date.dt.dayofweek 36 | for_feats['day'] = for_feats.date.dt.day 37 | for_feats['month'] = for_feats.date.dt.month 38 | for_feats['year'] = for_feats.date.dt.year 39 | for_feats.drop(columns=['date'], inplace=True) 40 | 41 | for_feats.drop(columns=['track_id_clean'], inplace=True) 42 | 43 | where_to_replace = for_feats.hist_user_behavior_reason_start.isin([ 44 | 'endplay', 'popup', 'uriopen', 'clickside' 45 | ]).copy() 46 | for_feats.loc[where_to_replace, 'hist_user_behavior_reason_start'] = 'merged' 47 | 48 | where_to_replace = for_feats.hist_user_behavior_reason_end.isin([ 49 | 'clickrow', 'appload', 'popup', 'uriopen', 'clickside', 'logout' 50 | ]).copy() 51 | for_feats.loc[where_to_replace, 'hist_user_behavior_reason_end'] = 'merged' 52 | 53 | for_feats.sort_values(['session_id', 'session_position'], inplace=True) 54 | 55 | traindf = traindf.loc[ 56 | lambda x: x.session_position > (x.session_length/2) 57 | ].sort_values(['session_id', 'session_position']) 58 | 59 | traindf = traindf.loc[:, [ 60 | 'session_id', 'session_position', 'session_length', 61 | 'track_id_clean', 'track_slno', 'skip_2' 62 | ]].copy() 63 | 64 | traindf.sort_values(['session_id', 'session_position'], inplace=True) 65 | 66 | return (traindf.reset_index(drop=True), 67 | for_feats.reset_index(drop=True)) 68 | 69 | 70 | tmp = pd.read_pickle('./data/final_samples/training_set_sample_data_l{}.pkl'.format(track_len)) 71 | tmp = pd.merge(tmp, track_ids_slnos, on=['track_id_clean'], how='inner') 72 | tmp.sort_values(['session_id', 'session_position'], inplace=True) 73 | 74 | sample_ids = tmp.session_id.drop_duplicates().sample(frac=0.2).tolist() 75 | 76 | train_df, train_feats = prepare_data_1( 77 | tmp 78 | .loc[lambda x: ~x.session_id.isin(sample_ids)] 79 | .sort_values(['session_id', 'session_position']) 80 | .reset_index(drop=True)) 81 | 82 | test_df, test_feats = prepare_data_1( 83 | tmp 84 | .loc[lambda x: x.session_id.isin(sample_ids)] 85 | .sort_values(['session_id', 'session_position']) 86 | .reset_index(drop=True)) 87 | 88 | cols_to_select = [ 89 | 'context_switch', 90 | 'context_type', 91 | 'day', 92 | 'hist_user_behavior_is_shuffle', 93 | 'hist_user_behavior_n_seekback', 94 | 'hist_user_behavior_n_seekfwd', 95 | 'hist_user_behavior_reason_end', 96 | 'hist_user_behavior_reason_start', 97 | 'hour_of_day', 98 | 'long_pause_before_play', 99 | 'month', 100 | 'no_pause_before_play', 101 | 'not_skipped', 102 | 'premium', 103 | 'session_position', 104 | 'short_pause_before_play', 105 | 'skip_1', 106 | 'skip_2', 107 | 'skip_3', 108 | 'wkdy'] 109 | 110 | train_feats_dummies = pd.get_dummies(train_feats.loc[:, cols_to_select]) 111 | test_feats_dummies = pd.get_dummies(test_feats.loc[:, cols_to_select]) 112 | 113 | train_feats.reset_index(drop=False, inplace=True) 114 | train_feats['index'] += 1 115 | train_feats.set_index('index', inplace=True, drop=True, verify_integrity=True) 116 | 117 | test_feats.reset_index(drop=False, inplace=True) 118 | test_feats['index'] += train_feats.index.max() + 1 119 | test_feats.set_index('index', inplace=True, drop=True, verify_integrity=True) 120 | 121 | train_seq = train_feats.reset_index().groupby('session_id')['index'].apply(lambda x: x.tolist()).tolist() 122 | test_seq = test_feats.reset_index().groupby('session_id')['index'].apply(lambda x: x.tolist()).tolist() 123 | 124 | train_track_seq = train_feats.groupby('session_id')['track_slno'].apply(lambda x: x.tolist()).tolist() 125 | test_track_seq = test_feats.groupby('session_id')['track_slno'].apply(lambda x: x.tolist()).tolist() 126 | 127 | train_df.skip_2 = train_df.skip_2.astype('int64') 128 | test_df.skip_2 = test_df.skip_2.astype('int64') 129 | 130 | train_pre_pred = train_feats.groupby('session_id')['skip_2'].apply(lambda x: x.tolist()).tolist() 131 | test_pre_pred = test_feats.groupby('session_id')['skip_2'].apply(lambda x: x.tolist()).tolist() 132 | 133 | train_to_pred_y = train_df.groupby('session_id')['skip_2'].apply(lambda x: x.tolist()).tolist() 134 | test_to_pred_y = test_df.groupby('session_id')['skip_2'].apply(lambda x: x.tolist()).tolist() 135 | 136 | train_to_pred_tracks = train_df.groupby('session_id')['track_slno'].apply(lambda x: x.tolist()).tolist() 137 | test_to_pred_tracks = test_df.groupby('session_id')['track_slno'].apply(lambda x: x.tolist()).tolist() 138 | 139 | cols_order = sorted(train_feats_dummies.columns.values) 140 | 141 | session_embed_mat = np.concatenate([ 142 | np.zeros((1, 38)), 143 | train_feats_dummies.loc[:, cols_order].values, 144 | test_feats_dummies.loc[:, cols_order].values]) 145 | 146 | track_embed_mat = np.concatenate([ 147 | np.zeros((1, 29)), 148 | track_features.values 149 | ]) 150 | 151 | session_embed = kl.Embedding( 152 | input_dim=session_embed_mat.shape[0], 153 | output_dim=session_embed_mat.shape[1], 154 | weights=[session_embed_mat], 155 | trainable=False, 156 | mask_zero=False, 157 | name='session_embed') 158 | 159 | track_embed = kl.Embedding( 160 | input_dim=track_embed_mat.shape[0], 161 | output_dim=track_embed_mat.shape[1], 162 | weights=[track_embed_mat], 163 | trainable=False, 164 | mask_zero=False, 165 | name='track_embed') 166 | 167 | session_bn = kl.BatchNormalization(name='bn1') 168 | session_transformer = kl.Dense(64, activation='relu', name='session_transformer') 169 | 170 | session_input = kl.Input(shape=(None,), dtype='int64', name='session_input') 171 | x1 = session_embed(session_input) 172 | x1 = session_bn(x1) 173 | x1 = session_transformer(x1) 174 | 175 | track_bn = kl.BatchNormalization(name='track_bn') 176 | track_transformer = kl.Dense(64, activation='relu', name='track_transformer') 177 | 178 | prehist_tracks_input = kl.Input(shape=(None,), dtype='int64', name='prehist_tracks_input') 179 | x2 = track_embed(prehist_tracks_input) 180 | x2 = track_bn(x2) 181 | x2 = track_transformer(x2) 182 | 183 | topred_tracks_input = kl.Input(shape=(None,), dtype='int64', name='topred_tracks_input') 184 | x3 = track_embed(topred_tracks_input) 185 | x3 = track_bn(x3) 186 | x3 = track_transformer(x3) 187 | 188 | x = kl.concatenate([x1, x2], axis=-1) 189 | lstm1 = kl.Bidirectional(kl.CuDNNLSTM(64, return_sequences=False, return_state=False, name='lstm1')) 190 | prehist_sc_1 = lstm1(x) 191 | 192 | x = kl.concatenate([x2, x3], axis=1) 193 | lstm2 = kl.Bidirectional(kl.CuDNNLSTM(64, return_sequences=False, return_state=False, name='lstm2')) 194 | prehist_sc_2 = lstm2(x) 195 | 196 | prehist_sc = kl.concatenate([prehist_sc_1, prehist_sc_2]) 197 | 198 | 199 | def repeat_vector(args): 200 | layer_to_repeat = args[0] 201 | sequence_layer = args[1] 202 | return kl.RepeatVector(K.shape(sequence_layer)[1])(layer_to_repeat) 203 | 204 | 205 | prehist_sc_rep = kl.Lambda(repeat_vector, output_shape=(None, 256))([ 206 | prehist_sc, 207 | x2 208 | ]) 209 | 210 | x = kl.concatenate([ 211 | prehist_sc_rep, 212 | x2 213 | ]) 214 | 215 | base_transformer = kl.Dense(256, activation='relu', name='base_transformer') 216 | encoder_2 = kl.Bidirectional(kl.CuDNNLSTM(256, return_sequences=False, return_state=True, name='encoder_2')) 217 | 218 | x = base_transformer(x) 219 | _, fwd_sh, fwd_sc, bck_sh, bck_sc = encoder_2(x) 220 | 221 | fwd_sh = kl.Dropout(0.2)(fwd_sh) 222 | fwd_sc = kl.Dropout(0.2)(fwd_sc) 223 | bck_sh = kl.Dropout(0.2)(bck_sh) 224 | bck_sc = kl.Dropout(0.2)(bck_sc) 225 | 226 | topred_prev_pred_input = kl.Input(shape=(1, 1), dtype='float32', name='topred_prev_pred_input') 227 | 228 | decoder_2 = kl.Bidirectional(kl.CuDNNLSTM(256, return_sequences=True, return_state=True, name='decoder_2')) 229 | decoder_3 = kl.CuDNNLSTM(64, return_sequences=True, return_state=True, name='decoder_3') 230 | decoder_4 = kl.Dropout(0.5) 231 | decoder_5 = kl.Dense(1, activation='sigmoid', name='decoder_5') 232 | 233 | all_ouputs = [] 234 | x = kl.concatenate([ 235 | kl.RepeatVector(1)(prehist_sc), 236 | kl.RepeatVector(1)(kl.Lambda(lambda x: x[:, 0])(x3)) 237 | ]) 238 | x = base_transformer(x) 239 | x, fwd_sh, fwd_sc, bck_sh, bck_sc = decoder_2(x, initial_state=[fwd_sh, fwd_sc, bck_sh, bck_sc]) 240 | x = kl.concatenate([x, topred_prev_pred_input]) 241 | x, sh, sc = decoder_3(x) 242 | x = decoder_4(x) 243 | oup = decoder_5(x) 244 | all_ouputs.append(oup) 245 | 246 | for i in range(1, int(np.ceil(track_len / 2))): 247 | x = kl.concatenate([ 248 | kl.RepeatVector(1)(prehist_sc), 249 | kl.RepeatVector(1)(kl.Lambda(lambda x: x[:, i])(x3)) 250 | ]) 251 | x = base_transformer(x) 252 | x, fwd_sh, fwd_sc, bck_sh, bck_sc = decoder_2(x, initial_state=[fwd_sh, fwd_sc, bck_sh, bck_sc]) 253 | x = kl.concatenate([x, oup]) 254 | x, sh, sc = decoder_3(x, initial_state=[sh, sc]) 255 | x = decoder_4(x) 256 | oup = decoder_5(x) 257 | all_ouputs.append(oup) 258 | 259 | out_combined = kl.Lambda(lambda x: K.concatenate(x, axis=1))(all_ouputs) 260 | model = Model(inputs=[session_input, 261 | prehist_tracks_input, 262 | topred_tracks_input, 263 | topred_prev_pred_input], 264 | outputs=[out_combined]) 265 | model.compile(optimizer=ko.RMSprop(lr=0.01), 266 | loss='binary_crossentropy', 267 | metrics=['accuracy'], 268 | sample_weight_mode='temporal') 269 | 270 | track_weights = { 271 | 5: [1.47948164, 1.15550756, 0.93952484, 0.7775378, 0.64794816], 272 | 6: [1.53926702, 1.22513089, 1.01570681, 0.85863874, 0.73298429, 273 | 0.62827225], 274 | 7: [1.59110833, 1.28428303, 1.07973283, 0.92632018, 0.80359006, 275 | 0.70131497, 0.61365059], 276 | 8: [1.63699919, 1.33584297, 1.13507215, 0.98449404, 0.86403155, 277 | 0.76364614, 0.67760151, 0.60231245], 278 | 9: [1.6782454, 1.38162748, 1.18388219, 1.03557323, 0.91692605, 279 | 0.81805341, 0.73330543, 0.65915095, 0.59323586], 280 | 10: [1.7157535, 1.42285967, 1.22759711, 1.08115019, 0.96399265, 281 | 0.86636138, 0.78267742, 0.70945396, 0.64436644, 0.58578768] 282 | } 283 | 284 | 285 | class TrainGenerator(Sequence): 286 | def __init__(self, 287 | session_seq, 288 | prehist_track_seq, 289 | prehist_pred_seq, 290 | topred_track_seq, 291 | y_seq, 292 | batch_size, 293 | shuffle=True): 294 | 295 | self.session_seq = session_seq 296 | self.prehist_track_seq = prehist_track_seq 297 | self.prehist_pred_seq = prehist_pred_seq 298 | self.topred_track_seq = topred_track_seq 299 | self.y_seq = y_seq 300 | self.batch_size = batch_size 301 | 302 | self.indices = list(range(len(self.session_seq))) 303 | 304 | self.shuffle = shuffle 305 | if self.shuffle: 306 | random.shuffle(self.indices) 307 | 308 | def __len__(self): 309 | return int(np.ceil(len(self.session_seq) / self.batch_size)) 310 | 311 | def on_epoch_end(self): 312 | if self.shuffle: 313 | random.shuffle(self.indices) 314 | 315 | def __getitem__(self, i): 316 | start = self.batch_size * i 317 | end = min(start + self.batch_size, len(self.session_seq)) 318 | this_batch_ids = self.indices[start:end] 319 | 320 | x1_batch = np.array([self.session_seq[i] for i in this_batch_ids]) 321 | x2_batch = np.array([self.prehist_track_seq[i] for i in this_batch_ids]) 322 | x3_batch = np.array([self.topred_track_seq[i] for i in this_batch_ids]) 323 | x4_batch = np.array([ 324 | [self.prehist_pred_seq[i][0]] + self.prehist_pred_seq[i][:-1] 325 | for i in this_batch_ids 326 | ]) 327 | x4_batch = np.expand_dims(x4_batch, -1).astype('float32') 328 | x5_batch = np.array([ 329 | [self.prehist_pred_seq[i][-1]] 330 | for i in this_batch_ids 331 | ]) 332 | x5_batch = np.expand_dims(x5_batch, -1).astype('float32') 333 | y_batch = np.array([self.y_seq[i] for i in this_batch_ids]) 334 | 335 | this_weights = track_weights[int(np.ceil(track_len / 2))] 336 | sample_weights = np.array([this_weights for _ in range(x1_batch.shape[0])]) 337 | 338 | return { 339 | 'session_input': x1_batch, 340 | 'prehist_tracks_input': x2_batch, 341 | 'topred_tracks_input': x3_batch, 342 | 'topred_prev_pred_input': x5_batch 343 | }, np.expand_dims(y_batch, -1), sample_weights 344 | 345 | 346 | train_batch_size = 2048 347 | val_batch_size = 2048 348 | 349 | train_generator = TrainGenerator( 350 | session_seq=train_seq, 351 | prehist_track_seq=train_track_seq, 352 | prehist_pred_seq=train_pre_pred, 353 | topred_track_seq=train_to_pred_tracks, 354 | y_seq=train_to_pred_y, 355 | batch_size=train_batch_size, 356 | shuffle=True) 357 | 358 | val_generator = TrainGenerator( 359 | session_seq=test_seq, 360 | prehist_track_seq=test_track_seq, 361 | prehist_pred_seq=test_pre_pred, 362 | topred_track_seq=test_to_pred_tracks, 363 | y_seq=test_to_pred_y, 364 | batch_size=val_batch_size, 365 | shuffle=False) 366 | 367 | callbacks = [ 368 | kc.EarlyStopping(monitor='val_loss', 369 | patience=15, 370 | verbose=1, 371 | min_delta=1e-4, 372 | mode='min'), 373 | kc.ReduceLROnPlateau(monitor='val_loss', 374 | factor=0.1, 375 | patience=4, 376 | verbose=1, 377 | epsilon=1e-4, 378 | mode='min'), 379 | kc.ModelCheckpoint(monitor='val_loss', 380 | filepath='model_weights_l{}.hdf5'.format(track_len), 381 | save_best_only=True, 382 | save_weights_only=True) 383 | ] 384 | 385 | hist = model.fit_generator( 386 | generator=train_generator, 387 | steps_per_epoch=len(train_generator), 388 | epochs=100, 389 | verbose=2, 390 | callbacks=callbacks, 391 | validation_data=val_generator, 392 | validation_steps=len(val_generator)) 393 | 394 | model.load_weights('./model_weights_l{}.hdf5'.format(track_len)) 395 | 396 | model.evaluate_generator( 397 | val_generator, 398 | steps=len(val_generator), 399 | workers=1, 400 | use_multiprocessing=False 401 | ) 402 | 403 | 404 | class TestGenerator(Sequence): 405 | def __init__(self, 406 | session_seq, 407 | prehist_track_seq, 408 | prehist_pred_seq, 409 | topred_track_seq, 410 | batch_size, 411 | shuffle=True): 412 | 413 | self.session_seq = session_seq 414 | self.prehist_track_seq = prehist_track_seq 415 | self.prehist_pred_seq = prehist_pred_seq 416 | self.topred_track_seq = topred_track_seq 417 | self.batch_size = batch_size 418 | 419 | self.indices = list(range(len(self.session_seq))) 420 | 421 | def __len__(self): 422 | return int(np.ceil(len(self.session_seq) / self.batch_size)) 423 | 424 | def __getitem__(self, i): 425 | start = self.batch_size * i 426 | end = min(start + self.batch_size, len(self.session_seq)) 427 | this_batch_ids = self.indices[start:end] 428 | 429 | x1_batch = np.array([self.session_seq[i] for i in this_batch_ids]) 430 | x2_batch = np.array([self.prehist_track_seq[i] for i in this_batch_ids]) 431 | x3_batch = np.array([self.topred_track_seq[i] for i in this_batch_ids]) 432 | x4_batch = np.array([ 433 | [self.prehist_pred_seq[i][0]] + self.prehist_pred_seq[i][:-1] 434 | for i in this_batch_ids 435 | ]) 436 | x4_batch = np.expand_dims(x4_batch, -1).astype('float32') 437 | x5_batch = np.array([ 438 | [self.prehist_pred_seq[i][-1]] 439 | for i in this_batch_ids 440 | ]) 441 | x5_batch = np.expand_dims(x5_batch, -1).astype('float32') 442 | return { 443 | 'session_input': x1_batch, 444 | 'prehist_tracks_input': x2_batch, 445 | 'topred_tracks_input': x3_batch, 446 | 'topred_prev_pred_input': x5_batch 447 | } 448 | 449 | 450 | test_generator = TestGenerator( 451 | session_seq=test_seq, 452 | prehist_track_seq=test_track_seq, 453 | prehist_pred_seq=test_pre_pred, 454 | topred_track_seq=test_to_pred_tracks, 455 | batch_size=val_batch_size) 456 | 457 | preds = model.predict_generator( 458 | test_generator, 459 | steps=len(test_generator), 460 | workers=1, 461 | use_multiprocessing=False 462 | ) 463 | 464 | preds_flat = [] 465 | for i in range(preds.shape[0]): 466 | for j in range(preds.shape[1]): 467 | preds_flat.append(preds[i, j, 0]) 468 | 469 | test_df['pred'] = pd.Series(preds_flat, index=test_df.index) 470 | test_df['label'] = (test_df.pred >= 0.5).astype('int64') 471 | 472 | gt = test_df.groupby('session_id')['skip_2'].apply(lambda x: x.tolist()).tolist() 473 | subm = test_df.groupby('session_id')['label'].apply(lambda x: x.tolist()).tolist() 474 | 475 | 476 | def evaluate(submission, groundtruth): 477 | ap_sum = 0.0 478 | first_pred_acc_sum = 0.0 479 | counter = 0 480 | for sub, tru in zip(submission, groundtruth): 481 | if len(sub) != len(tru): 482 | raise Exception('Line {} should contain {} predictions, but instead contains ' 483 | '{}'.format(counter+1, len(tru), len(sub))) 484 | ap_sum += ave_pre(sub, tru, counter) 485 | first_pred_acc_sum += sub[0] == tru[0] 486 | counter += 1 487 | ap = ap_sum/counter 488 | first_pred_acc = first_pred_acc_sum/counter 489 | return ap, first_pred_acc 490 | 491 | 492 | def ave_pre(submission, groundtruth, counter): 493 | s = 0.0 494 | t = 0.0 495 | c = 1.0 496 | for x, y in zip(submission, groundtruth): 497 | if x != 0 and x != 1: 498 | raise Exception('Invalid prediction in line {}, should be 0 or 1'.format(counter)) 499 | if x == y: 500 | s += 1.0 501 | t += s / c 502 | c += 1 503 | return t/len(groundtruth) 504 | 505 | 506 | print(evaluate(subm, gt)) 507 | -------------------------------------------------------------------------------- /workshop-paper-source/paper.tex: -------------------------------------------------------------------------------- 1 | %%%% Proceedings format for most of ACM conferences (with the exceptions listed below) and all ICPS volumes. 2 | \documentclass[sigconf]{acmart} 3 | \settopmatter{printacmref=false} % Removes citation information below abstract 4 | \renewcommand\footnotetextcopyrightpermission[1]{} % removes footnote with conference information in first column 5 | \pagestyle{plain} % removes running headers 6 | 7 | % defining the \BibTeX command - from Oren Patashnik's original BibTeX documentation. 8 | \def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08emT\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}} 9 | 10 | % 11 | % end of the preamble, start of the body of the document source. 12 | \setcopyright{none} 13 | \begin{document} 14 | 15 | % 16 | % The "title" command has an optional parameter, allowing the author to define a "short title" to be used in page headers. 17 | \title{Sequential modeling of Sessions using Recurrent Neural Networks for Skip Prediction} 18 | 19 | % 20 | % The "author" command and its associated commands are used to define the authors and their affiliations. 21 | % Of note is the shared affiliation of the first two authors, and the "authornote" and "authornotemark" commands 22 | % used to denote shared contribution to the research. 23 | \author{Sainath Adapa} 24 | \affiliation{\institution{FindHotel}} 25 | \email{adapasainath@gmail.com} 26 | 27 | % 28 | % By default, the full list of authors will be used in the page headers. Often, this list is too long, and will overlap 29 | % other information printed in the page headers. This command allows the author to define a more concise list 30 | % of authors' names for this purpose. 31 | % \renewcommand{\shortauthors}{Trovato and Tobin, et al.} 32 | 33 | % 34 | % The abstract is a short summary of the work to be presented in the article. 35 | \begin{abstract} 36 | Recommender systems play an essential role in music streaming services, prominently in the form of personalized playlists. Exploring the user interactions within these listening sessions can be beneficial to understanding the user preferences in the context of a single session. In the Spotify Sequential Skip Prediction Challenge\footnote{https://www.crowdai.org/challenges/spotify-sequential-skip-prediction-challenge}, WSDM, and Spotify are challenging people to understand the way users sequentially interact with music. We describe our solution approach in this paper and also state proposals for further improvements to the model. The proposed model initially generates a fixed vector representation of the session, and this additional information is incorporated into an Encoder-Decoder style architecture. This method achieved the seventh position in the competition\footnote{Team name: Sainath A}, with a mean average accuracy of 0.604 on the test set. The solution code is available on GitHub\footnote{https://github.com/sainathadapa/spotify-sequential-skip-prediction}. 37 | \end{abstract} 38 | 39 | \begin{CCSXML} 40 | 41 | 42 | 10002951.10003317.10003331.10003271 43 | Information systems~Personalization 44 | 300 45 | 46 | 47 | 10002951.10003317.10003371.10003386.10003390 48 | Information systems~Music retrieval 49 | 300 50 | 51 | 52 | 10002951.10003317.10003347.10003350 53 | Information systems~Recommender systems 54 | 100 55 | 56 | 57 | \end{CCSXML} 58 | 59 | \ccsdesc[300]{Information systems~Personalization} 60 | \ccsdesc[300]{Information systems~Music retrieval} 61 | \ccsdesc[100]{Information systems~Recommender systems} 62 | 63 | 64 | % 65 | % Keywords. The author(s) should pick words that accurately describe the work being 66 | % presented. Separate the keywords with commas. 67 | \keywords{Deep learning, recurrent neural networks, music, recommender systems, user modelling} 68 | 69 | % 70 | % This command processes the author and affiliation and title information and builds 71 | % the first part of the formatted document. 72 | \maketitle 73 | 74 | \section{Introduction} 75 | In many of the music streaming services such as Spotify\footnote{https://www.spotify.com}, personalized music recommendation systems play a prominent role. These recommendation systems allow the user to listen to suggested music based on a particular song, the user's mood, time or location. The vast amount of available music and diverse interests exhibited by various users, as well as by the same user during different situations pose considerable challenges to such systems. As part of WSDM Cup 2019\footnote{http://www.wsdm-conference.org/2019/wsdm-cup-2019.php}, the Spotify Sequential Skip Prediction Challenge mainly explores the sequential nature of user interactions during music listening sessions. 76 | 77 | Spotify has provided 130 million listening sessions for training for this challenge. Another 30 million sessions are provided as the test set\cite{brost2019music}. Each session is divided into two nearly equal halves, with the information about tracks available for both halves of a session. However, the user interaction features are available only for the first half\footnote{Also referred to as \textit{session log features} in this document}. The task is to predict if the user skipped any of the tracks in the second half. 78 | 79 | The length of each session varies from 10 to 20 tracks. This means the model has to predict skipping behavior for five tracks for the shortest sessions, and ten tracks for the longest. Metadata such as duration, release year, and US popularity estimate is provided for every track. Also, audio features such as acousticness, tempo, loudness are provided. For each track that the user was presented within the session, interactions such as seek forward/backward, short/long pause before play are available. Finally, session information such as the time of the day, date, premium user or not, context type of playlist is present. 80 | 81 | In the dataset, skipping behavior is classified into four types: 82 | \begin{enumerate} 83 | \item \textit{skip\_1}: Boolean indicating if the track was only played very briefly 84 | \item \textit{skip\_2}: Boolean indicating if the track was only played briefly 85 | \item \textit{skip\_3}: Boolean indicating if most of the track was played 86 | \item \textit{not\_skipped}: Boolean indicating that the track was played in its entirety 87 | \end{enumerate} 88 | The objective of the challenge is limited to predicting just the \textit{skip\_2} behavior. 89 | 90 | Tables 1 to 3 present distributions for some of the features in the dataset\footnote{Owing to the size of the dataset, a random sample of data was used to calculate the distributions for Table 2 and 3}. From Table 2, it can be inferred that the \textit{skip\_2} variable is fairly balanced between the true and false classes. We can also observe, from Table 3, that the skipping behavior remained consistent from track 4. 91 | 92 | The test set distributions of features were found to be very similar to that of the training set. Hence, neither sampling nor other modifications were made to the training set before training the model. 93 | 94 | \begin{table*} 95 | \caption{Distribution of number of tracks in sessions} 96 | \begin{tabular}{l|l|l|l|l|l|l|l|l|l|l|l|} 97 | \cline{2-12} 98 | Number of tracks & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20 \\ \cline{2-12} 99 | Percentage & 8.8\% & 7.7\% & 6.7\% & 5.9\% & 5.2\% & 4.5\% & 4.0\% & 3.5\% & 3.1\% & 2.8\% & 47.7\% \\ \cline{2-12} 100 | \end{tabular} 101 | \end{table*} 102 | 103 | 104 | \begin{table} 105 | \caption{Overall skipping behavior} 106 | \begin{tabular}{|l|l|} 107 | \hline 108 | Type & True percentage \\ \hline 109 | \textit{skip\_1} & 41.52\% \\ \hline 110 | \textit{skip\_2} & 50.89\% \\ \hline 111 | \textit{skip\_3} & 63.86\% \\ \hline 112 | \textit{not\_skipped} & 34.41\% \\ \hline 113 | \end{tabular} 114 | \end{table} 115 | 116 | \begin{table*} 117 | \caption{"skip\_2 = true" percentage by session position} 118 | \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l|l|} 119 | \hline 120 | 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20 \\ \hline 121 | 37.4 & 46.7 & 49.4 & 51.6 & 52.4 & 53.2 & 53.1 & 53.0 & 52.1 & 50.3 & 50.7 & 51.3 & 51.7 & 52.2 & 52.5 & 53.0 & 53.3 & 53.5 & 53.6 & 53.6 \\ \hline 122 | \end{tabular} 123 | \end{table*} 124 | 125 | 126 | \section{Related Work} 127 | Deep learning based recommendation methods have been extensively studied during recent years \cite{zhang2017deep}. Session-based music recommender systems specifically try to infer user's preferences and context using information from a single session. This differs from \textit{session-aware} systems which use previous interactions of the same user in the recommendation process \cite{quadrana2018sequence}. The current task shares many aspects of session-based music recommender systems. Hence, understanding the approaches that are employed to such systems is useful for the current task. A survey and evaluation of various approaches to Session-based recommendation systems was presented in \cite{ludewig2018evaluation}. Recurrent Neural Networks (RNNs) have been shown to work exceedingly well with sequential modeling tasks \cite{chung2014empirical}. As such, in \cite{hidasi2015session}, a new architecture named GRU4REC that employs Gated Recurrent Units (GRUs) was proposed to predict the probability of subsequent events given a session beginning. A data augmentation technique that improves upon \cite{hidasi2015session} via sequence pre-processing was proposed in \cite{tan2016improved}. To model the changes in user behavior based on context, a new recurrent architecture was proposed in \cite{smirnova2017contextual}. 128 | 129 | 130 | \section{Approach} 131 | \subsection{Modified Encoder-Decoder Architecture} 132 | In 2014, \citet{cho2014learning} proposed the Encoder-Decoder architecture, that consisted of two recurrent neural networks (RNN). The Encoder RNN strives to encode the input sequence into a fixed length representation, and from this representation, the Decoder RNN generates a correct, variable length target sequence. The architecture was proposed for the statistical machine translation, for which it was shown to be a significant improvement over previous methods. 133 | 134 | The current task of sequential skip prediction shares the variable length and the sequential dependency aspects of the statistical machine translation. However, differing significantly from the statistical machine translation task, the current data set contains information about the tracks in the second half. There is a direct one-to-one correspondence between the track and the output skip prediction. In the following sections, We describe a modified Encoder-Decoder architecture that takes advantage of the unique characteristics of the present dataset. 135 | 136 | \subsection{Base transformation of input data} 137 | The raw input feature vector space might not be an ideal representation for processing by the Long Short-Term Memory (LSTM) cells in the model. Hence, a single Fully-Connected (FC) layer was used to transform the user interaction features and other metadata about the session into a higher dimensional representation. Similarly, a separate FC layer was used to process the acoustic and other metadata associated with tracks. Note that the same FC layer mutates tracks from both the first and the second half of the session. Both the FC layers were equipped with the rectification (ReLU) non-linearity. Only the transformed features were used subsequently in the model. 138 | 139 | \subsection{Compact representation of the session} 140 | As shown by \citet{cho2014properties}, Encoder-Decoder architectures exhibit weakness in handling long sentences. The fixed-length vector representation that is transferred from encoder to decoder may not have enough capacity to encode the complicated relationships within the data. Many solutions have been proposed to mitigate this issue \cite{luong2015effective} \cite{vaswani2017attention}. In the current approach, a compact representation of the session is generated to preserve information for use by Decoder. This fixed length vector is then concatenated with each track's features, before being fed into the Encoder or Decoder. 141 | 142 | The track features corresponding to the first half of the session were concatenated with the first half's user interaction features. This was then fed into a Bi-directional Long Short-Term Memory (BiLSTM) network. The final output from this Bi-directional LSTM can be considered to contain aspects such as overall user behavior in the session and user behavior with respect to specific track features within the session. 143 | 144 | During the previous computation, we have only considered the first half of the session. However, we also have the track information for the second half of the session. Usage of track information from both the first and second halves can lead to a better understanding of the nature of the playlist. Hence a second BiLSTM layer was used to transform the long sequence of all the tracks within the session into a fixed length vector. 145 | 146 | The combined output from both the Bi-directional LSTMs can now be considered as a compact representation of all the information that is available to the model as input. 147 | 148 | \begin{figure}[h] 149 | \caption{Computing a fixed vector representation of the session} 150 | \centering 151 | \includegraphics[scale=0.5]{csr.png} 152 | \end{figure} 153 | 154 | \subsection{Encoder} 155 | At every track's prediction, the Decoder now has easy access to a representation of the session from the input. Hence, the only goal of the Encoder currently is to create the initial state for the decoder. The Encoder consists of an FC layer and a subsequent BiLSTM layer. 156 | 157 | \begin{figure}[h] 158 | \caption{Encoder architecture} 159 | \centering 160 | \includegraphics[scale=0.5]{encoder1.png} 161 | \end{figure} 162 | 163 | \subsection{Decoder} 164 | The track features of the second half along with fixed vector representation of the session is first sent to an FC layer with ReLU non-linearity. The purpose of this layer can be seen as a context setting mechanism - the track features are being transformed using the current session as the context. Note that the weights of this FC layer are shared with that of the FC layer from the Encoder. 165 | 166 | The output from the previous layer is now sent to a BiLSTM layer. For the very first track in the second half, the final state from the BiLSTM layer of the encoder is used as the hidden state for this layer. 167 | 168 | Skipping behavior exhibited by the user during the previous track is a significant predictor for the current track. Hence, the output from the Decoder for the previous track is combined with the output from the previous layer. In case of the first track, the actual \textit{skip\_2} value of the last track in the first half is used. This combined vector is sent to an LSTM layer. Finally, the output from the LSTM layer is fed into a Fully Connected layer with Sigmoid non-linearity to generate the prediction. 169 | 170 | \begin{figure}[h] 171 | \caption{Decoder architecture} 172 | \centering 173 | \includegraphics[scale=0.5]{decoder5.png} 174 | \end{figure} 175 | 176 | \section{Model training} 177 | \subsection{Evaluation metric} 178 | For evaluation, Mean Average Accuracy (MAA) was selected as the primary metric for the challenge. Here, the average accuracy is defined as 179 | \[ AA = \sum_{i=1}^T \frac{A(i)L(i)}{T} \] 180 | where: 181 | \begin{itemize} 182 | \item \textit{T} is the number of tracks to be predicted for the given session 183 | \item \textit{A(i)} is the accuracy at position \textit{i} of the sequence 184 | \item \textit{L(i)} is the Boolean indicator for if the \textit{i}'th prediction was correct 185 | \end{itemize} 186 | 187 | The motivation for the metric is the notion that the immediate track's prediction is most important. As a tie-breaking secondary metric, the average accuracy of the first prediction was used. 188 | 189 | \subsection{Loss function and weights} 190 | 191 | \begin{table} 192 | \caption{Average Accuracy values for one simulated sample of length 5} 193 | \begin{tabular}{|l|l|l|} 194 | \cline{1-1} \cline{2-2} \cline{3-3} 195 | Ground truth sequence & Predicted sequence & AA \\ \hline 196 | 1, 1, 1, 1, 1 & 0, 1, 1, 1, 1 & 0.543 \\ \hline 197 | 1, 1, 1, 1, 1 & 1, 0, 1, 1, 1 & 0.643 \\ \hline 198 | 1, 1, 1, 1, 1 & 1, 1, 0, 1, 1 & 0.710 \\ \hline 199 | 1, 1, 1, 1, 1 & 1, 1, 1, 0, 1 & 0.760 \\ \hline 200 | 1, 1, 1, 1, 1 & 1, 1, 1, 1, 0 & 0.800 \\ \hline 201 | \end{tabular} 202 | \end{table} 203 | 204 | Table 4 shows Average Accuracy values for various predictions on a sequence of length 5. As illustrated by the table, a wrong prediction of the first track decreases the AA value by 0.457 whereas an incorrect prediction of the last track would reduce the AA by just 0.2. One way to interpret this is that the first prediction is (0.457/0.2 =) 2.285 times as important as the last prediction in this example. Incorporating this information into the loss function is useful. Hence, session positions were allocated weights in proportion to the decrease in Average Accuracy value when the prediction for that session position alone is incorrect. Log Loss with weights assigned for each session position was used for optimizing the parameters of the model. 205 | 206 | \subsection{Training} 207 | Due to time and resource constraints, we were not able to train the model on the whole data set. Three mutually exclusive sets of sessions were sampled from the data - Training, Validation, and Test. The Model was trained on the training set, using the validation set to determine the stopping point. The parameters were tuned until the loss on validation set plateaued. The third sample - Test set was used to perform a local evaluation of the model. 208 | 209 | \subsection{Results} 210 | Before the results of the proposed method are presented, we introduce the result of a baseline model. The baseline model uses the skipping behavior of the last track in the first half as the prediction for all the tracks in the second half. This model scored 0.537 on MAA and 0.742 on First prediction accuracy. Predictions from the proposed model in this paper resulted in an MAA score of 0.604 and First Prediction accuracy of 0.792 on the hold-out set, thus achieving the seventh position in the competition. 211 | 212 | \section{Future work} 213 | Only around 20\% of the data was used for training the model because of resource constraints. Instead, training the model on 80\% of the data (leaving 20\% of the sessions for validation and test sets) might improve accuracy. 214 | 215 | During the exploration phase, a Random Forest (RF) model was built to predict the first track of the second half. Another RF model was trained to predict the last track in the second half. This model was built using the session log features until the last track, which is unlike the setup of this challenge where session log features are only available for the first half. Both the models achieved similar levels of accuracy. This reveals that fundamentally, user behavior during the end of the second half is not much more variable (and thus not harder to predict) than during the beginning of the second half. If complete data is available until the previous track, then any session position can be predicted with reasonable accuracy. 216 | 217 | In the absence of complete data, we can try to generate predictions for missing features by building a model that predicts those features. Hence if a model was trained to predict all types of user interactions (\textit{skip\_1}, \textit{2}, and \textit{3}, \textit{hist\_user\_behavior\_reason\_start}, and other remaining features), it is possible that the resulting model might be better at predicting \textit{skip\_2}. Similar to the proposed model in this paper, this model can use the previous time step's predictions while predicting the current time step. 218 | 219 | Another option is to employ transfer learning. Transfer learning has been useful in many areas, with one prominent example being the use of ImageNet-trained models\cite{huh2016makes}. As described in the previous paragraph, we can build and train a model to predict all the user interaction features available in the data. Such a model theoretically would have inferred more aspects of the user behavior than a model that is solely trained for \textit{skip\_2} prediction. We can then fine-tune the top layers of this model specifically for \textit{skip\_2} resulting in better \textit{skip\_2} prediction accuracy. 220 | 221 | % 222 | % The acknowledgments section is defined using the "acks" environment (and NOT an unnumbered section). This ensures 223 | % the proper identification of the section in the article metadata, and the consistent spelling of the heading. 224 | \begin{acks} 225 | We want to thank WSDM, Spotify, and CrowdAI for organizing the challenge. Special thanks to Google for providing the coupons for using Google Cloud Compute resources. Considering the large size of the dataset, the coupons were especially helpful. 226 | \end{acks} 227 | 228 | % 229 | % The next two lines define the bibliography style to be used, and the bibliography file. 230 | \bibliographystyle{ACM-Reference-Format} 231 | \bibliography{sample-base} 232 | 233 | \end{document} 234 | -------------------------------------------------------------------------------- /03-train-data-exploration.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Load packages" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import os\n", 17 | "import gc\n", 18 | "import numpy as np\n", 19 | "import pandas as pd\n", 20 | "from glob import glob\n", 21 | "from joblib import delayed, Parallel\n", 22 | "import matplotlib.pyplot as plt\n", 23 | "# import dask.dataframe as dd\n", 24 | "# import dask.array as da\n", 25 | "%matplotlib inline\n", 26 | "pd.set_option('display.max_columns', 500)" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 2, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "ts_files = sorted(glob('./data/training_set/*.csv.gz'))" 36 | ] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": {}, 41 | "source": [ 42 | "# Check if the training data files are sorted" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 4, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "def check_if_file_is_sorted(x):\n", 52 | " ts = pd.read_csv(x)\n", 53 | " original_index = ts.index.values.copy()\n", 54 | " ts.sort_values(['session_id', 'session_position'], inplace=True)\n", 55 | " new_index = ts.index.values.copy()\n", 56 | " is_sorted = np.all(original_index == new_index)\n", 57 | " ts['ts'] = pd.to_datetime(ts.date + ' ' + ts.hour_of_day.astype('str') + ':00:00')\n", 58 | " min_ts = ts.ts.min()\n", 59 | " max_ts = ts.ts.max()\n", 60 | " is_ts_sorted = np.all(ts.ts.values == ts.ts.sort_values().values)\n", 61 | " return (x, is_sorted, min_ts, max_ts, is_ts_sorted)" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": 5, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "tmp = Parallel(14)(delayed(check_if_file_is_sorted)(x) for x in ts_files)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 6, 76 | "metadata": {}, 77 | "outputs": [ 78 | { 79 | "data": { 80 | "text/plain": [ 81 | "660" 82 | ] 83 | }, 84 | "execution_count": 6, 85 | "metadata": {}, 86 | "output_type": "execute_result" 87 | } 88 | ], 89 | "source": [ 90 | "len(tmp)" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": 7, 96 | "metadata": {}, 97 | "outputs": [ 98 | { 99 | "data": { 100 | "text/plain": [ 101 | "{\"\"}" 102 | ] 103 | }, 104 | "execution_count": 7, 105 | "metadata": {}, 106 | "output_type": "execute_result" 107 | } 108 | ], 109 | "source": [ 110 | "set(str(type(x)) for x in tmp)" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": 8, 116 | "metadata": {}, 117 | "outputs": [ 118 | { 119 | "data": { 120 | "text/plain": [ 121 | "('./data/training_set/log_0_20180715_000000000000.csv.gz',\n", 122 | " True,\n", 123 | " Timestamp('2015-09-30 21:00:00'),\n", 124 | " Timestamp('2018-08-22 11:00:00'),\n", 125 | " False)" 126 | ] 127 | }, 128 | "execution_count": 8, 129 | "metadata": {}, 130 | "output_type": "execute_result" 131 | } 132 | ], 133 | "source": [ 134 | "tmp[0]" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": 9, 140 | "metadata": {}, 141 | "outputs": [], 142 | "source": [ 143 | "df = pd.DataFrame.from_records(tmp, columns=[\n", 144 | " 'filepath', 'is_sorted', 'min_ts', 'max_ts', 'is_ts_sorted'])" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": 10, 150 | "metadata": {}, 151 | "outputs": [ 152 | { 153 | "data": { 154 | "text/plain": [ 155 | "True" 156 | ] 157 | }, 158 | "execution_count": 10, 159 | "metadata": {}, 160 | "output_type": "execute_result" 161 | } 162 | ], 163 | "source": [ 164 | "df.is_sorted.all()" 165 | ] 166 | }, 167 | { 168 | "cell_type": "code", 169 | "execution_count": 11, 170 | "metadata": {}, 171 | "outputs": [ 172 | { 173 | "data": { 174 | "text/plain": [ 175 | "Timestamp('1969-12-31 16:00:00')" 176 | ] 177 | }, 178 | "execution_count": 11, 179 | "metadata": {}, 180 | "output_type": "execute_result" 181 | } 182 | ], 183 | "source": [ 184 | "df.min_ts.min()" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": 12, 190 | "metadata": {}, 191 | "outputs": [ 192 | { 193 | "data": { 194 | "text/plain": [ 195 | "Timestamp('2032-05-26 00:00:00')" 196 | ] 197 | }, 198 | "execution_count": 12, 199 | "metadata": {}, 200 | "output_type": "execute_result" 201 | } 202 | ], 203 | "source": [ 204 | "df.max_ts.max()" 205 | ] 206 | }, 207 | { 208 | "cell_type": "code", 209 | "execution_count": 13, 210 | "metadata": {}, 211 | "outputs": [ 212 | { 213 | "data": { 214 | "text/html": [ 215 | "
\n", 216 | "\n", 229 | "\n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | "
filepathis_sortedmin_tsmax_tsis_ts_sorted
370./data/training_set/log_5_20180824_00000000000...True2017-07-01 21:00:002018-10-08 06:00:00False
420./data/training_set/log_6_20180808_00000000000...True1970-01-01 20:00:002018-08-09 12:00:00False
\n", 259 | "
" 260 | ], 261 | "text/plain": [ 262 | " filepath is_sorted \\\n", 263 | "370 ./data/training_set/log_5_20180824_00000000000... True \n", 264 | "420 ./data/training_set/log_6_20180808_00000000000... True \n", 265 | "\n", 266 | " min_ts max_ts is_ts_sorted \n", 267 | "370 2017-07-01 21:00:00 2018-10-08 06:00:00 False \n", 268 | "420 1970-01-01 20:00:00 2018-08-09 12:00:00 False " 269 | ] 270 | }, 271 | "execution_count": 13, 272 | "metadata": {}, 273 | "output_type": "execute_result" 274 | } 275 | ], 276 | "source": [ 277 | "df.sample(2)" 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": 14, 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "del df\n", 287 | "del tmp" 288 | ] 289 | }, 290 | { 291 | "cell_type": "markdown", 292 | "metadata": {}, 293 | "source": [ 294 | "# Check which columns are (nearly) unique per session" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": 15, 300 | "metadata": {}, 301 | "outputs": [], 302 | "source": [ 303 | "ts = pd.read_csv(ts_files[0], dtype='str')" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": 16, 309 | "metadata": {}, 310 | "outputs": [ 311 | { 312 | "data": { 313 | "text/html": [ 314 | "
\n", 315 | "\n", 328 | "\n", 329 | " \n", 330 | " \n", 331 | " \n", 332 | " \n", 333 | " \n", 334 | " \n", 335 | " \n", 336 | " \n", 337 | " \n", 338 | " \n", 339 | " \n", 340 | " \n", 341 | " \n", 342 | " \n", 343 | " \n", 344 | " \n", 345 | " \n", 346 | " \n", 347 | " \n", 348 | " \n", 349 | " \n", 350 | " \n", 351 | " \n", 352 | " \n", 353 | " \n", 354 | " \n", 355 | " \n", 356 | " \n", 357 | " \n", 358 | " \n", 359 | " \n", 360 | " \n", 361 | " \n", 362 | " \n", 363 | " \n", 364 | " \n", 365 | " \n", 366 | " \n", 367 | " \n", 368 | " \n", 369 | " \n", 370 | " \n", 371 | " \n", 372 | " \n", 373 | " \n", 374 | " \n", 375 | " \n", 376 | " \n", 377 | " \n", 378 | " \n", 379 | " \n", 380 | " \n", 381 | " \n", 382 | " \n", 383 | " \n", 384 | " \n", 385 | " \n", 386 | " \n", 387 | " \n", 388 | " \n", 389 | " \n", 390 | " \n", 391 | " \n", 392 | " \n", 393 | " \n", 394 | " \n", 395 | " \n", 396 | " \n", 397 | " \n", 398 | " \n", 399 | " \n", 400 | " \n", 401 | " \n", 402 | " \n", 403 | " \n", 404 | " \n", 405 | " \n", 406 | " \n", 407 | " \n", 408 | " \n", 409 | " \n", 410 | " \n", 411 | " \n", 412 | " \n", 413 | " \n", 414 | " \n", 415 | " \n", 416 | " \n", 417 | " \n", 418 | " \n", 419 | " \n", 420 | " \n", 421 | " \n", 422 | " \n", 423 | " \n", 424 | " \n", 425 | " \n", 426 | " \n", 427 | " \n", 428 | " \n", 429 | " \n", 430 | " \n", 431 | " \n", 432 | " \n", 433 | " \n", 434 | " \n", 435 | " \n", 436 | " \n", 437 | " \n", 438 | " \n", 439 | " \n", 440 | " \n", 441 | " \n", 442 | " \n", 443 | " \n", 444 | " \n", 445 | " \n", 446 | " \n", 447 | " \n", 448 | " \n", 449 | " \n", 450 | " \n", 451 | " \n", 452 | " \n", 453 | " \n", 454 | " \n", 455 | " \n", 456 | " \n", 457 | " \n", 458 | " \n", 459 | " \n", 460 | " \n", 461 | " \n", 462 | " \n", 463 | " \n", 464 | " \n", 465 | " \n", 466 | " \n", 467 | " \n", 468 | " \n", 469 | " \n", 470 | " \n", 471 | " \n", 472 | " \n", 473 | " \n", 474 | " \n", 475 | " \n", 476 | " \n", 477 | "
session_idsession_positionsession_lengthtrack_id_cleanskip_1skip_2skip_3not_skippedcontext_switchno_pause_before_playshort_pause_before_playlong_pause_before_playhist_user_behavior_n_seekfwdhist_user_behavior_n_seekbackhist_user_behavior_is_shufflehour_of_daydatepremiumcontext_typehist_user_behavior_reason_starthist_user_behavior_reason_end
00_00006f66-33e5-4de7-a324-2d18e439fc1e120t_0479f24c-27d2-46d6-a00c-7ec928f2b539falsefalsefalsetrue000000true162018-07-15trueeditorial_playlisttrackdonetrackdone
10_00006f66-33e5-4de7-a324-2d18e439fc1e220t_9099cd7b-c238-47b7-9381-f23f2c1d1043falsefalsefalsetrue010000true162018-07-15trueeditorial_playlisttrackdonetrackdone
20_00006f66-33e5-4de7-a324-2d18e439fc1e320t_fc5df5ba-5396-49a7-8b29-35d0d28249e0falsefalsefalsetrue010000true162018-07-15trueeditorial_playlisttrackdonetrackdone
30_00006f66-33e5-4de7-a324-2d18e439fc1e420t_23cff8d6-d874-4b20-83dc-94e450e8aa20falsefalsefalsetrue010000true162018-07-15trueeditorial_playlisttrackdonetrackdone
40_00006f66-33e5-4de7-a324-2d18e439fc1e520t_64f3743c-f624-46bb-a579-0f3f9a07a123falsefalsefalsetrue010000true162018-07-15trueeditorial_playlisttrackdonetrackdone
\n", 478 | "
" 479 | ], 480 | "text/plain": [ 481 | " session_id session_position session_length \\\n", 482 | "0 0_00006f66-33e5-4de7-a324-2d18e439fc1e 1 20 \n", 483 | "1 0_00006f66-33e5-4de7-a324-2d18e439fc1e 2 20 \n", 484 | "2 0_00006f66-33e5-4de7-a324-2d18e439fc1e 3 20 \n", 485 | "3 0_00006f66-33e5-4de7-a324-2d18e439fc1e 4 20 \n", 486 | "4 0_00006f66-33e5-4de7-a324-2d18e439fc1e 5 20 \n", 487 | "\n", 488 | " track_id_clean skip_1 skip_2 skip_3 not_skipped \\\n", 489 | "0 t_0479f24c-27d2-46d6-a00c-7ec928f2b539 false false false true \n", 490 | "1 t_9099cd7b-c238-47b7-9381-f23f2c1d1043 false false false true \n", 491 | "2 t_fc5df5ba-5396-49a7-8b29-35d0d28249e0 false false false true \n", 492 | "3 t_23cff8d6-d874-4b20-83dc-94e450e8aa20 false false false true \n", 493 | "4 t_64f3743c-f624-46bb-a579-0f3f9a07a123 false false false true \n", 494 | "\n", 495 | " context_switch no_pause_before_play short_pause_before_play \\\n", 496 | "0 0 0 0 \n", 497 | "1 0 1 0 \n", 498 | "2 0 1 0 \n", 499 | "3 0 1 0 \n", 500 | "4 0 1 0 \n", 501 | "\n", 502 | " long_pause_before_play hist_user_behavior_n_seekfwd \\\n", 503 | "0 0 0 \n", 504 | "1 0 0 \n", 505 | "2 0 0 \n", 506 | "3 0 0 \n", 507 | "4 0 0 \n", 508 | "\n", 509 | " hist_user_behavior_n_seekback hist_user_behavior_is_shuffle hour_of_day \\\n", 510 | "0 0 true 16 \n", 511 | "1 0 true 16 \n", 512 | "2 0 true 16 \n", 513 | "3 0 true 16 \n", 514 | "4 0 true 16 \n", 515 | "\n", 516 | " date premium context_type hist_user_behavior_reason_start \\\n", 517 | "0 2018-07-15 true editorial_playlist trackdone \n", 518 | "1 2018-07-15 true editorial_playlist trackdone \n", 519 | "2 2018-07-15 true editorial_playlist trackdone \n", 520 | "3 2018-07-15 true editorial_playlist trackdone \n", 521 | "4 2018-07-15 true editorial_playlist trackdone \n", 522 | "\n", 523 | " hist_user_behavior_reason_end \n", 524 | "0 trackdone \n", 525 | "1 trackdone \n", 526 | "2 trackdone \n", 527 | "3 trackdone \n", 528 | "4 trackdone " 529 | ] 530 | }, 531 | "execution_count": 16, 532 | "metadata": {}, 533 | "output_type": "execute_result" 534 | } 535 | ], 536 | "source": [ 537 | "ts.head()" 538 | ] 539 | }, 540 | { 541 | "cell_type": "code", 542 | "execution_count": 17, 543 | "metadata": {}, 544 | "outputs": [ 545 | { 546 | "data": { 547 | "text/plain": [ 548 | "true 1533436\n", 549 | "false 1457173\n", 550 | "Name: skip_2, dtype: int64" 551 | ] 552 | }, 553 | "execution_count": 17, 554 | "metadata": {}, 555 | "output_type": "execute_result" 556 | } 557 | ], 558 | "source": [ 559 | "ts.skip_2.value_counts()" 560 | ] 561 | }, 562 | { 563 | "cell_type": "code", 564 | "execution_count": 18, 565 | "metadata": {}, 566 | "outputs": [ 567 | { 568 | "data": { 569 | "text/plain": [ 570 | "false 1985901\n", 571 | "true 1004708\n", 572 | "Name: not_skipped, dtype: int64" 573 | ] 574 | }, 575 | "execution_count": 18, 576 | "metadata": {}, 577 | "output_type": "execute_result" 578 | } 579 | ], 580 | "source": [ 581 | "ts.not_skipped.value_counts()" 582 | ] 583 | }, 584 | { 585 | "cell_type": "code", 586 | "execution_count": 19, 587 | "metadata": {}, 588 | "outputs": [ 589 | { 590 | "data": { 591 | "text/plain": [ 592 | "False" 593 | ] 594 | }, 595 | "execution_count": 19, 596 | "metadata": {}, 597 | "output_type": "execute_result" 598 | } 599 | ], 600 | "source": [ 601 | "((ts.skip_2 == 'true') == (ts.not_skipped == 'false')).all()" 602 | ] 603 | }, 604 | { 605 | "cell_type": "code", 606 | "execution_count": 20, 607 | "metadata": {}, 608 | "outputs": [ 609 | { 610 | "data": { 611 | "text/plain": [ 612 | "178342" 613 | ] 614 | }, 615 | "execution_count": 20, 616 | "metadata": {}, 617 | "output_type": "execute_result" 618 | } 619 | ], 620 | "source": [ 621 | "len(ts.session_id.unique())" 622 | ] 623 | }, 624 | { 625 | "cell_type": "code", 626 | "execution_count": 21, 627 | "metadata": {}, 628 | "outputs": [ 629 | { 630 | "data": { 631 | "text/plain": [ 632 | "(521578, 2)" 633 | ] 634 | }, 635 | "execution_count": 21, 636 | "metadata": {}, 637 | "output_type": "execute_result" 638 | } 639 | ], 640 | "source": [ 641 | "ts.loc[:, ['session_id', 'hist_user_behavior_reason_end']].drop_duplicates().shape" 642 | ] 643 | }, 644 | { 645 | "cell_type": "code", 646 | "execution_count": 22, 647 | "metadata": {}, 648 | "outputs": [ 649 | { 650 | "data": { 651 | "text/plain": [ 652 | "(554160, 2)" 653 | ] 654 | }, 655 | "execution_count": 22, 656 | "metadata": {}, 657 | "output_type": "execute_result" 658 | } 659 | ], 660 | "source": [ 661 | "ts.loc[:, ['session_id', 'hist_user_behavior_reason_start']].drop_duplicates().shape" 662 | ] 663 | }, 664 | { 665 | "cell_type": "code", 666 | "execution_count": 23, 667 | "metadata": {}, 668 | "outputs": [ 669 | { 670 | "data": { 671 | "text/plain": [ 672 | "(230742, 2)" 673 | ] 674 | }, 675 | "execution_count": 23, 676 | "metadata": {}, 677 | "output_type": "execute_result" 678 | } 679 | ], 680 | "source": [ 681 | "ts.loc[:, ['session_id', 'context_type']].drop_duplicates().shape" 682 | ] 683 | }, 684 | { 685 | "cell_type": "code", 686 | "execution_count": 24, 687 | "metadata": {}, 688 | "outputs": [ 689 | { 690 | "data": { 691 | "text/plain": [ 692 | "(178366, 2)" 693 | ] 694 | }, 695 | "execution_count": 24, 696 | "metadata": {}, 697 | "output_type": "execute_result" 698 | } 699 | ], 700 | "source": [ 701 | "ts.loc[:, ['session_id', 'premium']].drop_duplicates().shape" 702 | ] 703 | }, 704 | { 705 | "cell_type": "code", 706 | "execution_count": 25, 707 | "metadata": {}, 708 | "outputs": [ 709 | { 710 | "data": { 711 | "text/plain": [ 712 | "(181173, 2)" 713 | ] 714 | }, 715 | "execution_count": 25, 716 | "metadata": {}, 717 | "output_type": "execute_result" 718 | } 719 | ], 720 | "source": [ 721 | "ts.loc[:, ['session_id', 'date']].drop_duplicates().shape" 722 | ] 723 | }, 724 | { 725 | "cell_type": "code", 726 | "execution_count": 26, 727 | "metadata": {}, 728 | "outputs": [ 729 | { 730 | "data": { 731 | "text/plain": [ 732 | "(200598, 2)" 733 | ] 734 | }, 735 | "execution_count": 26, 736 | "metadata": {}, 737 | "output_type": "execute_result" 738 | } 739 | ], 740 | "source": [ 741 | "ts.loc[:, ['session_id', 'hist_user_behavior_is_shuffle']].drop_duplicates().shape" 742 | ] 743 | }, 744 | { 745 | "cell_type": "code", 746 | "execution_count": 27, 747 | "metadata": {}, 748 | "outputs": [ 749 | { 750 | "data": { 751 | "text/plain": [ 752 | "(240121, 2)" 753 | ] 754 | }, 755 | "execution_count": 27, 756 | "metadata": {}, 757 | "output_type": "execute_result" 758 | } 759 | ], 760 | "source": [ 761 | "ts.loc[:, ['session_id', 'hist_user_behavior_n_seekback']].drop_duplicates().shape" 762 | ] 763 | }, 764 | { 765 | "cell_type": "code", 766 | "execution_count": 28, 767 | "metadata": {}, 768 | "outputs": [ 769 | { 770 | "data": { 771 | "text/plain": [ 772 | "(232455, 2)" 773 | ] 774 | }, 775 | "execution_count": 28, 776 | "metadata": {}, 777 | "output_type": "execute_result" 778 | } 779 | ], 780 | "source": [ 781 | "ts.loc[:, ['session_id', 'hist_user_behavior_n_seekfwd']].drop_duplicates().shape" 782 | ] 783 | }, 784 | { 785 | "cell_type": "code", 786 | "execution_count": 29, 787 | "metadata": {}, 788 | "outputs": [ 789 | { 790 | "data": { 791 | "text/plain": [ 792 | "(336010, 2)" 793 | ] 794 | }, 795 | "execution_count": 29, 796 | "metadata": {}, 797 | "output_type": "execute_result" 798 | } 799 | ], 800 | "source": [ 801 | "ts.loc[:, ['session_id', 'long_pause_before_play']].drop_duplicates().shape" 802 | ] 803 | }, 804 | { 805 | "cell_type": "code", 806 | "execution_count": 30, 807 | "metadata": {}, 808 | "outputs": [ 809 | { 810 | "data": { 811 | "text/plain": [ 812 | "(325376, 2)" 813 | ] 814 | }, 815 | "execution_count": 30, 816 | "metadata": {}, 817 | "output_type": "execute_result" 818 | } 819 | ], 820 | "source": [ 821 | "ts.loc[:, ['session_id', 'short_pause_before_play']].drop_duplicates().shape" 822 | ] 823 | }, 824 | { 825 | "cell_type": "code", 826 | "execution_count": 31, 827 | "metadata": {}, 828 | "outputs": [ 829 | { 830 | "data": { 831 | "text/plain": [ 832 | "(356655, 2)" 833 | ] 834 | }, 835 | "execution_count": 31, 836 | "metadata": {}, 837 | "output_type": "execute_result" 838 | } 839 | ], 840 | "source": [ 841 | "ts.loc[:, ['session_id', 'no_pause_before_play']].drop_duplicates().shape" 842 | ] 843 | }, 844 | { 845 | "cell_type": "code", 846 | "execution_count": 32, 847 | "metadata": {}, 848 | "outputs": [ 849 | { 850 | "data": { 851 | "text/plain": [ 852 | "(241712, 2)" 853 | ] 854 | }, 855 | "execution_count": 32, 856 | "metadata": {}, 857 | "output_type": "execute_result" 858 | } 859 | ], 860 | "source": [ 861 | "ts.loc[:, ['session_id', 'context_switch']].drop_duplicates().shape" 862 | ] 863 | }, 864 | { 865 | "cell_type": "markdown", 866 | "metadata": {}, 867 | "source": [ 868 | "# Extract session related information" 869 | ] 870 | }, 871 | { 872 | "cell_type": "code", 873 | "execution_count": 33, 874 | "metadata": {}, 875 | "outputs": [ 876 | { 877 | "data": { 878 | "text/plain": [ 879 | "1161" 880 | ] 881 | }, 882 | "execution_count": 33, 883 | "metadata": {}, 884 | "output_type": "execute_result" 885 | } 886 | ], 887 | "source": [ 888 | "gc.collect()" 889 | ] 890 | }, 891 | { 892 | "cell_type": "code", 893 | "execution_count": 34, 894 | "metadata": {}, 895 | "outputs": [], 896 | "source": [ 897 | "def uniq_session_ids(x):\n", 898 | " ts = pd.read_csv(x, dtype='str')\n", 899 | " ts = ts.groupby('session_id')['session_length', 'date', 'premium'].first().reset_index().assign(filepath = x)\n", 900 | " return ts" 901 | ] 902 | }, 903 | { 904 | "cell_type": "code", 905 | "execution_count": 35, 906 | "metadata": {}, 907 | "outputs": [], 908 | "source": [ 909 | "tmp = Parallel(14)(delayed(uniq_session_ids)(x) for x in ts_files)" 910 | ] 911 | }, 912 | { 913 | "cell_type": "code", 914 | "execution_count": 36, 915 | "metadata": {}, 916 | "outputs": [ 917 | { 918 | "data": { 919 | "text/plain": [ 920 | "(124950714, 5)" 921 | ] 922 | }, 923 | "execution_count": 36, 924 | "metadata": {}, 925 | "output_type": "execute_result" 926 | } 927 | ], 928 | "source": [ 929 | "df = pd.concat(tmp)\n", 930 | "df.shape" 931 | ] 932 | }, 933 | { 934 | "cell_type": "code", 935 | "execution_count": 37, 936 | "metadata": {}, 937 | "outputs": [], 938 | "source": [ 939 | "df.to_pickle('./data/all_session_ids.pkl')" 940 | ] 941 | }, 942 | { 943 | "cell_type": "markdown", 944 | "metadata": {}, 945 | "source": [ 946 | "# Distribution of session_length, year and premium" 947 | ] 948 | }, 949 | { 950 | "cell_type": "code", 951 | "execution_count": 38, 952 | "metadata": {}, 953 | "outputs": [ 954 | { 955 | "data": { 956 | "text/plain": [ 957 | "(124950714, 5)" 958 | ] 959 | }, 960 | "execution_count": 38, 961 | "metadata": {}, 962 | "output_type": "execute_result" 963 | } 964 | ], 965 | "source": [ 966 | "df = pd.read_pickle('./data/all_session_ids.pkl.gz')\n", 967 | "df.shape" 968 | ] 969 | }, 970 | { 971 | "cell_type": "code", 972 | "execution_count": 39, 973 | "metadata": {}, 974 | "outputs": [ 975 | { 976 | "data": { 977 | "text/plain": [ 978 | "124950714" 979 | ] 980 | }, 981 | "execution_count": 39, 982 | "metadata": {}, 983 | "output_type": "execute_result" 984 | } 985 | ], 986 | "source": [ 987 | "len(df.session_id.unique())" 988 | ] 989 | }, 990 | { 991 | "cell_type": "code", 992 | "execution_count": 40, 993 | "metadata": {}, 994 | "outputs": [ 995 | { 996 | "data": { 997 | "text/html": [ 998 | "
\n", 999 | "\n", 1012 | "\n", 1013 | " \n", 1014 | " \n", 1015 | " \n", 1016 | " \n", 1017 | " \n", 1018 | " \n", 1019 | " \n", 1020 | " \n", 1021 | " \n", 1022 | " \n", 1023 | " \n", 1024 | " \n", 1025 | " \n", 1026 | " \n", 1027 | " \n", 1028 | " \n", 1029 | " \n", 1030 | " \n", 1031 | " \n", 1032 | " \n", 1033 | " \n", 1034 | " \n", 1035 | " \n", 1036 | " \n", 1037 | " \n", 1038 | " \n", 1039 | " \n", 1040 | " \n", 1041 | " \n", 1042 | " \n", 1043 | " \n", 1044 | " \n", 1045 | " \n", 1046 | " \n", 1047 | " \n", 1048 | " \n", 1049 | " \n", 1050 | " \n", 1051 | " \n", 1052 | " \n", 1053 | " \n", 1054 | " \n", 1055 | " \n", 1056 | " \n", 1057 | " \n", 1058 | " \n", 1059 | " \n", 1060 | " \n", 1061 | " \n", 1062 | " \n", 1063 | " \n", 1064 | " \n", 1065 | "
session_idsession_lengthdatepremiumfilepath
00_00006f66-33e5-4de7-a324-2d18e439fc1e202018-07-15true./data/training_set/log_0_20180715_00000000000...
10_0000a72b-09ac-412f-b452-9b9e79bded8f202018-07-15true./data/training_set/log_0_20180715_00000000000...
20_00010fc5-b79e-4cdf-bc4c-f140d0f99a3a202018-07-15true./data/training_set/log_0_20180715_00000000000...
30_00016a3d-9076-4f67-918f-f29e3ce160dc202018-07-15true./data/training_set/log_0_20180715_00000000000...
40_00018b58-deb8-4f98-ac5e-d7e01b346130112018-07-15true./data/training_set/log_0_20180715_00000000000...
\n", 1066 | "
" 1067 | ], 1068 | "text/plain": [ 1069 | " session_id session_length date premium \\\n", 1070 | "0 0_00006f66-33e5-4de7-a324-2d18e439fc1e 20 2018-07-15 true \n", 1071 | "1 0_0000a72b-09ac-412f-b452-9b9e79bded8f 20 2018-07-15 true \n", 1072 | "2 0_00010fc5-b79e-4cdf-bc4c-f140d0f99a3a 20 2018-07-15 true \n", 1073 | "3 0_00016a3d-9076-4f67-918f-f29e3ce160dc 20 2018-07-15 true \n", 1074 | "4 0_00018b58-deb8-4f98-ac5e-d7e01b346130 11 2018-07-15 true \n", 1075 | "\n", 1076 | " filepath \n", 1077 | "0 ./data/training_set/log_0_20180715_00000000000... \n", 1078 | "1 ./data/training_set/log_0_20180715_00000000000... \n", 1079 | "2 ./data/training_set/log_0_20180715_00000000000... \n", 1080 | "3 ./data/training_set/log_0_20180715_00000000000... \n", 1081 | "4 ./data/training_set/log_0_20180715_00000000000... " 1082 | ] 1083 | }, 1084 | "execution_count": 40, 1085 | "metadata": {}, 1086 | "output_type": "execute_result" 1087 | } 1088 | ], 1089 | "source": [ 1090 | "df.head()" 1091 | ] 1092 | }, 1093 | { 1094 | "cell_type": "code", 1095 | "execution_count": 41, 1096 | "metadata": {}, 1097 | "outputs": [], 1098 | "source": [ 1099 | "df.session_length = df.session_length.astype('int64')" 1100 | ] 1101 | }, 1102 | { 1103 | "cell_type": "code", 1104 | "execution_count": 42, 1105 | "metadata": {}, 1106 | "outputs": [ 1107 | { 1108 | "data": { 1109 | "text/plain": [ 1110 | "10 11025730\n", 1111 | "11 9611839\n", 1112 | "12 8407692\n", 1113 | "13 7344162\n", 1114 | "14 6460309\n", 1115 | "15 5664259\n", 1116 | "16 4994670\n", 1117 | "17 4400713\n", 1118 | "18 3917839\n", 1119 | "19 3477536\n", 1120 | "20 59645965\n", 1121 | "Name: session_length, dtype: int64" 1122 | ] 1123 | }, 1124 | "execution_count": 42, 1125 | "metadata": {}, 1126 | "output_type": "execute_result" 1127 | } 1128 | ], 1129 | "source": [ 1130 | "df.session_length.value_counts().sort_index()" 1131 | ] 1132 | }, 1133 | { 1134 | "cell_type": "code", 1135 | "execution_count": 43, 1136 | "metadata": {}, 1137 | "outputs": [ 1138 | { 1139 | "data": { 1140 | "text/plain": [ 1141 | "10 8.824063\n", 1142 | "11 7.692504\n", 1143 | "12 6.728807\n", 1144 | "13 5.877647\n", 1145 | "14 5.170286\n", 1146 | "15 4.533195\n", 1147 | "16 3.997312\n", 1148 | "17 3.521959\n", 1149 | "18 3.135507\n", 1150 | "19 2.783126\n", 1151 | "20 47.735594\n", 1152 | "Name: session_length, dtype: float64" 1153 | ] 1154 | }, 1155 | "execution_count": 43, 1156 | "metadata": {}, 1157 | "output_type": "execute_result" 1158 | } 1159 | ], 1160 | "source": [ 1161 | "df.session_length.value_counts(normalize=True, sort=False).sort_index()*100" 1162 | ] 1163 | }, 1164 | { 1165 | "cell_type": "code", 1166 | "execution_count": 44, 1167 | "metadata": {}, 1168 | "outputs": [ 1169 | { 1170 | "data": { 1171 | "text/plain": [ 1172 | "true 0.816271\n", 1173 | "false 0.183729\n", 1174 | "Name: premium, dtype: float64" 1175 | ] 1176 | }, 1177 | "execution_count": 44, 1178 | "metadata": {}, 1179 | "output_type": "execute_result" 1180 | } 1181 | ], 1182 | "source": [ 1183 | "df.premium.value_counts(normalize=True)" 1184 | ] 1185 | }, 1186 | { 1187 | "cell_type": "code", 1188 | "execution_count": 45, 1189 | "metadata": {}, 1190 | "outputs": [ 1191 | { 1192 | "data": { 1193 | "text/plain": [ 1194 | "1969 0.0001104\n", 1195 | "1970 0.0001409\n", 1196 | "1972 0.0000008\n", 1197 | "1999 0.0000048\n", 1198 | "2000 0.0000104\n", 1199 | "2008 0.0000016\n", 1200 | "2009 0.0000200\n", 1201 | "2010 0.0000512\n", 1202 | "2011 0.0000160\n", 1203 | "2012 0.0000112\n", 1204 | "2013 0.0000216\n", 1205 | "2014 0.0000448\n", 1206 | "2015 0.0001785\n", 1207 | "2016 0.0002105\n", 1208 | "2017 0.0011100\n", 1209 | "2018 99.9980480\n", 1210 | "2019 0.0000104\n", 1211 | "2031 0.0000008\n", 1212 | "2032 0.0000080\n", 1213 | "Name: date, dtype: object" 1214 | ] 1215 | }, 1216 | "execution_count": 45, 1217 | "metadata": {}, 1218 | "output_type": "execute_result" 1219 | } 1220 | ], 1221 | "source": [ 1222 | "(df.date.str[:4].value_counts(normalize=True, sort=False).sort_index() * 100)\\\n", 1223 | " .apply(lambda x: '%.7f' % x)" 1224 | ] 1225 | }, 1226 | { 1227 | "cell_type": "code", 1228 | "execution_count": null, 1229 | "metadata": {}, 1230 | "outputs": [], 1231 | "source": [] 1232 | } 1233 | ], 1234 | "metadata": { 1235 | "kernelspec": { 1236 | "display_name": "Python 3", 1237 | "language": "python", 1238 | "name": "python3" 1239 | }, 1240 | "language_info": { 1241 | "codemirror_mode": { 1242 | "name": "ipython", 1243 | "version": 3 1244 | }, 1245 | "file_extension": ".py", 1246 | "mimetype": "text/x-python", 1247 | "name": "python", 1248 | "nbconvert_exporter": "python", 1249 | "pygments_lexer": "ipython3", 1250 | "version": "3.6.7" 1251 | }, 1252 | "toc": { 1253 | "base_numbering": 1, 1254 | "nav_menu": {}, 1255 | "number_sections": true, 1256 | "sideBar": true, 1257 | "skip_h1_title": false, 1258 | "title_cell": "Table of Contents", 1259 | "title_sidebar": "Contents", 1260 | "toc_cell": false, 1261 | "toc_position": {}, 1262 | "toc_section_display": true, 1263 | "toc_window_display": true 1264 | } 1265 | }, 1266 | "nbformat": 4, 1267 | "nbformat_minor": 2 1268 | } 1269 | -------------------------------------------------------------------------------- /01-dataset-sample-rows.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import pandas as pd\n", 10 | "pd.set_option('display.max_columns', 500)" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 2, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "def glimpse(df, maxvals=10, maxlen=110):\n", 20 | " print('Shape: ', df.shape)\n", 21 | " \n", 22 | " def pad(y):\n", 23 | " max_len = max([len(x) for x in y])\n", 24 | " return [x.ljust(max_len) for x in y]\n", 25 | " \n", 26 | " # Column Name\n", 27 | " toprnt = pad(df.columns.tolist())\n", 28 | " \n", 29 | " # Column Type\n", 30 | " toprnt = pad([toprnt[i] + ' ' + str(df.iloc[:,i].dtype) for i in range(df.shape[1])])\n", 31 | " \n", 32 | " # Num NAs\n", 33 | " num_nas = [df.iloc[:,i].isnull().sum() for i in range(df.shape[1])]\n", 34 | " num_nas_ratio = [int(round(x*100/df.shape[0])) for x in num_nas]\n", 35 | " num_nas_str = [str(x) + ' (' + str(y) + '%)' for x,y in zip(num_nas, num_nas_ratio)]\n", 36 | " max_len = max([len(x) for x in num_nas_str])\n", 37 | " num_nas_str = [x.rjust(max_len) for x in num_nas_str]\n", 38 | " toprnt = [x + ' ' + y + ' NAs' for x,y in zip(toprnt, num_nas_str)]\n", 39 | " \n", 40 | " # Separator\n", 41 | " toprnt = [x + ' : ' for x in toprnt]\n", 42 | " \n", 43 | " # Values\n", 44 | " toprnt = [toprnt[i] + ', '.join([str(y) for y in df.iloc[:min([maxvals,df.shape[0]]), i]]) for i in range(df.shape[1])]\n", 45 | " \n", 46 | " # Trim to maxlen\n", 47 | " toprnt = [x[:min(maxlen, len(x))] for x in toprnt]\n", 48 | " \n", 49 | " for x in toprnt:\n", 50 | " print(x)" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "# Test set" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 4, 63 | "metadata": {}, 64 | "outputs": [ 65 | { 66 | "name": "stdout", 67 | "output_type": "stream", 68 | "text": [ 69 | "Shape: (3777547, 4)\n", 70 | "session_id object 0 (0%) NAs : 0_00001e52-55c0-470c-8d32-85c691c2019a, 0_00001e52-55c0-470c-8d32-85c691c\n", 71 | "track_id_clean object 0 (0%) NAs : t_2e6b3753-5b16-4aa2-97f8-c77a81377139, t_fb588cbd-afee-4155-86a4-f871594\n", 72 | "session_position int64 0 (0%) NAs : 9, 10, 11, 12, 13, 14, 15, 16, 11, 12\n", 73 | "session_length int64 0 (0%) NAs : 16, 16, 16, 16, 16, 16, 16, 16, 20, 20\n" 74 | ] 75 | } 76 | ], 77 | "source": [ 78 | "glimpse(pd.read_csv('./data/test_set/log_input_20180715_000000000000.csv.gz'))" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 5, 84 | "metadata": {}, 85 | "outputs": [ 86 | { 87 | "name": "stdout", 88 | "output_type": "stream", 89 | "text": [ 90 | "Shape: (3673820, 21)\n", 91 | "session_id object 0 (0%) NAs : 0_00001e52-55c0-470c-8d32-85c691c2019a, 0_00001e52-55c0-47\n", 92 | "session_position int64 0 (0%) NAs : 1, 2, 3, 4, 5, 6, 7, 8, 1, 2\n", 93 | "session_length int64 0 (0%) NAs : 16, 16, 16, 16, 16, 16, 16, 16, 20, 20\n", 94 | "track_id_clean object 0 (0%) NAs : t_a0b2a533-caad-4a72-af14-e647bd7e9c1f, t_a998907c-e11c-4a\n", 95 | "skip_1 bool 0 (0%) NAs : False, False, False, False, True, False, False, False, Tru\n", 96 | "skip_2 bool 0 (0%) NAs : True, False, False, True, True, True, False, True, True, F\n", 97 | "skip_3 bool 0 (0%) NAs : True, True, False, True, True, True, True, True, True, Fal\n", 98 | "not_skipped bool 0 (0%) NAs : False, False, True, False, False, False, False, False, Fal\n", 99 | "context_switch int64 0 (0%) NAs : 0, 1, 0, 0, 0, 0, 0, 0, 0, 0\n", 100 | "no_pause_before_play int64 0 (0%) NAs : 0, 1, 0, 0, 1, 0, 0, 1, 0, 1\n", 101 | "short_pause_before_play int64 0 (0%) NAs : 0, 0, 0, 1, 0, 1, 0, 0, 0, 0\n", 102 | "long_pause_before_play int64 0 (0%) NAs : 0, 0, 1, 1, 0, 1, 1, 0, 0, 0\n", 103 | "hist_user_behavior_n_seekfwd int64 0 (0%) NAs : 1, 0, 0, 0, 0, 0, 0, 0, 0, 0\n", 104 | "hist_user_behavior_n_seekback int64 0 (0%) NAs : 0, 0, 1, 0, 0, 0, 0, 0, 0, 0\n", 105 | "hist_user_behavior_is_shuffle bool 0 (0%) NAs : False, False, False, False, False, False, False, False, Tr\n", 106 | "hour_of_day int64 0 (0%) NAs : 21, 21, 21, 21, 21, 21, 21, 21, 14, 14\n", 107 | "date object 0 (0%) NAs : 2018-07-14, 2018-07-14, 2018-07-14, 2018-07-14, 2018-07-14\n", 108 | "premium bool 0 (0%) NAs : False, False, False, False, False, False, False, False, Tr\n", 109 | "context_type object 0 (0%) NAs : catalog, user_collection, user_collection, user_collection\n", 110 | "hist_user_behavior_reason_start object 0 (0%) NAs : appload, clickrow, clickrow, trackdone, fwdbtn, fwdbtn, cl\n", 111 | "hist_user_behavior_reason_end object 0 (0%) NAs : endplay, endplay, trackdone, fwdbtn, fwdbtn, endplay, fwdb\n" 112 | ] 113 | } 114 | ], 115 | "source": [ 116 | "glimpse(pd.read_csv('./data/test_set/log_prehistory_20180715_000000000000.csv.gz'))" 117 | ] 118 | }, 119 | { 120 | "cell_type": "markdown", 121 | "metadata": {}, 122 | "source": [ 123 | "# Track features" 124 | ] 125 | }, 126 | { 127 | "cell_type": "markdown", 128 | "metadata": {}, 129 | "source": [ 130 | "- track_id: unique identifier\n", 131 | "- duration: length of track in seconds\n", 132 | "- release_year: estimate of year the track was released\n", 133 | "- us_populairty_estimate: estimate of the US popularity percentile of the track as of Oct 12, 2018\n", 134 | "- acousticness: A confidence measure from 0.0 to 1.0 of whether the track is acoustic. 1.0 represents high confidence the track is acoustic.\n", 135 | "- beat_strength: ??\n", 136 | "- bounciness: ??\n", 137 | "- dyn_range_mean: ??\n", 138 | "- energy: Energy is a measure from 0.0 to 1.0 and represents a perceptual measure of intensity and activity. Typically, energetic tracks feel fast, loud, and noisy. For example, death metal has high energy, while a Bach prelude scores low on the scale. Perceptual features contributing to this attribute include dynamic range, perceived loudness, timbre, onset rate, and general entropy.\n", 139 | "- flatness: ??\n", 140 | "- instrumentalness: Predicts whether a track contains no vocals. \"Ooh\" and \"aah\" sounds are treated as instumental in this context. Rap or spoken word tracks are clearly \"vocal\". The closer the instrumentalness value is to 1.0, the greater likelihood the track contains no vocal content. Values above 0.5 are intended to represent instrumental tracks, but confidence is higher as the value approaches 1.0.\n", 141 | "- key: The estimated overall key of the track. Integers map to pitches using standard Pitch Class notation (https://en.wikipedia.org/wiki/Pitch_class). E.g. 0 = C, 1 = C♯/D♭, 2 = D, and so on.\n", 142 | "- liveness: Detects the presence of an audience in the recording. Higher liveness values represent an increased probability that the track was performed live. A value above 0.8 provides strong likelihood that the track is live.\n", 143 | "- loudness: The overall loudness of a track in decibels (dB). Loudness values are averaged across the entire track and are useful for comparing relative loudness of tracks. Loudness is the quality of a sound that is the primary psychological correlate of physical strength (amplitude). Values typical range between -60 and 0 db. \n", 144 | "- mechanism: ??\n", 145 | "- mode: Model indicates the modality (major or minor) of a track, the type of scale from which its melodic content is derived. \n", 146 | "- organism: ??\n", 147 | "- speechiness: Speechiness detects the presence of spoken words in a track. The more exclusively speech-like the recording (e.g. talk show, audio book, poetry), the closer to 1.0 the attribute value. Values above 0.66 describe tracks that are probably made entirely of spoken words. Values between 0.33 and 0.66 describe tracks that may contain both music and speech, either in sections or layered, including such cases as rap music. Values below 0.33 most likely represent music and other non-speech-like tracks. \n", 148 | "- tempo: The overall estimated tempo of a track in beats per minute (BPM). In musical terminology, tempo is the speed or pace of a given piece and derives directly from the average beat duration. \n", 149 | "- time_signature: An estimated overall time signature of a track. The time signature (meter) is a notational convention to specify how many beats are in each bar (or measure).\n", 150 | "- valence: A measure from 0.0 to 1.0 describing the musical positiveness conveyed by a track. Tracks with high valence sound more positive (e.g. happy, cheerful, euphoric), while tracks with low valence sound more negative (e.g. sad, depressed, angry). \n", 151 | "- See https://developer.spotify.com/documentation/web-api/reference/tracks/get-audio-features/\n", 152 | "- acoustic_vector_*: See http://benanne.github.io/2014/08/05/spotify-cnns.html and http://papers.nips.cc/paper/5004-deep-content-based-\n" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": 6, 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "track_features = pd.read_csv('./data/track_features/part-00065-6667ece7-5ba8-45f2-860c-f7cafe499e31-c000.csv.gz')" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": 7, 167 | "metadata": {}, 168 | "outputs": [ 169 | { 170 | "data": { 171 | "text/html": [ 172 | "
\n", 173 | "\n", 186 | "\n", 187 | " \n", 188 | " \n", 189 | " \n", 190 | " \n", 191 | " \n", 192 | " \n", 193 | " \n", 194 | " \n", 195 | " \n", 196 | " \n", 197 | " \n", 198 | " \n", 199 | " \n", 200 | " \n", 201 | " \n", 202 | " \n", 203 | " \n", 204 | " \n", 205 | " \n", 206 | " \n", 207 | " \n", 208 | " \n", 209 | " \n", 210 | " \n", 211 | " \n", 212 | " \n", 213 | " \n", 214 | " \n", 215 | " \n", 216 | " \n", 217 | " \n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | " \n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | " \n", 281 | " \n", 282 | " \n", 283 | " \n", 284 | " \n", 285 | " \n", 286 | " \n", 287 | " \n", 288 | " \n", 289 | " \n", 290 | " \n", 291 | " \n", 292 | " \n", 293 | " \n", 294 | " \n", 295 | " \n", 296 | " \n", 297 | " \n", 298 | " \n", 299 | " \n", 300 | " \n", 301 | " \n", 302 | " \n", 303 | " \n", 304 | " \n", 305 | " \n", 306 | " \n", 307 | " \n", 308 | " \n", 309 | " \n", 310 | " \n", 311 | " \n", 312 | " \n", 313 | " \n", 314 | " \n", 315 | " \n", 316 | " \n", 317 | " \n", 318 | " \n", 319 | " \n", 320 | " \n", 321 | " \n", 322 | " \n", 323 | " \n", 324 | " \n", 325 | " \n", 326 | " \n", 327 | " \n", 328 | " \n", 329 | " \n", 330 | " \n", 331 | " \n", 332 | " \n", 333 | " \n", 334 | " \n", 335 | " \n", 336 | " \n", 337 | " \n", 338 | " \n", 339 | " \n", 340 | " \n", 341 | " \n", 342 | " \n", 343 | " \n", 344 | " \n", 345 | " \n", 346 | " \n", 347 | " \n", 348 | " \n", 349 | " \n", 350 | " \n", 351 | " \n", 352 | " \n", 353 | " \n", 354 | " \n", 355 | " \n", 356 | " \n", 357 | " \n", 358 | " \n", 359 | " \n", 360 | " \n", 361 | " \n", 362 | " \n", 363 | " \n", 364 | " \n", 365 | " \n", 366 | " \n", 367 | " \n", 368 | " \n", 369 | " \n", 370 | " \n", 371 | " \n", 372 | " \n", 373 | " \n", 374 | " \n", 375 | " \n", 376 | " \n", 377 | " \n", 378 | " \n", 379 | " \n", 380 | " \n", 381 | " \n", 382 | " \n", 383 | " \n", 384 | " \n", 385 | " \n", 386 | " \n", 387 | " \n", 388 | " \n", 389 | " \n", 390 | " \n", 391 | " \n", 392 | " \n", 393 | " \n", 394 | " \n", 395 | " \n", 396 | " \n", 397 | " \n", 398 | " \n", 399 | " \n", 400 | " \n", 401 | " \n", 402 | " \n", 403 | " \n", 404 | " \n", 405 | " \n", 406 | " \n", 407 | " \n", 408 | " \n", 409 | " \n", 410 | " \n", 411 | " \n", 412 | " \n", 413 | " \n", 414 | " \n", 415 | " \n", 416 | " \n", 417 | " \n", 418 | " \n", 419 | " \n", 420 | " \n", 421 | " \n", 422 | " \n", 423 | " \n", 424 | " \n", 425 | " \n", 426 | " \n", 427 | " \n", 428 | " \n", 429 | " \n", 430 | " \n", 431 | " \n", 432 | " \n", 433 | " \n", 434 | " \n", 435 | " \n", 436 | " \n", 437 | " \n", 438 | " \n", 439 | "
01234
track_idt_52d899dd-cdde-458d-b37c-05d145da6b49t_52d8a762-dea1-4345-830c-bad7d19a29b8t_52d8a89c-55cf-4a73-9719-66d2e3d9892ct_52d8a901-c97f-4478-86d2-64847b5cecf4t_52d8ad56-d7a9-4493-89e3-fe8e0af2a02b
duration196.64179.29493.4661132.692134
release_year19862014201520102018
us_popularity_estimate94.426898.840594.585492.314998.8441
acousticness0.04112830.003465590.9776110.1668120.283672
beat_strength0.7081030.3103030.3815060.3267710.471132
bounciness0.7619920.4246630.5440870.2569130.595489
danceability0.8176740.4702440.488310.5052340.503046
dyn_range_mean11.37717.737119.334014.612479.69354
energy0.6831460.7755330.02777480.9446170.811545
flatness0.9976151.008451.068490.9084810.961257
instrumentalness0.005300260.0300340.9175920.9422381.4554e-14
key119098
liveness0.07870280.6743040.1151190.07733280.292384
loudness-10.953-5.657-19.689-8.961-5.272
mechanism0.9055560.7676060.20.8577590.287582
modeminormajormajorminormajor
organism0.07283990.1643460.8932310.1550140.542222
speechiness0.03500510.04866110.06367420.05493190.448734
tempo128.346169.67120.052129.973160.117
time_signature44344
valence0.9804630.2641840.2347090.1768850.735359
acoustic_vector_0-0.0152818-0.09744350.8306040.283323-0.964598
acoustic_vector_1-0.0389102-0.0319587-0.715818-0.1373590.255574
acoustic_vector_20.2312980.0469461-0.26032-0.1726330.168999
acoustic_vector_30.225196-0.09805140.2724710.1019120.245326
acoustic_vector_40.402138-0.533764-0.400693-0.26147-0.326109
acoustic_vector_5-0.04935440.138756-0.171517-0.110278-0.117049
acoustic_vector_60.342457-0.1177140.1670330.207227-0.57656
acoustic_vector_7-0.3765130.6720620.03826630.2466490.123986
\n", 440 | "
" 441 | ], 442 | "text/plain": [ 443 | " 0 \\\n", 444 | "track_id t_52d899dd-cdde-458d-b37c-05d145da6b49 \n", 445 | "duration 196.64 \n", 446 | "release_year 1986 \n", 447 | "us_popularity_estimate 94.4268 \n", 448 | "acousticness 0.0411283 \n", 449 | "beat_strength 0.708103 \n", 450 | "bounciness 0.761992 \n", 451 | "danceability 0.817674 \n", 452 | "dyn_range_mean 11.3771 \n", 453 | "energy 0.683146 \n", 454 | "flatness 0.997615 \n", 455 | "instrumentalness 0.00530026 \n", 456 | "key 11 \n", 457 | "liveness 0.0787028 \n", 458 | "loudness -10.953 \n", 459 | "mechanism 0.905556 \n", 460 | "mode minor \n", 461 | "organism 0.0728399 \n", 462 | "speechiness 0.0350051 \n", 463 | "tempo 128.346 \n", 464 | "time_signature 4 \n", 465 | "valence 0.980463 \n", 466 | "acoustic_vector_0 -0.0152818 \n", 467 | "acoustic_vector_1 -0.0389102 \n", 468 | "acoustic_vector_2 0.231298 \n", 469 | "acoustic_vector_3 0.225196 \n", 470 | "acoustic_vector_4 0.402138 \n", 471 | "acoustic_vector_5 -0.0493544 \n", 472 | "acoustic_vector_6 0.342457 \n", 473 | "acoustic_vector_7 -0.376513 \n", 474 | "\n", 475 | " 1 \\\n", 476 | "track_id t_52d8a762-dea1-4345-830c-bad7d19a29b8 \n", 477 | "duration 179.294 \n", 478 | "release_year 2014 \n", 479 | "us_popularity_estimate 98.8405 \n", 480 | "acousticness 0.00346559 \n", 481 | "beat_strength 0.310303 \n", 482 | "bounciness 0.424663 \n", 483 | "danceability 0.470244 \n", 484 | "dyn_range_mean 7.73711 \n", 485 | "energy 0.775533 \n", 486 | "flatness 1.00845 \n", 487 | "instrumentalness 0.030034 \n", 488 | "key 9 \n", 489 | "liveness 0.674304 \n", 490 | "loudness -5.657 \n", 491 | "mechanism 0.767606 \n", 492 | "mode major \n", 493 | "organism 0.164346 \n", 494 | "speechiness 0.0486611 \n", 495 | "tempo 169.67 \n", 496 | "time_signature 4 \n", 497 | "valence 0.264184 \n", 498 | "acoustic_vector_0 -0.0974435 \n", 499 | "acoustic_vector_1 -0.0319587 \n", 500 | "acoustic_vector_2 0.0469461 \n", 501 | "acoustic_vector_3 -0.0980514 \n", 502 | "acoustic_vector_4 -0.533764 \n", 503 | "acoustic_vector_5 0.138756 \n", 504 | "acoustic_vector_6 -0.117714 \n", 505 | "acoustic_vector_7 0.672062 \n", 506 | "\n", 507 | " 2 \\\n", 508 | "track_id t_52d8a89c-55cf-4a73-9719-66d2e3d9892c \n", 509 | "duration 93.4661 \n", 510 | "release_year 2015 \n", 511 | "us_popularity_estimate 94.5854 \n", 512 | "acousticness 0.977611 \n", 513 | "beat_strength 0.381506 \n", 514 | "bounciness 0.544087 \n", 515 | "danceability 0.48831 \n", 516 | "dyn_range_mean 9.33401 \n", 517 | "energy 0.0277748 \n", 518 | "flatness 1.06849 \n", 519 | "instrumentalness 0.917592 \n", 520 | "key 0 \n", 521 | "liveness 0.115119 \n", 522 | "loudness -19.689 \n", 523 | "mechanism 0.2 \n", 524 | "mode major \n", 525 | "organism 0.893231 \n", 526 | "speechiness 0.0636742 \n", 527 | "tempo 120.052 \n", 528 | "time_signature 3 \n", 529 | "valence 0.234709 \n", 530 | "acoustic_vector_0 0.830604 \n", 531 | "acoustic_vector_1 -0.715818 \n", 532 | "acoustic_vector_2 -0.26032 \n", 533 | "acoustic_vector_3 0.272471 \n", 534 | "acoustic_vector_4 -0.400693 \n", 535 | "acoustic_vector_5 -0.171517 \n", 536 | "acoustic_vector_6 0.167033 \n", 537 | "acoustic_vector_7 0.0382663 \n", 538 | "\n", 539 | " 3 \\\n", 540 | "track_id t_52d8a901-c97f-4478-86d2-64847b5cecf4 \n", 541 | "duration 132.692 \n", 542 | "release_year 2010 \n", 543 | "us_popularity_estimate 92.3149 \n", 544 | "acousticness 0.166812 \n", 545 | "beat_strength 0.326771 \n", 546 | "bounciness 0.256913 \n", 547 | "danceability 0.505234 \n", 548 | "dyn_range_mean 4.61247 \n", 549 | "energy 0.944617 \n", 550 | "flatness 0.908481 \n", 551 | "instrumentalness 0.942238 \n", 552 | "key 9 \n", 553 | "liveness 0.0773328 \n", 554 | "loudness -8.961 \n", 555 | "mechanism 0.857759 \n", 556 | "mode minor \n", 557 | "organism 0.155014 \n", 558 | "speechiness 0.0549319 \n", 559 | "tempo 129.973 \n", 560 | "time_signature 4 \n", 561 | "valence 0.176885 \n", 562 | "acoustic_vector_0 0.283323 \n", 563 | "acoustic_vector_1 -0.137359 \n", 564 | "acoustic_vector_2 -0.172633 \n", 565 | "acoustic_vector_3 0.101912 \n", 566 | "acoustic_vector_4 -0.26147 \n", 567 | "acoustic_vector_5 -0.110278 \n", 568 | "acoustic_vector_6 0.207227 \n", 569 | "acoustic_vector_7 0.246649 \n", 570 | "\n", 571 | " 4 \n", 572 | "track_id t_52d8ad56-d7a9-4493-89e3-fe8e0af2a02b \n", 573 | "duration 134 \n", 574 | "release_year 2018 \n", 575 | "us_popularity_estimate 98.8441 \n", 576 | "acousticness 0.283672 \n", 577 | "beat_strength 0.471132 \n", 578 | "bounciness 0.595489 \n", 579 | "danceability 0.503046 \n", 580 | "dyn_range_mean 9.69354 \n", 581 | "energy 0.811545 \n", 582 | "flatness 0.961257 \n", 583 | "instrumentalness 1.4554e-14 \n", 584 | "key 8 \n", 585 | "liveness 0.292384 \n", 586 | "loudness -5.272 \n", 587 | "mechanism 0.287582 \n", 588 | "mode major \n", 589 | "organism 0.542222 \n", 590 | "speechiness 0.448734 \n", 591 | "tempo 160.117 \n", 592 | "time_signature 4 \n", 593 | "valence 0.735359 \n", 594 | "acoustic_vector_0 -0.964598 \n", 595 | "acoustic_vector_1 0.255574 \n", 596 | "acoustic_vector_2 0.168999 \n", 597 | "acoustic_vector_3 0.245326 \n", 598 | "acoustic_vector_4 -0.326109 \n", 599 | "acoustic_vector_5 -0.117049 \n", 600 | "acoustic_vector_6 -0.57656 \n", 601 | "acoustic_vector_7 0.123986 " 602 | ] 603 | }, 604 | "execution_count": 7, 605 | "metadata": {}, 606 | "output_type": "execute_result" 607 | } 608 | ], 609 | "source": [ 610 | "track_features.head().T" 611 | ] 612 | }, 613 | { 614 | "cell_type": "markdown", 615 | "metadata": {}, 616 | "source": [ 617 | "# Training set - session logs" 618 | ] 619 | }, 620 | { 621 | "cell_type": "markdown", 622 | "metadata": {}, 623 | "source": [ 624 | "- session_id: unique identifier for the session that this row is a part of\n", 625 | "- session_position: {1-20} - position of row within the session\n", 626 | "- session_length: {10-20} - number of rows in session\n", 627 | "- track_id_clean: unique identifier for the track played. This is linked with track_id in the track features and metadata table.\n", 628 | "- skip_1: Boolean indicating if the track was only played very briefly\n", 629 | "- skip_2: Boolean indicating if the track was only played briefly\n", 630 | "- skip_3: Boolean indicating if most of track was played\n", 631 | "- not_skipped: Boolean indicating that the track was played in its entirety\n", 632 | "- context_switch: Boolean indicating if the user changed context between previous row and the current row. This could for example occur if the user switched from one playlist to another.\n", 633 | "- no_pause_before_play: Boolean indicating if there was no pause between playback of the previous track and this track.\n", 634 | "- short_pause_before_play: Boolean indicating if there was a short pause between playback of the previous track and this track\n", 635 | "- long_pause_before_play: Boolean indicating if there was a long pause between playback of the previous track and this track\n", 636 | "- hist_user_behavior_n_seekfwd: Number of times the user did a seek forward within track\n", 637 | "- hist_user_behavior_n_seekback: Number of times the user did a seek back within track\n", 638 | "- hist_user_behavior_is_shuffle: Boolean indicating if the user encountered this track while shuffle mode was activated\n", 639 | "- hour_of_day: {0-23} - The hour of the day\n", 640 | "- date\n", 641 | "- premium: Boolean indicating if the user was on premium or not. This has potential implications for skipping behavior.\n", 642 | "- context_type: E.g. editorial playlist - what type of context the playback occurred within\n", 643 | "- hist_user_behavior_reason_start: E.g. fwdbtn - the user action which led to the current track being played\n", 644 | "- hist_user_behavior_reason_end: E.g. trackdone - the user action which led to the current track playback ending\n" 645 | ] 646 | }, 647 | { 648 | "cell_type": "code", 649 | "execution_count": 8, 650 | "metadata": {}, 651 | "outputs": [], 652 | "source": [ 653 | "training_set = pd.read_csv('./data/training_set/log_0_20180822_000000000000.csv.gz')" 654 | ] 655 | }, 656 | { 657 | "cell_type": "code", 658 | "execution_count": 9, 659 | "metadata": {}, 660 | "outputs": [ 661 | { 662 | "data": { 663 | "text/html": [ 664 | "
\n", 665 | "\n", 678 | "\n", 679 | " \n", 680 | " \n", 681 | " \n", 682 | " \n", 683 | " \n", 684 | " \n", 685 | " \n", 686 | " \n", 687 | " \n", 688 | " \n", 689 | " \n", 690 | " \n", 691 | " \n", 692 | " \n", 693 | " \n", 694 | " \n", 695 | " \n", 696 | " \n", 697 | " \n", 698 | " \n", 699 | " \n", 700 | " \n", 701 | " \n", 702 | " \n", 703 | " \n", 704 | " \n", 705 | " \n", 706 | " \n", 707 | " \n", 708 | " \n", 709 | " \n", 710 | " \n", 711 | " \n", 712 | " \n", 713 | " \n", 714 | " \n", 715 | " \n", 716 | " \n", 717 | " \n", 718 | " \n", 719 | " \n", 720 | " \n", 721 | " \n", 722 | " \n", 723 | " \n", 724 | " \n", 725 | " \n", 726 | " \n", 727 | " \n", 728 | " \n", 729 | " \n", 730 | " \n", 731 | " \n", 732 | " \n", 733 | " \n", 734 | " \n", 735 | " \n", 736 | " \n", 737 | " \n", 738 | " \n", 739 | " \n", 740 | " \n", 741 | " \n", 742 | " \n", 743 | " \n", 744 | " \n", 745 | " \n", 746 | " \n", 747 | " \n", 748 | " \n", 749 | " \n", 750 | " \n", 751 | " \n", 752 | " \n", 753 | " \n", 754 | " \n", 755 | " \n", 756 | " \n", 757 | " \n", 758 | " \n", 759 | " \n", 760 | " \n", 761 | " \n", 762 | " \n", 763 | " \n", 764 | " \n", 765 | " \n", 766 | " \n", 767 | " \n", 768 | " \n", 769 | " \n", 770 | " \n", 771 | " \n", 772 | " \n", 773 | " \n", 774 | " \n", 775 | " \n", 776 | " \n", 777 | " \n", 778 | " \n", 779 | " \n", 780 | " \n", 781 | " \n", 782 | " \n", 783 | " \n", 784 | " \n", 785 | " \n", 786 | " \n", 787 | " \n", 788 | " \n", 789 | " \n", 790 | " \n", 791 | " \n", 792 | " \n", 793 | " \n", 794 | " \n", 795 | " \n", 796 | " \n", 797 | " \n", 798 | " \n", 799 | " \n", 800 | " \n", 801 | " \n", 802 | " \n", 803 | " \n", 804 | " \n", 805 | " \n", 806 | " \n", 807 | " \n", 808 | " \n", 809 | " \n", 810 | " \n", 811 | " \n", 812 | " \n", 813 | " \n", 814 | " \n", 815 | " \n", 816 | " \n", 817 | " \n", 818 | " \n", 819 | " \n", 820 | " \n", 821 | " \n", 822 | " \n", 823 | " \n", 824 | " \n", 825 | " \n", 826 | " \n", 827 | " \n", 828 | " \n", 829 | " \n", 830 | " \n", 831 | " \n", 832 | " \n", 833 | " \n", 834 | " \n", 835 | " \n", 836 | " \n", 837 | " \n", 838 | " \n", 839 | " \n", 840 | " \n", 841 | " \n", 842 | " \n", 843 | " \n", 844 | " \n", 845 | " \n", 846 | " \n", 847 | " \n", 848 | " \n", 849 | " \n", 850 | " \n", 851 | " \n", 852 | " \n", 853 | " \n", 854 | " \n", 855 | " \n", 856 | " \n", 857 | " \n", 858 | " \n", 859 | "
01234
session_id38_00006771-7eb1-4024-b52f-014b3b7b048838_00006771-7eb1-4024-b52f-014b3b7b048838_00006771-7eb1-4024-b52f-014b3b7b048838_00006771-7eb1-4024-b52f-014b3b7b048838_00006771-7eb1-4024-b52f-014b3b7b0488
session_position12345
session_length1717171717
track_id_cleant_2b723bb2-0a80-450c-b5e9-20d055175256t_889887f2-02b4-4cb7-8207-c7df6b115854t_f36f81cd-c827-43c2-82a0-78bdee27d503t_830a9de3-ddba-44b8-84be-a5472e925bc2t_a1817b44-24c4-4289-bde4-046a1315f28d
skip_1FalseFalseFalseFalseFalse
skip_2FalseFalseFalseFalseFalse
skip_3TrueFalseFalseTrueTrue
not_skippedFalseTrueTrueFalseFalse
context_switch01001
no_pause_before_play01101
short_pause_before_play00010
long_pause_before_play00010
hist_user_behavior_n_seekfwd00000
hist_user_behavior_n_seekback00000
hist_user_behavior_is_shuffleFalseFalseFalseFalseFalse
hour_of_day1111111111
date2018-08-222018-08-222018-08-222018-08-222018-08-22
premiumTrueTrueTrueTrueTrue
context_typecatalogcatalogcatalogcataloguser_collection
hist_user_behavior_reason_starttrackdoneclickrowtrackdonetrackdoneclickrow
hist_user_behavior_reason_endremotetrackdonetrackdoneendplayendplay
\n", 860 | "
" 861 | ], 862 | "text/plain": [ 863 | " 0 \\\n", 864 | "session_id 38_00006771-7eb1-4024-b52f-014b3b7b0488 \n", 865 | "session_position 1 \n", 866 | "session_length 17 \n", 867 | "track_id_clean t_2b723bb2-0a80-450c-b5e9-20d055175256 \n", 868 | "skip_1 False \n", 869 | "skip_2 False \n", 870 | "skip_3 True \n", 871 | "not_skipped False \n", 872 | "context_switch 0 \n", 873 | "no_pause_before_play 0 \n", 874 | "short_pause_before_play 0 \n", 875 | "long_pause_before_play 0 \n", 876 | "hist_user_behavior_n_seekfwd 0 \n", 877 | "hist_user_behavior_n_seekback 0 \n", 878 | "hist_user_behavior_is_shuffle False \n", 879 | "hour_of_day 11 \n", 880 | "date 2018-08-22 \n", 881 | "premium True \n", 882 | "context_type catalog \n", 883 | "hist_user_behavior_reason_start trackdone \n", 884 | "hist_user_behavior_reason_end remote \n", 885 | "\n", 886 | " 1 \\\n", 887 | "session_id 38_00006771-7eb1-4024-b52f-014b3b7b0488 \n", 888 | "session_position 2 \n", 889 | "session_length 17 \n", 890 | "track_id_clean t_889887f2-02b4-4cb7-8207-c7df6b115854 \n", 891 | "skip_1 False \n", 892 | "skip_2 False \n", 893 | "skip_3 False \n", 894 | "not_skipped True \n", 895 | "context_switch 1 \n", 896 | "no_pause_before_play 1 \n", 897 | "short_pause_before_play 0 \n", 898 | "long_pause_before_play 0 \n", 899 | "hist_user_behavior_n_seekfwd 0 \n", 900 | "hist_user_behavior_n_seekback 0 \n", 901 | "hist_user_behavior_is_shuffle False \n", 902 | "hour_of_day 11 \n", 903 | "date 2018-08-22 \n", 904 | "premium True \n", 905 | "context_type catalog \n", 906 | "hist_user_behavior_reason_start clickrow \n", 907 | "hist_user_behavior_reason_end trackdone \n", 908 | "\n", 909 | " 2 \\\n", 910 | "session_id 38_00006771-7eb1-4024-b52f-014b3b7b0488 \n", 911 | "session_position 3 \n", 912 | "session_length 17 \n", 913 | "track_id_clean t_f36f81cd-c827-43c2-82a0-78bdee27d503 \n", 914 | "skip_1 False \n", 915 | "skip_2 False \n", 916 | "skip_3 False \n", 917 | "not_skipped True \n", 918 | "context_switch 0 \n", 919 | "no_pause_before_play 1 \n", 920 | "short_pause_before_play 0 \n", 921 | "long_pause_before_play 0 \n", 922 | "hist_user_behavior_n_seekfwd 0 \n", 923 | "hist_user_behavior_n_seekback 0 \n", 924 | "hist_user_behavior_is_shuffle False \n", 925 | "hour_of_day 11 \n", 926 | "date 2018-08-22 \n", 927 | "premium True \n", 928 | "context_type catalog \n", 929 | "hist_user_behavior_reason_start trackdone \n", 930 | "hist_user_behavior_reason_end trackdone \n", 931 | "\n", 932 | " 3 \\\n", 933 | "session_id 38_00006771-7eb1-4024-b52f-014b3b7b0488 \n", 934 | "session_position 4 \n", 935 | "session_length 17 \n", 936 | "track_id_clean t_830a9de3-ddba-44b8-84be-a5472e925bc2 \n", 937 | "skip_1 False \n", 938 | "skip_2 False \n", 939 | "skip_3 True \n", 940 | "not_skipped False \n", 941 | "context_switch 0 \n", 942 | "no_pause_before_play 0 \n", 943 | "short_pause_before_play 1 \n", 944 | "long_pause_before_play 1 \n", 945 | "hist_user_behavior_n_seekfwd 0 \n", 946 | "hist_user_behavior_n_seekback 0 \n", 947 | "hist_user_behavior_is_shuffle False \n", 948 | "hour_of_day 11 \n", 949 | "date 2018-08-22 \n", 950 | "premium True \n", 951 | "context_type catalog \n", 952 | "hist_user_behavior_reason_start trackdone \n", 953 | "hist_user_behavior_reason_end endplay \n", 954 | "\n", 955 | " 4 \n", 956 | "session_id 38_00006771-7eb1-4024-b52f-014b3b7b0488 \n", 957 | "session_position 5 \n", 958 | "session_length 17 \n", 959 | "track_id_clean t_a1817b44-24c4-4289-bde4-046a1315f28d \n", 960 | "skip_1 False \n", 961 | "skip_2 False \n", 962 | "skip_3 True \n", 963 | "not_skipped False \n", 964 | "context_switch 1 \n", 965 | "no_pause_before_play 1 \n", 966 | "short_pause_before_play 0 \n", 967 | "long_pause_before_play 0 \n", 968 | "hist_user_behavior_n_seekfwd 0 \n", 969 | "hist_user_behavior_n_seekback 0 \n", 970 | "hist_user_behavior_is_shuffle False \n", 971 | "hour_of_day 11 \n", 972 | "date 2018-08-22 \n", 973 | "premium True \n", 974 | "context_type user_collection \n", 975 | "hist_user_behavior_reason_start clickrow \n", 976 | "hist_user_behavior_reason_end endplay " 977 | ] 978 | }, 979 | "execution_count": 9, 980 | "metadata": {}, 981 | "output_type": "execute_result" 982 | } 983 | ], 984 | "source": [ 985 | "training_set.head().T" 986 | ] 987 | }, 988 | { 989 | "cell_type": "code", 990 | "execution_count": null, 991 | "metadata": {}, 992 | "outputs": [], 993 | "source": [] 994 | } 995 | ], 996 | "metadata": { 997 | "kernelspec": { 998 | "display_name": "Python 3", 999 | "language": "python", 1000 | "name": "python3" 1001 | }, 1002 | "language_info": { 1003 | "codemirror_mode": { 1004 | "name": "ipython", 1005 | "version": 3 1006 | }, 1007 | "file_extension": ".py", 1008 | "mimetype": "text/x-python", 1009 | "name": "python", 1010 | "nbconvert_exporter": "python", 1011 | "pygments_lexer": "ipython3", 1012 | "version": "3.6.7" 1013 | }, 1014 | "toc": { 1015 | "base_numbering": 1, 1016 | "nav_menu": {}, 1017 | "number_sections": true, 1018 | "sideBar": true, 1019 | "skip_h1_title": false, 1020 | "title_cell": "Table of Contents", 1021 | "title_sidebar": "Contents", 1022 | "toc_cell": false, 1023 | "toc_position": {}, 1024 | "toc_section_display": true, 1025 | "toc_window_display": false 1026 | } 1027 | }, 1028 | "nbformat": 4, 1029 | "nbformat_minor": 2 1030 | } 1031 | --------------------------------------------------------------------------------