{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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 numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport lightgbm as lgb\nfrom sklearn.linear_model import Ridge\nimport time\nfrom sklearn import preprocessing\nimport warnings\nimport datetime\nwarnings.filterwarnings(\"ignore\")\nimport gc\nfrom tqdm import tqdm\n\nfrom scipy.stats import describe\n%matplotlib inline\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import mean_squared_error\nimport xgboost as xgb\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\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6d66435363b053ff225d751a326850b0ddb7f593"},"cell_type":"code","source":"def reduce_mem_usage(df, verbose=True):\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() / 1024**2    \n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col_type in numerics:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)    \n    end_mem = df.memory_usage().sum() / 1024**2\n    if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n    return df","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import os\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"0244a95367e8cb020ce7aeff21354f8cbdb09406"},"cell_type":"code","source":"#Loading Train and Test Data\ntrain = pd.read_csv(\"../input/train.csv\", parse_dates=[\"first_active_month\"])\ntest = pd.read_csv(\"../input/test.csv\", parse_dates=[\"first_active_month\"])\nhist_trans = pd.read_csv('../input/historical_transactions.csv')\nnew_merchant_trans = pd.read_csv('../input/new_merchant_transactions.csv')\nprint(\"{} observations and {} features in train set.\".format(train.shape[0],train.shape[1]))\nprint(\"{} observations and {} features in test set.\".format(test.shape[0],test.shape[1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"0c2043a9e32fa232123fb0b903da0ed0b425f095"},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5015b7c5eb5759862a05774ee86bcefd4ba73f98"},"cell_type":"code","source":"for df in [hist_trans,new_merchant_trans]:\n    df['category_2'].fillna(1.0,inplace=True)\n    df['category_3'].fillna('A',inplace=True)\n    df['merchant_id'].fillna('M_ID_00a6ca8a8a',inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7cb159a54f5f439994300b21b94977e6632091f9"},"cell_type":"code","source":"def get_new_columns(name,aggs):\n    return [name + '_' + k + '_' + agg for k in aggs.keys() for agg in aggs[k]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cc3bf90a3b89bd1a15520c89633d2d47dfa8e687"},"cell_type":"code","source":"for df in [hist_trans,new_merchant_trans]:\n    df['purchase_date'] = pd.to_datetime(df['purchase_date'])\n    df['year'] = df['purchase_date'].dt.year\n    df['weekofyear'] = df['purchase_date'].dt.weekofyear\n    df['month'] = df['purchase_date'].dt.month\n    df['dayofweek'] = df['purchase_date'].dt.dayofweek\n    df['weekend'] = (df.purchase_date.dt.weekday >=5).astype(int)\n    df['hour'] = df['purchase_date'].dt.hour\n    df['authorized_flag'] = df['authorized_flag'].map({'Y':1, 'N':0})\n    df['category_1'] = df['category_1'].map({'Y':1, 'N':0}) \n    #https://www.kaggle.com/c/elo-merchant-category-recommendation/discussion/73244\n    df['month_diff'] = ((datetime.datetime.today() - df['purchase_date']).dt.days)//30\n    df['month_diff'] += df['month_lag']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d98d1dc9eb1adaee77a5d43cfb2be50544793de0"},"cell_type":"code","source":"def aggregate(df,name):\n    aggs = {}\n    for col in ['month','hour','weekofyear','dayofweek','year','subsector_id','merchant_id','merchant_category_id']:\n        aggs[col] = ['nunique']\n\n    aggs['purchase_amount'] = ['sum','max','min','mean','var']\n    aggs['installments'] = ['sum','max','min','mean','var']\n    aggs['purchase_date'] = ['max','min']\n    aggs['month_lag'] = ['max','min','mean','var']\n    aggs['month_diff'] = ['mean']\n    aggs['authorized_flag'] = ['sum', 'mean']\n    aggs['weekend'] = ['sum', 'mean']\n    aggs['category_1'] = ['sum', 'mean']\n    aggs['card_id'] = ['size']\n\n    for col in ['category_2','category_3']:\n        df[col+'_mean'] = df.groupby([col])['purchase_amount'].transform('mean')\n        aggs[col+'_mean'] = ['mean'] \n            \n    new_columns = get_new_columns(name,aggs)\n    new_df = df.groupby('card_id').agg(aggs)\n    new_df.columns = new_columns\n    new_df.reset_index(drop=False,inplace=True)\n    new_df[name + '_purchase_date_diff'] = (new_df[name + '_purchase_date_max'] - new_df[name + '_purchase_date_min']).dt.days\n    new_df[name + '_purchase_date_average'] = new_df[name + '_purchase_date_diff']/new_df[name + '_card_id_size']\n    new_df[name + '_purchase_date_uptonow'] = (datetime.datetime.today() - new_df[name + '_purchase_date_max']).dt.days\n    \n    return new_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":false,"_uuid":"6d4d2cf9f7ac398b65e51b0eeec4fd2dc9624c1f"},"cell_type":"code","source":"hist_agged_df = aggregate(hist_trans,'hist');\nnew_hist_agged_df = aggregate(new_merchant_trans,'new_hist');\n\nfor df in [hist_agged_df,new_hist_agged_df]:\n    train = train.merge(df,on='card_id',how='left')\n    test = test.merge(df,on='card_id',how='left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f5b55a49ca1a8dd8d6878b6de79017e229cd8177"},"cell_type":"code","source":"display(train.head())\ndisplay(test.head())\ndisplay(train.describe())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"725454f807b3f9af6687c14770b601367111ba9e"},"cell_type":"code","source":"train['outliers'] = 0\ntrain.loc[train['target'] < -30, 'outliers'] = 1\ntrain['outliers'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ee9f6553b9c316dfb7697871abec70ba54318085"},"cell_type":"code","source":"for df in [train,test]:\n    df['first_active_month'] = pd.to_datetime(df['first_active_month'])\n    df['dayofweek'] = df['first_active_month'].dt.dayofweek\n    df['weekofyear'] = df['first_active_month'].dt.weekofyear\n    df['month'] = df['first_active_month'].dt.month\n    df['elapsed_time'] = (datetime.datetime.today() - df['first_active_month']).dt.days\n    df['hist_first_buy'] = (df['hist_purchase_date_min'] - df['first_active_month']).dt.days\n    df['new_hist_first_buy'] = (df['new_hist_purchase_date_min'] - df['first_active_month']).dt.days\n    for f in ['hist_purchase_date_max','hist_purchase_date_min','new_hist_purchase_date_max',\\\n                     'new_hist_purchase_date_min']:\n        df[f] = df[f].astype(np.int64) * 1e-9\n    df['card_id_total'] = df['new_hist_card_id_size']+df['hist_card_id_size']\n    df['purchase_amount_total'] = df['new_hist_purchase_amount_sum']+df['hist_purchase_amount_sum']\n\nfor f in ['feature_1','feature_2','feature_3']:\n    order_label = train.groupby([f])['outliers'].mean()\n    train[f] = train[f].map(order_label)\n    test[f] = test[f].map(order_label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ee56f9cc4f259cf33eeeb55ded27a3da2faa6e9e"},"cell_type":"code","source":"train_columns = [c for c in train.columns if c not in ['card_id', 'first_active_month','target','outliers']]\ntarget = train['target']\ndel train['target']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"abe5d6961d7adc2f8939591908b5c674f1586948"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1f69b35d4145744f21a9b177c1f7e5a00a381c72","scrolled":false},"cell_type":"code","source":"param = {'num_leaves': 31,\n         'min_data_in_leaf': 30, \n         'objective':'regression',\n         'max_depth': -1,\n         'learning_rate': 0.01,\n         \"min_child_samples\": 20,\n         \"boosting\": \"gbdt\",\n         \"feature_fraction\": 0.9,\n         \"bagging_freq\": 1,\n         \"bagging_fraction\": 0.9 ,\n         \"bagging_seed\": 11,\n         \"metric\": 'rmse',\n         \"lambda_l1\": 0.1,\n         \"verbosity\": -1,\n         \"nthread\": 4,\n         \"random_state\": 4590}\n\noof_lgb_3 = np.zeros(len(train))\npredictions_lgb_3 = np.zeros(len(test))\nstart = time.time()\n\nfolds = StratifiedKFold(n_splits=5, shuffle=True, random_state=15)\n\nfor fold_, (trn_idx, val_idx) in enumerate(folds.split(train,train['outliers'].values)):    \n    print(\"fold n°{}\".format(fold_))\n    trn_data = lgb.Dataset(train.iloc[trn_idx][train_columns], label=target.iloc[trn_idx])\n    val_data = lgb.Dataset(train.iloc[val_idx][train_columns], label=target.iloc[val_idx])\n\n    num_round = 10000\n    clf = lgb.train(param, trn_data, num_round, valid_sets = [trn_data, val_data], verbose_eval=100, early_stopping_rounds = 200)\n    oof_lgb_3[val_idx] = clf.predict(train.iloc[val_idx][train_columns], num_iteration=clf.best_iteration)\n    \n    predictions_lgb_3 += clf.predict(test[train_columns], num_iteration=clf.best_iteration) / folds.n_splits\n\nnp.save('oof_lgb_3', oof_lgb_3)\nnp.save('predictions_lgb_3', predictions_lgb_3)\nprint(\"CV score: {:<8.5f}\".format(mean_squared_error(oof_lgb_3, target)**0.5))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"21a2f2202337b3950b3fb0ddb12eb717837ec41a"},"cell_type":"code","source":"sample_submission = pd.read_csv('../input/sample_submission.csv')\nsample_submission['target'] = predictions_lgb_3\nsample_submission.to_csv('stacker.csv', index=False)","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}