{"cells":[{"metadata":{"_uuid":"5d41b1f1d0a5b2d927742386fb24b0076ff76b5e"},"cell_type":"markdown","source":"**Select Features Before Model Building (LightGBM):**  \nFeature selection methods from  scikit-learn Python library.\n\n1) Feature Importance  \n2)  Recursive Feature Elimination (RFE) "},{"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 os, json\nfrom pandas.io.json import json_normalize\nimport lightgbm as lgb\nfrom sklearn.feature_selection import RFE\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\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# configurations\nFILE_DIR = \"../input\"\nfile_name = \"train.csv\"\nnrows = None\nJSON_COLS_TO_PARSE = ['device', 'geoNetwork', 'totals', 'trafficSource']\nfile_path = os.path.join(FILE_DIR, file_name)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4b48fed0036171b9d8122aa0a449a17c84d66df1"},"cell_type":"code","source":"# data load\ndf = pd.read_csv(file_path,\n    converters={column: json.loads for column in JSON_COLS_TO_PARSE}, \n    dtype={'fullVisitorId': 'str'},  # Important!!\n    nrows=nrows) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"eb8b5f0bbd70c5c0fd3ea7c626c75f4152bb48ab"},"cell_type":"code","source":"df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"94f62c99ca77355dda805058835fcf920df17e06"},"cell_type":"code","source":"#json parsing\nfor cols in JSON_COLS_TO_PARSE:\n    column_as_df = json_normalize(df[cols])\n    column_as_df.columns = [f\"{cols}_{subcolumn}\" for subcolumn in column_as_df.columns]\n    df = df.drop(cols, axis=1).merge(column_as_df, right_index=True, left_index=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"29a15fcbfb72482e5c1144679ef6a9dff1226c49"},"cell_type":"code","source":"df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cd3dfe7a6bb8f9d47851e5fc7eb0945c14edd68c"},"cell_type":"code","source":"# select columns to transform\n\n# numeric cols\nnumeric_cols_to_transform = ['totals_hits'\n                ,'totals_pageviews'\n                ,'visitNumber'\n                ,'totals_newVisits'\n                ,'totals_bounces'\n                ,'totals_transactionRevenue']\n#object cols\nobj_cols_to_transform = list(df.select_dtypes(include=['object', 'bool']).columns)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"scrolled":true,"_uuid":"01c8919ebf9fcf333c50b73e8e52b86966610d31"},"cell_type":"code","source":"# transfer numeric columns as float\ndf[numeric_cols_to_transform] = df[numeric_cols_to_transform].fillna(0)\nfor col in numeric_cols_to_transform:\n    df[col] = df[col].astype('float')\n                        \n# transfer object columns as category cols\nfor col in obj_cols_to_transform:\n    df[col] =  df[col].astype('category').cat.codes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d0096617c34a9e4a198d2a73ec59d21d3eb73df4"},"cell_type":"code","source":"df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bae8221b970ba6b5af989c3d733eb6205ee810b0"},"cell_type":"code","source":"# split train and target variables\ntrain = df.drop('totals_transactionRevenue', axis=1)\ntarget = df.totals_transactionRevenue","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d87e08b594460bc63892e7b43fdac54b3e4427f6"},"cell_type":"markdown","source":"**Feature Importance**"},{"metadata":{"trusted":true,"_uuid":"0da049e6bb22bf80f43452f4cf5ed0489da38ecb"},"cell_type":"code","source":"# Feature importance\n\n#lightGBM model fit\ngbm = lgb.LGBMRegressor()\ngbm.fit(train, target)\ngbm.booster_.feature_importance()\n\n# importance of each attribute\nfea_imp_ = pd.DataFrame({'cols':train.columns, 'fea_imp':gbm.feature_importances_})\nfea_imp_.loc[fea_imp_.fea_imp > 0].sort_values(by=['fea_imp'], ascending = False)\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d5dda83d87afa306d5322034fbfe331648857535"},"cell_type":"markdown","source":"**Recursive Feature Elimination(RFE)**"},{"metadata":{"trusted":true,"_uuid":"5e3094c3aa5abdc9f6b680e294a91a1e5d86f687"},"cell_type":"code","source":"#Recursive Feature Elimination(RFE)\n\n# create the RFE model and select 10 attributes\nrfe = RFE(gbm, 10)\nrfe = rfe.fit(train, target)\n\n# summarize the selection of the attributes\nprint(rfe.support_)\n\n# summarize the ranking of the attributes\nfea_rank_ = pd.DataFrame({'cols':train.columns, 'fea_rank':rfe.ranking_})\nfea_rank_.loc[fea_rank_.fea_rank > 0].sort_values(by=['fea_rank'], ascending = True)\n","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}