{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true},"cell_type":"code","source":"# General imports\nimport numpy as np\nimport pandas as pd\nimport os, gc, sys, warnings, random, math, psutil, pickle\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import KFold, StratifiedKFold\n\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Helpers\n#################################################################################\n## Seeder\n# :seed to make all processes deterministic     # type: int\ndef seed_everything(seed=0):\n    random.seed(seed)\n    np.random.seed(seed)\n    \n## Simple \"Memory profilers\" to see memory usage\ndef get_memory_usage():\n    return np.round(psutil.Process(os.getpid()).memory_info()[0]/2.**30, 2) \n        \ndef sizeof_fmt(num, suffix='B'):\n    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:\n        if abs(num) < 1024.0:\n            return \"%3.1f%s%s\" % (num, unit, suffix)\n        num /= 1024.0\n    return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\n## Memory Reducer\n# :df pandas dataframe to reduce size             # type: pd.DataFrame()\n# :verbose                                        # type: bool\ndef 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        if col!=TARGET:\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":{"trusted":true},"cell_type":"code","source":"########################### Vars\n#################################################################################\nSEED = 42\nN_SPLITS = 2\nLOCAl_TEST = False\nUSE_EXTERNAL_MODELS = True\nEXTERNAL_PATH = '../input/ashrae-lgbm-external-models/'\n\nif USE_EXTERNAL_MODELS:\n    external_models = []\n    for i in range(N_SPLITS):\n        external_models.append(EXTERNAL_PATH + 'lgbm__fold_' + str(i)  + '.bin')\n    BATCH_SIZE = 500000\nelse:\n    BATCH_SIZE = 2000000\n    \nseed_everything(SEED)\nTARGET = 'meter_reading'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### DATA LOAD\n#################################################################################\nprint('Load Data')\ntrain_df = pd.read_pickle('../input/ashrae-data-minification/train.pkl')\ntest_df = pd.read_pickle('../input/ashrae-data-minification/test.pkl')\n\nbuilding_df = pd.read_pickle('../input/ashrae-data-minification/building_metadata.pkl')\n\ntrain_weather_df = pd.read_pickle('../input/ashrae-data-minification/weather_train.pkl')\ntest_weather_df = pd.read_pickle('../input/ashrae-data-minification/weather_test.pkl')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Remove 0 meter readings for site_id==0\n#################################################################################\ndf = building_df[building_df['site_id']==0]\n\ntrain_df['drop'] = np.where(train_df['DT_D']<=140, 1, 0)\ntrain_df['drop'] = np.where(train_df['building_id'].isin(df['building_id']), train_df['drop'], 0)\n\ntrain_df = train_df[train_df['drop']==0].reset_index(drop=True)\n\ndel df, train_df['drop']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Building DF merge through concat \n#################################################################################\n# Benefits of concat:\n## Faster for huge datasets (columns number)\n## No dtype change for dataset\n## Consume less memmory \n\ntemp_df = train_df[['building_id']]\ntemp_df = temp_df.merge(building_df, on=['building_id'], how='left')\ndel temp_df['building_id']\ntrain_df = pd.concat([train_df, temp_df], axis=1)\n\ntemp_df = test_df[['building_id']]\ntemp_df = temp_df.merge(building_df, on=['building_id'], how='left')\ndel temp_df['building_id']\ntest_df = pd.concat([test_df, temp_df], axis=1)\n\ndel building_df, temp_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Weather DF merge over concat (to not lose type)\n#################################################################################\n# Benefits of concat:\n## Faster for huge datasets (columns number)\n## No dtype change for dataset\n## Consume less memmory \n\ntemp_df = train_df[['site_id','timestamp']]\ntemp_df = temp_df.merge(train_weather_df, on=['site_id','timestamp'], how='left')\ndel temp_df['site_id'], temp_df['timestamp']\ntrain_df = pd.concat([train_df, temp_df], axis=1)\n\ntemp_df = test_df[['site_id','timestamp']]\ntemp_df = temp_df.merge(test_weather_df, on=['site_id','timestamp'], how='left')\ndel temp_df['site_id'], temp_df['timestamp']\ntest_df = pd.concat([test_df, temp_df], axis=1)\n\ndel train_weather_df, test_weather_df, temp_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Delete some columns\n#################################################################################\ndel test_df['row_id']\n\ni_cols = [\n         'timestamp',\n         'DT_D',\n         'DT_day_month',\n         'DT_week_month',\n        ]\n\nfor col in i_cols:\n    try:\n        del train_df[col], test_df[col]\n    except:\n        pass","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Smooth readings\n#################################################################################\ntrain_df['s_uid'] = train_df['site_id'].astype(str) +'_'+\\\n                    train_df['DT_M'].astype(str) +'_'+\\\n                    train_df['meter'].astype(str) +'_'+\\\n                    train_df['primary_use'].astype(str)\n\ntemp_df = train_df.groupby(['s_uid'])[TARGET].apply(lambda x: int(np.percentile(x,99)))\ntemp_df = temp_df.to_dict()\n\ntrain_df['s_uid'] = train_df['s_uid'].map(temp_df)\ntrain_df[TARGET] = np.where(train_df[TARGET]>train_df['s_uid'], train_df['s_uid'], train_df[TARGET])\n\ndel train_df['s_uid'], temp_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Encode Meter\n#################################################################################\n# Building and site id\nfor enc_col in ['building_id', 'site_id']:\n    temp_df = train_df.groupby([enc_col])['meter'].agg(['unique'])\n    temp_df['unique'] = temp_df['unique'].apply(lambda x: '_'.join(str(x))).astype(str)\n\n    le = LabelEncoder()\n    temp_df['unique'] = le.fit_transform(temp_df['unique']).astype(np.int8)\n    temp_df = temp_df['unique'].to_dict()\n\n    train_df[enc_col+'_uid_enc'] = train_df[enc_col].map(temp_df)\n    test_df[enc_col+'_uid_enc'] = test_df[enc_col].map(temp_df)\n    \n    # Nunique\n    temp_dict = train_df.groupby([enc_col])['meter'].agg(['nunique'])['nunique'].to_dict()\n    train_df[enc_col+'-m_nunique'] = train_df[enc_col].map(temp_dict).astype(np.int8)\n    test_df[enc_col+'-m_nunique'] = test_df[enc_col].map(temp_dict).astype(np.int8)\n\ndel temp_df, temp_dict","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Daily temperature\n#################################################################################\nfor df in [train_df, test_df]:\n    df['DT_w_hour'] = np.where((df['DT_hour']>5)&(df['DT_hour']<13),1,0)\n    df['DT_w_hour'] = np.where((df['DT_hour']>12)&(df['DT_hour']<19),2,df['DT_w_hour'])\n    df['DT_w_hour'] = np.where((df['DT_hour']>18),3,df['DT_w_hour'])\n\n    df['DT_w_temp'] = df.groupby(['site_id','DT_W','DT_w_hour'])['air_temperature'].transform('mean')\n    df['DT_w_dew_temp'] = df.groupby(['site_id','DT_W','DT_w_hour'])['dew_temperature'].transform('mean')\n\ni_cols = [\n         'DT_w_hour',\n        ]\n\nfor col in i_cols:\n    del train_df[col], test_df[col]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Reduce memory usage\n#################################################################################\ntrain_df = reduce_mem_usage(train_df)\ntest_df = reduce_mem_usage(test_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Model params\nimport lightgbm as lgb\nlgb_params = {\n                    'objective':'regression',\n                    'boosting_type':'gbdt',\n                    'metric':'rmse',\n                    'n_jobs':-1,\n                    'learning_rate':0.05,\n                    'num_leaves': 2**8,\n                    'max_depth':-1,\n                    'tree_learner':'serial',\n                    'colsample_bytree': 0.9,\n                    'subsample_freq':1,\n                    'subsample':0.5,\n                    'n_estimators':2000,\n                    'max_bin':255,\n                    'verbose':-1,\n                    'seed': SEED,\n                    'early_stopping_rounds':100, \n                } ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Features\n#################################################################################\nremove_columns = [TARGET]\nfeatures_columns = [col for col in list(train_df) if col not in remove_columns]\n\ni_cols = [\n        'building_id',\n        'site_id',\n        'primary_use',\n        'DT_M',\n        'floor_count',\n        'building_id_uid_enc', \n        'site_id_uid_enc',\n]\n\nfor col in i_cols:\n    train_df[col] = train_df[col].astype('category')\n    test_df[col] = test_df[col].astype('category')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Store test_df to HDD and cleanup\n#################################################################################\ntest_df[features_columns].to_pickle('test_df.pkl')\n\ndf = 0\ntemp_df = 0\ntemp_dict = 0\ni_cols = 0\ncol = 0\n\ndel test_df\ndel df, temp_df, temp_dict\ndel col, i_cols\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Check memory usage\n#################################################################################\nfor name, size in sorted(((name, sys.getsizeof(value)) for name,value in locals().items()),\n                         key= lambda x: -x[1])[:10]:\n    print(\"{:>30}: {:>8}\".format(name,sizeof_fmt(size)))\nprint('Memory in Gb', get_memory_usage())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Split groups\n#################################################################################\nsplit_groups = train_df['building_id'].astype(str) +'_'+ train_df['DT_M'].astype(str)\nle = LabelEncoder()\nsplit_groups = le.fit_transform(split_groups).astype(np.int16)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Model\n#################################################################################\n\nif not USE_EXTERNAL_MODELS:\n    # Models saving\n    model_filename = 'lgbm'\n    models = []\n\n    folds = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=SEED)\n\n    for i, (idxT, idxV) in enumerate(folds.split(train_df, split_groups)):\n        print('Fold', i)\n\n        tr_data = lgb.Dataset(train_df.iloc[idxT][features_columns], label=np.log1p(train_df[TARGET][idxT]))\n        vl_data = lgb.Dataset(train_df.iloc[idxV][features_columns], label=np.log1p(train_df[TARGET][idxV]))\n\n        estimator = lgb.train(\n                    lgb_params,\n                    tr_data,\n                    valid_sets = [tr_data,vl_data],\n                    verbose_eval = 100,\n                )\n\n        pickle.dump(estimator, open(model_filename + '__fold_' + str(i)  + '.bin', 'wb'))\n        models.append(model_filename + '__fold_' + str(i)  + '.bin')\n\n    if not LOCAl_TEST:\n        del tr_data, train_df, split_groups\n        gc.collect()\n    \nelse:\n    models = external_models\n    del train_df, split_groups","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Predict\n#################################################################################\nif not LOCAl_TEST:\n    \n    # Load test_df from hdd\n    test_df = pd.read_pickle('test_df.pkl')\n    \n    # Remove test_df from hdd\n    os.system('rm test_df.pkl')\n    \n    # Read submission file\n    submission = pd.read_csv('../input/ashrae-energy-prediction/sample_submission.csv')\n\n    # Remove row_id for a while\n    del submission['row_id']\n    \n    for model_path in models:\n        print('Predictions for', model_path)\n        estimator = pickle.load(open(model_path, 'rb'))\n\n        predictions = []\n        for batch in range(int(len(test_df)/BATCH_SIZE)+1):\n            print('Predicting batch:', batch)\n            predictions += list(np.expm1(estimator.predict(test_df[features_columns].iloc[batch*BATCH_SIZE:(batch+1)*BATCH_SIZE])))\n            \n        submission['meter_reading'] += predictions\n        \n    # Average over models\n    submission['meter_reading'] /= len(models)\n    \n    # Delete test_df\n    del test_df\n     \n    # Fix negative values\n    submission['meter_reading'] = submission['meter_reading'].clip(0,None)\n\n    # Restore row_id\n    submission['row_id'] = submission.index\n    \n    ########################### Check\n    print(submission.iloc[:20])\n    print(submission['meter_reading'].describe())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Export\n#################################################################################\nif not LOCAl_TEST:\n    submission.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"}},"nbformat":4,"nbformat_minor":1}