{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\nfigure(num=None, figsize=(20, 10), dpi=80, facecolor='w', edgecolor='k')\nimport seaborn as sns\nfrom tqdm import tqdm\nfrom datetime import datetime\nimport json\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.model_selection import train_test_split, KFold, cross_val_score \nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nfrom sklearn.preprocessing import LabelEncoder, Imputer\nfrom sklearn import model_selection, preprocessing, metrics\nimport lightgbm as lgb\n\nfrom plotly import tools\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nfrom scipy.stats import skew \nfrom scipy.special import boxcox1p\nfrom scipy.stats import boxcox_normmax\n# models\nfrom xgboost import XGBRegressor\nimport warnings\n\n# Ignore useless warnings\nwarnings.filterwarnings(action=\"ignore\", message=\"^internal gelsd\")\n\n# Avoid runtime error messages\npd.set_option('display.float_format', lambda x:'%f'%x)\n\n# make notebook's output stable across runs\nnp.random.seed(42)\n\npd.options.mode.chained_assignment = None\npd.options.display.max_columns = 999\n\nimport os\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"#!ls ../input/","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bfdab255f309f4ca9239eaa07f17398e643010a3"},"cell_type":"code","source":"#comando parse_dates: coloca data no formato yyyy-mm-dd\ntrain_df = pd.read_csv(\"../input/elo-merchant-category-recommendation/train.csv\", parse_dates=[\"first_active_month\"])\ntest_df = pd.read_csv(\"../input/elo-merchant-category-recommendation/test.csv\", parse_dates=[\"first_active_month\"])\nprint(\"Número de linhas e colunas no train_df : \",train_df.shape)\nprint(\"Número de linhas e colunas no teste_df : \",test_df.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h2>Análise do arquivo train_df</h1>"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get column names\ncolumn_names = train_df.columns\nprint(column_names)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get column data types\ntrain_df.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Also check if the column is unique\nfor i in column_names:\n  print('{} is unique: {}'.format(i, train_df[i].is_unique))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Check the index values\ntrain_df.index.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a00bb53642516cefacf7159a02e84f0ce26a5d58"},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.isnull().sum().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.describe()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true,"_uuid":"93b6dd9e83e3d762a7dd0ac80efedd94a98defb8"},"cell_type":"code","source":"plt.figure(figsize=(12,8))\nsns.distplot(train_df['target'].values, bins=50, kde=False, color=\"blue\")\nplt.title(\"Histogram of Loyalty score\")\nplt.xlabel('Loyalty score', fontsize=12)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3ac53af6e71346176abafc19666c18d5ee512840"},"cell_type":"markdown","source":"Alguns valores de loyalty estão muito distantes se comparados com outros. Vamos verificar o total desses valores."},{"metadata":{"trusted":true,"_uuid":"9a6b77591f0cd86505e6bcaac84240af09143011"},"cell_type":"code","source":"(train_df['target'] < -30).sum()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0132162b004ec52f5f42c5080886fd932f8aea97"},"cell_type":"markdown","source":"Temos 2207 linhas (quase 1% dos dados), que são diferentes do restante. Conforme a métrica RMSE estes dados tem um importante papel. Então, deve-se ficar atento a eles."},{"metadata":{"_kg_hide-input":true,"trusted":true,"_uuid":"e1bad37ff53af54a0e42f3ab2512e9b7e5615f00"},"cell_type":"code","source":"#agrega todas as datas\ncnt_srs = train_df['first_active_month'].dt.date.value_counts()\n#faz um sort\ncnt_srs = cnt_srs.sort_index() \nplt.figure(figsize=(14,6)) \nsns.barplot(cnt_srs.index, cnt_srs.values, alpha=0.8, color='orange')\nplt.xticks(rotation='vertical')\nplt.xlabel('First active month', fontsize=12)\nplt.ylabel('Número de cartões', fontsize=12)\nplt.title(\"Contagem Número de cartões x first_active_month\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.describe(include='O')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[\"year\"] = train_df[\"first_active_month\"].dt.year\ntrain_df[\"month\"] = train_df[\"first_active_month\"].dt.month\ntest_df[\"year\"] = test_df[\"first_active_month\"].dt.year\ntest_df[\"month\"] = test_df[\"first_active_month\"].dt.month","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df1 = train_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#all_df = pd.concat([train_df,test_df], axis=0, ignore_index=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h2>Análise do arquivo historical_transactions"},{"metadata":{"trusted":true,"_uuid":"ebb27ee19be1dc40b94731d4dcd0ce670aacc86d"},"cell_type":"code","source":"hist_df = pd.read_csv(\"../input/elo-merchant-category-recommendation/historical_transactions.csv\", nrows=5000000)\nhist_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist_df.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#verificar valores nulos\nhist_df.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist_df.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"hist_df['card_id'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"80d9a378203a3cfc75a7a189c66ada9478a6d67e"},"cell_type":"markdown","source":"<h2>Análise do arquivo new_merchant_transactions"},{"metadata":{"trusted":true,"_uuid":"191aed6554c8698d5a0a4b782fe1ed4e5a306a8a"},"cell_type":"code","source":"new_trans_df = pd.read_csv(\"../input/elo-merchant-category-recommendation/new_merchant_transactions.csv\")\nnew_trans_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_trans_df['card_id'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get column data types\nnew_trans_df.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_trans_df.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_trans_df.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_trans_df.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12,8))\nsns.distplot(new_trans_df['purchase_amount'].values, bins=50, kde=False, color=\"blue\")\nplt.title(\"Histogram of purchase_amount\")\nplt.xlabel('purchase_amount', fontsize=12)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_trans_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_trans_df.hist(bins=50, figsize=(20,15))\nplt.tight_layout(pad=0.4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<h2>Join dos arquivos train_df e newTransGr"},{"metadata":{"trusted":true},"cell_type":"code","source":"newTransGr = pd.read_csv(\"../input/newtransgr2/newTransGr2.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"newTransGr.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"newTransGr.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data1 = pd.merge(train_df, newTransGr, on='card_id', how='inner')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data2 = pd.merge(test_df, newTransGr, on='card_id', how='inner')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#all_datax = pd.merge(all_df, newTransGr, on='card_id', how='inner')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data1.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data2.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data2.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12,8))\nsns.distplot(newTransGr['purchase_amount'].values, bins=50, kde=False, color=\"blue\")\nplt.title(\"Histogram of listGroup\")\nplt.xlabel('listGroup', fontsize=12)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data1 = all_data1.drop(['card_id'], axis=1)\ntest_card = all_data2['card_id']\nall_data2 = all_data2.drop(['card_id'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data1_dummies = pd.get_dummies(all_data1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data1_dummies.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data2_dummies = pd.get_dummies(all_data2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data1_dummies.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data2_dummies.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data1_dummies = all_data1_dummies.drop(['first_active_month'], axis=1)\n#train_dummies = train_dummies.drop(['target'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_data2_dummies = all_data2_dummies.drop(['first_active_month'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cols_to_use = ['feature_1', 'feature_2', 'feature_3', 'year',\n       'month', 'City_Mode', 'Install_Mode', 'Merch_Mode', 'Mon_mean',\n       'purchase_amount', 'Cat2_Mode', 'State_Mode', 'Subsec_Mode',\n       'Cat1_Mode_N', 'Cat1_Mode_Y', 'Cat3_Mode_A', 'Cat3_Mode_B',\n       'Cat3_Mode_C']\n\ndef run_lgb(train_X, train_y, val_X, val_y, test_X):\n    params = {\n        \"objective\" : \"regression\",\n        \"metric\" : \"rmse\",\n        \"num_leaves\" : 30,\n        \"min_child_weight\" : 50,\n        \"learning_rate\" : 0.05,\n        \"bagging_fraction\" : 0.7,\n        \"feature_fraction\" : 0.7,\n        \"bagging_frequency\" : 5,\n        \"bagging_seed\" : 2018,\n        \"verbosity\" : -1\n    }\n    \n    lgtrain = lgb.Dataset(train_X, label=train_y)\n    lgval = lgb.Dataset(val_X, label=val_y)\n    evals_result = {}\n    model = lgb.train(params, lgtrain, 1000, valid_sets=[lgval], early_stopping_rounds=100, verbose_eval=100, evals_result=evals_result)\n    \n    pred_test_y = model.predict(test_X, num_iteration=model.best_iteration)\n    return pred_test_y, model, evals_result\n\ntrain_X = all_data1_dummies[cols_to_use]\ntest_X = all_data2_dummies[cols_to_use]\ntrain_y = all_data1_dummies['target'].values\n\npred_test = 0\nkf = model_selection.KFold(n_splits=5, random_state=2018, shuffle=True)\nfor dev_index, val_index in kf.split(all_data1_dummies):\n    dev_X, val_X = train_X.loc[dev_index,:], train_X.loc[val_index,:]\n    dev_y, val_y = train_y[dev_index], train_y[val_index]\n    \n    pred_test_tmp, model, evals_result = run_lgb(dev_X, dev_y, val_X, val_y, test_X)\n    pred_test += pred_test_tmp\npred_test /= 5.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#fig, ax = plt.subplots(figsize=(12,10))\n#lgb.plot_importance(model, max_num_features=50, height=0.8, ax=ax)\n#ax.grid(False)\n#plt.title(\"LightGBM - Feature Importance\", fontsize=15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_card = pd.DataFrame({\"card_id\":test_card.values})\ntest_card","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_df = pd.DataFrame({\"card_id\":test_card[\"card_id\"].values})\nsub_df[\"target\"] = pred_test\nprint(sub_df)\nsub_df.to_csv(\"baseline3_lgb.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_df.shape","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}