{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport random\nimport joblib\nimport gc\nimport itertools\nfrom itertools import combinations\n\nimport scipy as sp\nimport numpy as np\nimport pandas as pd\nfrom tqdm.notebook import tqdm\n\nimport lightgbm as lgb\nfrom sklearn.preprocessing import LabelEncoder\nfrom hyperopt import STATUS_OK, Trials, fmin, hp, tpe\nfrom sklearn.model_selection import StratifiedKFold, train_test_split\n\n\npd.set_option('display.width', 1000)\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\nimport warnings; warnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2022-07-24T06:34:38.784242Z","iopub.execute_input":"2022-07-24T06:34:38.785637Z","iopub.status.idle":"2022-07-24T06:34:41.638433Z","shell.execute_reply.started":"2022-07-24T06:34:38.785519Z","shell.execute_reply":"2022-07-24T06:34:41.637442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## train preprocessing function","metadata":{}},{"cell_type":"code","source":"def get_difference(data, num_features):\n    df1 = []\n    customer_ids = []\n    \n    for customer_id, df in tqdm(data.groupby(['customer_ID'])):\n        diff_df1 = df[num_features].diff(1).iloc[[-1]].values.astype(np.float16)#float32をfloat16に変えた\n        df1.append(diff_df1)\n        customer_ids.append(customer_id)\n    \n    df1 = np.concatenate(df1, axis = 0)\n    df1 = pd.DataFrame(df1, columns = [col + '_diff1' for col in df[num_features].columns])\n    df1['customer_ID'] = customer_ids\n    return df1","metadata":{"execution":{"iopub.status.busy":"2022-07-24T06:34:41.641387Z","iopub.execute_input":"2022-07-24T06:34:41.641771Z","iopub.status.idle":"2022-07-24T06:34:41.651725Z","shell.execute_reply.started":"2022-07-24T06:34:41.641744Z","shell.execute_reply":"2022-07-24T06:34:41.650538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_preprocess_traindata(train_, train_labels_):    \n    # 特徴量の指定(customerとS_2以外のすべて):Set feature\n    features = train_.drop(['customer_ID', 'target', 'S_2'], axis = 1).columns.to_list()\n    # カテゴリ変数の指定 : Set Categorical variables\n    cat_features = [\n        \"B_30\",\n        \"B_38\",\n        \"D_114\",\n        \"D_116\",\n        \"D_117\",\n        \"D_120\",\n        \"D_126\",\n        \"D_63\",\n        \"D_64\",\n        \"D_66\",\n        \"D_68\",\n    ]\n    \n    # 数値変数の個数(特徴量の中からカテゴリ変数で指定したものを除く): number of num features\n    num_features = [col for col in features if col not in cat_features]\n    \n    # floatデータのメモリ削減(もともとfloat32だったものをfloat16まで減らす) \n    # reducing memory by casting float32 to float16\n    print('Starting reducing memory. (num feature: cast float32 to float16)')\n    float_cols = list(train_.dtypes[train_.dtypes == 'float32'].index)\n    for col in tqdm(float_cols):\n        train_[col] = train_[col].astype(np.float16)\n    \n    # 特徴量の生成: feature engineering\n    print('Starting training feature engineer...')    \n    train_num_agg = train_.groupby(\"customer_ID\")[num_features].agg(['mean', 'std', 'min', 'max', 'last'])\n    train_num_agg.columns = ['_'.join(x) for x in train_num_agg.columns]\n    train_num_agg.reset_index(inplace = True)\n    train_cat_agg = train_.groupby(\"customer_ID\")[cat_features].agg(['count', 'last', 'nunique'])\n    train_cat_agg.columns = ['_'.join(x) for x in train_cat_agg.columns]\n    train_cat_agg.reset_index(inplace = True)\n    \n    print('Starting reducing memory. (new features:cast 64->8)')\n    # floatデータのメモリ削減(もともとfloat32だったものをfloat16まで減らす)\n    # reducing memory by casting float32 to float16\n    cols = list(train_num_agg.dtypes[train_num_agg.dtypes == 'float64'].index)    \n    for col in tqdm(cols):\n        train_num_agg[col] = train_num_agg[col].astype(np.float16)\n        \n    # intデータのメモリ削減(もともとint32だったものをint8まで減らす)\n    # reducing memory by casting int32 to int8\n    cols = list(train_cat_agg.dtypes[train_cat_agg.dtypes == 'int64'].index)    \n    for col in tqdm(cols):\n        train_cat_agg[col] = train_cat_agg[col].astype(np.int8)\n        \n    print('Starting calculate difference...')\n    train_diff = get_difference(train_, num_features)\n    train_ = train_num_agg.merge(train_cat_agg, how = 'inner', on = 'customer_ID').merge(train_diff, how = 'inner', on = 'customer_ID').merge(train_labels_, how = 'inner', on = 'customer_ID')\n    \n    del train_num_agg, train_cat_agg, train_diff\n    gc.collect()\n    \n    # 保存用にデータを変換(float32->float16)\n    # Cast for saving csv parquet files(float32 to float16)\n    print('Starting reducing memory. (num feature: cast float16 to float32)')\n    float_cols = list(train_.dtypes[train_.dtypes == 'float16'].index)\n    for col in tqdm(float_cols):\n        train_[col] = train_[col].astype(np.float32)\n    \n    print('Saving file ...')\n    train_.to_parquet('train_fe.parquet')\n    print('Finished Saving file.')","metadata":{"execution":{"iopub.status.busy":"2022-07-24T06:34:41.653494Z","iopub.execute_input":"2022-07-24T06:34:41.654221Z","iopub.status.idle":"2022-07-24T06:34:41.676099Z","shell.execute_reply.started":"2022-07-24T06:34:41.654179Z","shell.execute_reply":"2022-07-24T06:34:41.675150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## train data preprocessing","metadata":{}},{"cell_type":"code","source":"train = pd.read_parquet('../input/amex-parquet/train_data.parquet')\ntrain_labels = pd.read_csv('../input/amex-default-prediction/train_labels.csv')","metadata":{"execution":{"iopub.status.busy":"2022-07-24T06:34:41.700092Z","iopub.execute_input":"2022-07-24T06:34:41.700772Z","iopub.status.idle":"2022-07-24T06:35:17.260111Z","shell.execute_reply.started":"2022-07-24T06:34:41.700743Z","shell.execute_reply":"2022-07-24T06:35:17.258738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"read_preprocess_traindata(train, train_labels)\ndel train, train_labels","metadata":{"execution":{"iopub.status.busy":"2022-07-24T06:35:17.261647Z","iopub.execute_input":"2022-07-24T06:35:17.261978Z","iopub.status.idle":"2022-07-24T06:59:06.588857Z","shell.execute_reply.started":"2022-07-24T06:35:17.261948Z","shell.execute_reply":"2022-07-24T06:59:06.586664Z"},"trusted":true},"execution_count":null,"outputs":[]}]}