{"cells":[{"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)\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport gc, math\n\nfrom sklearn.preprocessing import LabelEncoder\n\nimport lightgbm as lgb\nfrom tqdm import tqdm\nfrom lightgbm import plot_importance\n\nfrom sklearn.model_selection import KFold\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 all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"%%time\nweather_train_df = pd.read_csv('/kaggle/input/ashrae-energy-prediction/weather_train.csv')\nweather_test_df = pd.read_csv('/kaggle/input/ashrae-energy-prediction/weather_test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Function to reduce the memory usage\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        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\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train_df = reduce_mem_usage(weather_train_df)\nweather_test_df = reduce_mem_usage(weather_test_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Convert timestamp fiels to datetime64\n\ndef convert_to_datetime(df):\n    return df['timestamp'].astype('datetime64[ns]')\n\n\n# Function for extraction timestamp fields such as Year,Month,dat,hour etc...\n\ndef extract_timestamp_fields(df):\n    \n    df['year'] = df['timestamp'].dt.year.astype(np.uint16)\n    df['month'] = df['timestamp'].dt.month.astype(np.uint8)\n    df['hour'] = df['timestamp'].dt.hour.astype(np.uint8)\n    df['day'] = df['timestamp'].dt.day.astype(np.uint8)\n    df['building_age'] = df['timestamp'].dt.year.astype(np.uint16) - df.year_built\n    return df\n\n\n# Cyclic Catagorical Encoding for features month,day,hour,wind direcrtion\n\ndef cyclic_encoder(df,col):\n    if col == 'month':\n        df['sine_' + col] = np.sin(2 * np.pi * (df[col] -1)/max(df[col]))\n        df['cos_' + col] =  np.cos(2 * np.pi * (df[col] -1)/max(df[col]))\n    elif col == 'hour':\n        df['sine_' + col] = np.sin(2 * np.pi * df[col]/24)\n        df['cos_' + col] =  np.cos(2 * np.pi * df[col]/24)\n    elif col == 'day':\n        df['sine_' + col] = np.sin(2 * np.pi * df[col]/max(df[col]))\n        df['cos_' + col] = np.cos(2 * np.pi * df[col]/max(df[col]))\n    else:\n        df['sine_' + col] = np.sin(2 * np.pi * df[col]/360.0)\n        df['cos_' + col] = np.cos(2 * np.pi * df[col]/360.0)\n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train_df['timestamp'] = convert_to_datetime(weather_train_df)\nweather_test_df['timestamp'] = convert_to_datetime(weather_test_df)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Align  timestamp Thanks to Original Author\n# Since site_id is in different time zone w.r.t weather conditions ,therefore we have to align the timestamp on site_id\n\nweather = pd.concat([weather_train_df,weather_test_df],ignore_index=True)\nweather_key = ['site_id','timestamp']\n\ntemp_skeleton = weather[weather_key +['air_temperature']].drop_duplicates(subset=weather_key).sort_values(by=weather_key).copy()\n#temp_skeleton.head()\ntemp_skeleton['temp_rank'] = temp_skeleton.groupby(['site_id',temp_skeleton.timestamp.dt.date])['air_temperature'].rank('average')\ndf_2d = temp_skeleton.groupby(['site_id',temp_skeleton.timestamp.dt.hour])['temp_rank'].mean().unstack(level=1)\nsite_id_offsets = pd.Series(df_2d.values.argmax(axis=1)-14) # temp peak at every 14 hours\nsite_id_offsets.index.name = 'site_id'\nsite_id_offsets.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Function \ndef timestamp_align(df):\n    df['offset'] = df.site_id.map(site_id_offsets)\n    df['timestamp_aligned'] = (df.timestamp - pd.to_timedelta(df.offset,unit='H'))\n    df['timestamp'] = df['timestamp_aligned']\n    del df['timestamp_aligned']\n    return df\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train_df = timestamp_align(weather_train_df)\nweather_test_df  = timestamp_align(weather_test_df)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del weather\ndel df_2d\ndel temp_skeleton\ndel site_id_offsets\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Training DataFrame Preprocessing"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nmetadata_df = pd.read_csv('/kaggle/input/ashrae-energy-prediction/building_metadata.csv')\ntrain_df = pd.read_csv('/kaggle/input/ashrae-energy-prediction/train.csv')\n\nmetadata_df = reduce_mem_usage(metadata_df)\ntrain_df = reduce_mem_usage(train_df)\n\ntrain_df['timestamp'] = convert_to_datetime(train_df)\n\ntrain_df['meter_reading_log1p'] = np.log1p(train_df['meter_reading'])\nmetadata_df['square_feet_log'] = np.log(metadata_df['square_feet'])\n\n# converting primary_use of metadata_df\n\nle = LabelEncoder()\nmetadata_df['primary_use'] = le.fit_transform(metadata_df['primary_use'])\n#metadata_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Merge Train DF with metadata and weather train DF's\ntrain_df = train_df.merge(metadata_df,on=['building_id'],how='left')\ntrain_df_final = train_df.merge(weather_train_df,on=['site_id','timestamp'],how='left')\ntrain_df_final.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df_final.isnull().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"missing_value_cols =['year_built','floor_count',\n                     'air_temperature','cloud_coverage',\n                     'dew_temperature','precip_depth_1_hr',\n                     'sea_level_pressure','wind_direction',\n                     'wind_speed']\n\ndef impute_missing_value(df,missing_value_cols):\n    for c in missing_value_cols:\n        df[c].fillna(df[c].median(),inplace=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Imputing Training data missing column values ....\")\n\nimpute_missing_value(train_df_final,missing_value_cols)\nprint(\"Done!...\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df_final = extract_timestamp_fields(train_df_final)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train_df\ndel weather_train_df\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df_final.columns.tolist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Calling cyclic_encoder for month,day,hour and wind_direction as these features are cyclic in nature\n\ntrain_df_final = cyclic_encoder(train_df_final,'month')\ntrain_df_final = cyclic_encoder(train_df_final,'day')\ntrain_df_final = cyclic_encoder(train_df_final,'hour')\ntrain_df_final = cyclic_encoder(train_df_final,'wind_direction')\ntrain_df_final.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # Cyclic Categorical encoding for Test DF  Later run this \n# test_df_final = cyclic_encoder(test_df_final,'month')\n# test_df_final = cyclic_encoder(test_df_final,'day')\n# test_df_final = cyclic_encoder(test_df_final,'hour')\n# test_df_final = cyclic_encoder(test_df_final,'wind_direction')\n# test_df_final.head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# feature_cols = ['building_id', 'meter', \n#        'site_id', 'primary_use', 'square_feet_log',\n#        'year_built', 'floor_count', 'air_temperature', 'cloud_coverage',\n#        'dew_temperature', 'precip_depth_1_hr', 'sea_level_pressure',\n#        'wind_speed', 'year', 'sine_month','cos_month', 'sine_hour',\n#         'cos_hour', 'sine_wind_direction','cos_wind_direction',\n#         'sine_day', 'cos_day', 'building_age']\n\n# X_train = train_df_final[feature_cols]\n# y_train = train_df_final['meter_reading_log1p']\n\n# X_train.head(),y_train.head()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Let me apply train_test_split for simplicity and get feature importance"},{"metadata":{"trusted":true},"cell_type":"code","source":"# import lightgbm as lgb\n# from tqdm import tqdm\n\n# from sklearn.model_selection import train_test_split\n# print(\"Spliting train and test/validation set...\\n\")\n\n# train_x,valid_x,train_y,valid_y = train_test_split(X_train,y_train,test_size=0.25,random_state=42)\n\n# print(\"Trainin Size :\",train_x.shape,train_y.shape,\"\\n\")\n# print(\"Test/Validation Size:\",valid_x.shape,valid_y.shape)\n\n# print(\"Splitting Done...\")\n# categorical_feats = ['building_id','site_id','meter','primary_use',\n#                      'sine_month','cos_month', 'sine_hour',\n#                      'cos_hour', 'sine_wind_direction',\n#                      'cos_wind_direction','sine_day', 'cos_day',]\n\n# # lgbm params\n# params = {  'boosting_type': 'gbdt',\n#             'objective': 'regression',\n#             'metric': {'rmse'},\n#             'subsample': 0.25,\n#             'subsample_freq': 1,\n#             'learning_rate': 0.01,\n#             'num_leaves': 31,\n#             'feature_fraction': 0.9,\n#             'lambda_l1': 1,\n#             'lambda_l2': 1\n#             }\n\n# #lgb Dataset\n# print(\"Preparing LGB dataset\\n\")\n# d_train = lgb.Dataset(train_x,label=train_y,categorical_feature=categorical_feats)\n# d_valid = lgb.Dataset(valid_x,label=valid_y,categorical_feature=categorical_feats)\n# valid_sets = [d_train,d_valid]\n    \n# print(\"Training LGB ...\")\n# lgb_reg = lgb.train(params,\n#                     train_set=d_train,\n#                     num_boost_round=200,\n#                     valid_sets=valid_sets,\n#                     verbose_eval=20,\n#                     early_stopping_rounds=50)\n    \n# print(\"LGB Training Done!...\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# fig,ax = plt.subplots(figsize=(12,8))\n# plot_importance(lgb_reg,ax=ax)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"feature_cols = ['building_id', 'meter', \n       'site_id', 'primary_use', 'square_feet_log',\n       'year_built', 'floor_count', 'air_temperature', 'cloud_coverage',\n       'dew_temperature', 'precip_depth_1_hr', 'sea_level_pressure',\n       'wind_speed', 'sine_month','cos_month', 'sine_hour',\n        'cos_hour', 'sine_wind_direction','cos_wind_direction',\n        'sine_day', 'cos_day', 'building_age']\n\n\nX_train = train_df_final[feature_cols]\ny_train = train_df_final['meter_reading_log1p']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Shape of X_train and y_train: \",X_train.shape,y_train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train_df_final\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Let me apply KFold of 5 splits\nfolds = 5\nseed = 555\nkf = KFold(n_splits=folds,shuffle=False,random_state=seed)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# lgbm params\nparams = {  'boosting_type': 'gbdt',\n            'objective': 'regression',\n            'metric': {'rmse'},\n            'subsample': 0.25,\n            'subsample_freq': 1,\n            'learning_rate': 0.01,\n            'num_leaves': 31,\n            'feature_fraction': 0.9,\n            'lambda_l1': 1,\n            'lambda_l2': 1\n            }\n\n#X_train[feature_cols].head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Let me split the data and train using lightGBM\n\ncategorical_feats = ['building_id','site_id','meter','primary_use','sine_month',\n                     'cos_month', 'sine_hour','cos_hour', 'sine_wind_direction',\n                     'cos_wind_direction','sine_day', 'cos_day']\nmodels = []\nfor train_idx,valid_idx in kf.split(X_train[feature_cols]):\n    \n    xtrain = X_train.iloc[train_idx]\n    ytrain = y_train.iloc[train_idx]\n    xvalid = X_train.iloc[valid_idx]\n    yvalid = y_train.iloc[valid_idx]\n    \n    print(\"xtrain shape:\",xtrain.shape)\n    print(\"xvalid shape:\",xvalid.shape)\n    print(\"ytrain shape:\",ytrain.shape)\n    print(\"yvalid shape:\",yvalid.shape)\n    \n    #lgb Dataset \n    d_train = lgb.Dataset(xtrain,label=ytrain,categorical_feature=categorical_feats)\n    d_valid = lgb.Dataset(xvalid,label=yvalid,categorical_feature=categorical_feats)\n    valid_sets = [d_train,d_valid]\n    \n    print(\"Training LGB ...\")\n    lgb_reg1 = lgb.train(params,\n                     train_set=d_train,\n                     num_boost_round=400,\n                     valid_sets=valid_sets,\n                     verbose_eval=20,\n                     early_stopping_rounds=100)\n    models.append(lgb_reg1)\n    \n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Testing Dataframe preprocessing\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\ntest_df = pd.read_csv('/kaggle/input/ashrae-energy-prediction/test.csv')\ntest_df = reduce_mem_usage(test_df)\n\nprint(\"Converting timestamp to Datetime type .. \")\ntest_df['timestamp'] = convert_to_datetime(test_df)\nprint(\"Size of test_df:\",test_df.shape)\nprint(\"Merging Test Data sets step 1....\")\ntest_df_final = test_df.merge(metadata_df,on=['building_id'],how='left')\n\nprint(\"Deleting test_df ..\")\ndel test_df\ngc.collect()\nprint(\"Merging Test Data sets step 2 ....\")\ntest_df_final = test_df_final.merge(weather_test_df,on=['site_id','timestamp'],how='left')\n#test_df_final.head()\n\n\n\nprint(\"Missing value imputation ...\")\nimpute_missing_value(test_df_final,missing_value_cols)\n\nprint(\"Extracting timestamp into year,month,day and hour ...\")\ntest_df_final = extract_timestamp_fields(test_df_final)\n\ntest_df_final = reduce_mem_usage(test_df_final)\n\nprint(\"cyclic encoding testing df...\")\ntest_df_final = cyclic_encoder(test_df_final,'month')\ntest_df_final = cyclic_encoder(test_df_final,'day')\ntest_df_final = cyclic_encoder(test_df_final,'hour')\ntest_df_final = cyclic_encoder(test_df_final,'wind_direction')\n\ntest_df_final = reduce_mem_usage(test_df_final)\n\nprint(\"Size of test_df_final:\",test_df_final.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Deleting test_df_final,weater_test_df and metadata_df ...\")\n\ndel metadata_df\ndel weather_test_df\ndel X_train\n#del y_train\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=0\nresult=[]\nstep_size=50000\nfor _ in tqdm(range(int(np.ceil(test_df_final.shape[0]/step_size)))):\n    result.append(np.expm1(sum([model.predict(test_df_final.loc[i:i+step_size-1,feature_cols],num_iteration=model.best_iteration) for model in models])/folds))\n    i+=step_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del test_df_final\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_result = np.concatenate(result)\nlen(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('/kaggle/input/ashrae-energy-prediction/sample_submission.csv')\n\nsubmission.shape\n\nsubmission = reduce_mem_usage(submission)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['meter_reading'] = np.clip(sub_result,0,a_max=None)\nsubmission.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"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}