{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","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\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\nLOCAl_TEST = False\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":"########################### Features\n#################################################################################\nremove_columns = [TARGET]\nfeatures_columns = [col for col in list(train_df) if col not in remove_columns]\n\ncategorical_features = [\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]","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":"########################### Catboost Model\nfrom catboost import CatBoostRegressor\n\nmodel_filename = 'catboost'\nmodels = []\n\ncat_params = {\n        'n_estimators': 2000,\n        'learning_rate': 0.1,\n        'eval_metric': 'RMSE',\n        'loss_function': 'RMSE',\n        'random_seed': SEED,\n        'metric_period': 10,\n        'task_type': 'GPU',\n        'depth': 8,\n    }\n\nestimator = CatBoostRegressor(**cat_params)\nestimator.fit(\n            train_df[features_columns], np.log1p(train_df[TARGET]),\n            cat_features=categorical_features,\n            verbose=True)\n\nestimator.save_model(model_filename + '.bin')\nmodels.append(model_filename + '.bin')\n\ndel estimator\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"########################### Predict\n#################################################################################\nif not LOCAl_TEST:\n   \n    # delete train_df\n    del train_df\n\n    # Read test file\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        \n        if 'catboost' in model_path:\n            estimator = CatBoostRegressor()\n            estimator.load_model(model_path)\n        else:\n            estimator = pickle.load(open(model_path, 'rb'))\n\n        predictions = []\n        batch_size = 500000\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":{"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":4,"nbformat_minor":1}