{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"scrolled":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport os\nimport random\nimport math\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\n\nfrom learntools.core import binder; binder.bind(globals())\nfrom learntools.embeddings.ex1_embedding_layers import *\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\ninput_dir = '../input/elo-merchant-category-recommendation'\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"54d27119ddf940b728e17c675c9d429d16158b59"},"cell_type":"code","source":"df = pd.read_csv(\"../input/elo-merchant-category-lab/trans_by_card.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7b0a38bf312c97176dc5cf6b5942e76a77c4f5cc"},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"fields = ['card_id', 'authorized_flag', 'merchant_id', 'purchase_amount']\ndf = pd.read_csv(os.path.join(input_dir, 'historical_transactions.csv'), usecols=fields)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0228d0859de1ee251f89f5997f42287307c760a6"},"cell_type":"code","source":"df = df[df['authorized_flag'] == 'Y']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8309c10666155aada63f1b0d1ee06f9ad7dc6a58"},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"98eeb2a5450900e00af1dc61b4f439372ca0728e"},"cell_type":"code","source":"df = df.groupby(['card_id', 'merchant_id']).agg({'authorized_flag':'count',\n                                                 'purchase_amount':'sum'\n                                                }).reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"89103532b5817bb58e7dd93a7599fc907a80924e"},"cell_type":"code","source":"#plt.hist(df.purchase_amount, bins=1000)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4538252cef770945fcfafba002bf9d2839630e28"},"cell_type":"code","source":"merchant_ids = set(df.merchant_id)\nmerchant_dict = dict()\ni = 0\nfor s in merchant_ids:\n    merchant_dict[s] = i\n    i +=1\ndf['merchant_id_numeric'] = df['merchant_id'].apply(lambda x: merchant_dict[x])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0b7408efbee56da4717e19e99c850611d04770b0"},"cell_type":"code","source":"card_ids = set(df.card_id)\ncard_dict = dict()\ni = 0\nfor s in card_ids:\n    card_dict[s] = i\n    i += 1\ndf['card_id_numeric'] = df['card_id'].apply(lambda x: card_dict[x])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cc14dd91dc51375f9ff75039bb96e4bb82499609"},"cell_type":"code","source":"del [card_dict, card_ids, merchant_ids, merchant_dict]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"da93874c99bb04ec85ccebd8b6da32b3716f063b"},"cell_type":"code","source":"#df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5777d84bc93463f25cd0b03c8ea6981a355410fe"},"cell_type":"code","source":"from sklearn import preprocessing\n\nx = np.array(df.purchase_amount) #returns a numpy array\nstandard_scaler = preprocessing.StandardScaler()\nx_scaled = standard_scaler.fit_transform(x.reshape(-1,1))\ndf['y'] = x_scaled","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3a18ea1cd92cb8e9bfeac6b4613be05e94cc1a75"},"cell_type":"code","source":"# Some hyperparameters. (You might want to play with these later)\nLR = .005 # Learning rate\nEPOCHS = 8 # Default number of training epochs (i.e. cycles through the training data)\nhidden_units = (32,4) # Size of our hidden layers\n\ndef build_and_train_model(merchant_embedding_size=8, card_embedding_size=8, verbose=2, epochs=EPOCHS):\n    tf.set_random_seed(1); np.random.seed(1); random.seed(1) # Set seeds for reproducibility\n    card_id_input = keras.Input(shape=(1,), name='card_id_numeric')\n    merchant_id_input = keras.Input(shape=(1,), name='merchant_id_numeric')\n    card_embedded = keras.layers.Embedding(df.card_id_numeric.max()+1, card_embedding_size, \n                                       input_length=1, name='card_embedding')(card_id_input)\n    merchant_embedded = keras.layers.Embedding(df.merchant_id_numeric.max()+1, merchant_embedding_size, \n                                        input_length=1, name='merchant_embedding')(merchant_id_input)\n    bias_embedded = keras.layers.Embedding(df.merchant_id_numeric.max()+1, 1, input_length=1, name='bias',\n                                      )(merchant_id_input)\n    concatenated = keras.layers.Concatenate()([card_embedded, merchant_embedded])\n    out = keras.layers.Flatten()(concatenated)\n\n    # Add one or more hidden layers\n    for n_hidden in hidden_units:\n        out = keras.layers.Dense(n_hidden, activation='relu')(out)\n\n    # A single output: our predicted rating\n    out = keras.layers.Dense(1, activation='linear', name='prediction')(out)\n    \n    merchant_bias = keras.layers.Flatten()(bias_embedded)\n\n    out = keras.layers.Add()([out, merchant_bias])\n\n    model = keras.Model(\n        inputs = [card_id_input, merchant_id_input],\n        outputs = out,\n    )\n    model.summary()\n    \n    model.compile(\n        tf.train.AdamOptimizer(LR),\n        loss='MSE',\n        metrics=['MAE'],\n    )\n    history = model.fit(\n        [df.card_id_numeric, df.merchant_id_numeric],\n        df.y,\n        batch_size=5 * 10**3,\n        epochs=epochs,\n        verbose=verbose,\n        validation_split=.15,\n    )\n    return history","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"87e350a986f05d7b3b2a2101479507d781c23bae"},"cell_type":"code","source":"history = build_and_train_model(verbose=1, card_embedding_size=64, merchant_embedding_size=64, epochs=3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5fb1f43af2a93fed2405a06409fb6675f8edde6f"},"cell_type":"code","source":"history_FS = (15, 5)\ndef plot_history(histories, keys=('mean_absolute_error',), train=True, figsize=history_FS):\n    if isinstance(histories, tf.keras.callbacks.History):\n        histories = [ ('', histories) ]\n    for key in keys:\n        plt.figure(figsize=history_FS)\n        for name, history in histories:\n            val = plt.plot(history.epoch, history.history['val_'+key],\n                           '--', label=str(name).title()+' Val')\n            if train:\n                plt.plot(history.epoch, history.history[key], color=val[0].get_color(), alpha=.5,\n                         label=str(name).title()+' Train')\n\n        plt.xlabel('Epochs')\n        plt.ylabel(key.replace('_',' ').title())\n        plt.legend()\n        plt.title(key)\n\n        plt.xlim([0,max(max(history.epoch) for (_, history) in histories)])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ee93e0c685ab61b703b6b5798fec6bd6629dae94"},"cell_type":"code","source":"plot_history([ \n    ('base model', history),\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"09b7e30731d1963fdf247d66eb85aee22ad01e06"},"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.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}