{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import gc\nimport numpy as np \nimport pandas as pd\nfrom sklearn.model_selection import KFold\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, LSTM, Embedding, Bidirectional, CuDNNLSTM\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.callbacks import EarlyStopping\nplt.style.use('fivethirtyeight') \n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"data = pd.concat([\n       pd.read_csv(\"../input/pageviews/pageviews.csv\", parse_dates=[\"FEC_EVENT\"]),\n       pd.read_csv(\"../input/pageviews_complemento/pageviews_complemento.csv\", parse_dates=[\"FEC_EVENT\"])\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_prev = pd.read_csv(\"../input/conversiones/conversiones.csv\")\ny_train = pd.Series(0, index=sorted(data.USER_ID.unique()))\ny_train.loc[y_prev[y_prev.mes >= 10].USER_ID.unique()] = 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pages = data[data.FEC_EVENT.dt.month < 10].groupby(\"PAGE\").USER_ID.unique()\npages = pages.index[pages.apply(lambda x: y_train.loc[x].mean() / y_train.mean() - 1).abs() > 0.05]\npages_set = set(pages)\npages = data.PAGE.value_counts()\npages = pages.index[(pages > 10) & (pages < pages.iloc[int(pages.shape[0] * 0.1)])]\npages_set = list(pages_set.intersection(pages))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = 500\n\ntrain = data.groupby(\"USER_ID\").apply(lambda x: x[(x.FEC_EVENT.dt.month < 10) & x.PAGE.isin(pages_set)]\\\n                                      .sort_values(\"FEC_EVENT\").PAGE[-history:].values)\ntrain = pad_sequences(train)\ntrain","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom sklearn.metrics import roc_auc_score\n\ndef auroc(y_true, y_pred):\n    return tf.py_func(roc_auc_score, (y_true, y_pred), tf.double)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def getModel():\n    model = Sequential()\n    model.add(Embedding(train.max() + 1, 32, input_length=history))\n    model.add(Bidirectional(CuDNNLSTM(64, return_sequences=True)))\n    model.add(Dropout(0.2))\n    model.add(Bidirectional(CuDNNLSTM(32)))\n    model.add(Dropout(0.2))\n    model.add(Dense(64, activation=\"relu\"))\n    model.add(Dropout(0.2))\n    model.add(Dense(32, activation=\"relu\"))\n    model.add(Dropout(0.2))\n    model.add(Dense(1, activation=\"sigmoid\"))\n    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[auroc])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = getModel()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train, y_train, batch_size=2500, epochs=1000, verbose=1, validation_split=0.1,\n          callbacks=[EarlyStopping(monitor='val_auroc', patience=10, verbose=1, mode='max', restore_best_weights=True)])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = data.groupby(\"USER_ID\").apply(lambda x: x[x.PAGE.isin(pages_set)].sort_values(\"FEC_EVENT\").PAGE[-history:].values)\ntest = pad_sequences(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_probs = []\nfor i in range(10):\n    model = getModel()\n    model.fit(train, y_train, batch_size=1000, epochs=1000, verbose=1,\n                validation_split=0.1,\n                callbacks=[EarlyStopping(monitor='val_auroc', patience=10, verbose=1,\n                                         mode=\"max\", restore_best_weights=True)])\n    \n    test_probs.append(pd.Series(model.predict(test)[:, -1], name=\"fold_\" + str(i)))\n\ntest_probs = pd.concat(test_probs, axis=1).mean(axis=1)\ntest_probs.index.name=\"USER_ID\"\ntest_probs.name=\"SCORE\"\n\ntest_probs.to_csv(\"rnn2_benchmark.zip\", header=True, compression=\"zip\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}