{"cells":[{"metadata":{},"cell_type":"markdown","source":"<font color='red' align='left'>Work in progress...</font>\n<br><font color='green' align='left'>please upvote if you find notebook useful</font>\n# PROBLEM STATEMENT\n\nIn this competition ask is to develop accurate models of metered building energy usage in the following areas:\n<br>chilled water, electric, hot water and stream meters.\n<br>\n<br>\n\n\n\n<img align=\"left\" src=\"https://github.com/rahul2712/ASHRAE/blob/master/evaluation_matrix.png?raw=true\"></img>\n\n\n\n"},{"metadata":{},"cell_type":"markdown","source":"# SOLUTION APPROACH 1\n- <b>Step1:</b> Analyzing all features individually and along with target features <font color='green'><b>DONE</b></font>\n- <b>Step2:</b> Creating join between train and building metadata. Further join with weather train data. <font color='green'><b>DONE</b></font>\n- <b>Step3:</b> Handle all NULL values and convert all categorical features into numeric equivalents.<font color='green'><b>DONE</b></font>\n- <b>Step4:</b> Replacing NULL values in weather datasets (train/test) with average of train & test values for a given week.<font color='green'><b>DONE</b></font>\n- <b>Step5:</b> Create and save 52 (meter,primary_use combination) x 2 (iterations) = 104  models one for every meter type (0,1,2,3) & primary_use (Education,Office,etc.). Both train and test data have same number of combinations. <font color='green'><b>DONE</b></font>\n- <b>Step6:</b> No advanced feature engineering only basic feature engineering, e.g. extracting hour or day from <i>timestamp</i> feature or creating aggregates <font color='green'><b>DONE</b></font>\n- <b>Step7:</b> Preparing test data in same lines as training data, read saved models one by one, predict and submit results <font color='green'><b>DONE</b></font>\n- <font color='blue'>Result <b>Cross Validation score : 0.60438 and Public score: 1.42 </b>(still don't know reason for such a big difference). Requesting experts to comment and guide </font>\n\n# FURTHER IMPROVEMENTS\n- Replacing null values under weather data with weekly means. Other alternate is replacing with interpolated values. We will first try weekly mean as we know interpolated values are giving better results.\n- Increasing training iterations from 6000 to 10000. As for number of models early stopping is not reached. Therefore, there is a scope of improvement."},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#IMPORTING REQUIRED LIBRARIES\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport matplotlib.pyplot as plt\nimport datetime\n\nfrom lightgbm.sklearn import LGBMRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_log_error,mean_squared_error\nfrom sklearn.model_selection import KFold\nimport lightgbm as lgb\nimport pickle\n\nimport gc\ngc.enable()\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# DATASET OVERVIEW"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#DATASET VIEW\npath1=\"/kaggle/input/ashrae-energy-prediction/\"\npath=\"/kaggle/input/ashrae-eda-and-104-models/\"\ndata_files=list(os.listdir(path1))\ndf_files=pd.DataFrame(data_files,columns=['File_Name'])\ndf_files['Size_in_MB']=df_files.File_Name.apply(lambda x:round(os.stat(path1+x).st_size/(1024*1024),2))\n\nwith pd.option_context('display.max_rows', None, 'display.max_columns', None):\n    display(df_files.sort_values('File_Name'))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"![ERD](https://github.com/rahul2712/ASHRAE/blob/master/ASHRAE.png?raw=true)"},{"metadata":{},"cell_type":"markdown","source":"# DATA READING STRATEGY\n1. Will read only train, weather_train and building_metadata to start with.\n2. As test set is big in size will be reading it after model training.\n3. Not try to reduce datasize as per my understanding by reducing datasize sometimes we loose important information. "},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"%%time\n#READING TRAIN DATASET\nprint('READING TRAIN DATASET...')\ndf_train=pd.read_csv(path1+'train.csv')\n\nprint('READING WEATHER TRAIN DATASET...')\ndf_weather_train=pd.read_csv(path1+'weather_train.csv')\n\nprint('READING WEATHER TEST DATASET...')\ndf_weather_test=pd.read_csv(path1+'weather_test.csv')\n\nprint('READING BUILDING METADATA...')\ndf_building_metadata=pd.read_csv(path1+'building_metadata.csv')\n\nprint('DATA READING COMPLETE')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#All FUNCTIONS\n\n#FUNCTION FOR PROVIDING FEATURE SUMMARY\ndef feature_summary(df_fa):\n    print('DataFrame shape')\n    print('rows:',df_fa.shape[0])\n    print('cols:',df_fa.shape[1])\n    col_list=['Null','Unique_Count','Data_type','Max/Min','Mean','Std','Skewness','Sample_values']\n    df=pd.DataFrame(index=df_fa.columns,columns=col_list)\n    df['Null']=list([len(df_fa[col][df_fa[col].isnull()]) for i,col in enumerate(df_fa.columns)])\n    #df['%_Null']=list([len(df_fa[col][df_fa[col].isnull()])/df_fa.shape[0]*100 for i,col in enumerate(df_fa.columns)])\n    df['Unique_Count']=list([len(df_fa[col].unique()) for i,col in enumerate(df_fa.columns)])\n    df['Data_type']=list([df_fa[col].dtype for i,col in enumerate(df_fa.columns)])\n    for i,col in enumerate(df_fa.columns):\n        if 'float' in str(df_fa[col].dtype) or 'int' in str(df_fa[col].dtype):\n            df.at[col,'Max/Min']=str(round(df_fa[col].max(),2))+'/'+str(round(df_fa[col].min(),2))\n            df.at[col,'Mean']=df_fa[col].mean()\n            df.at[col,'Std']=df_fa[col].std()\n            df.at[col,'Skewness']=df_fa[col].skew()\n        elif 'datetime64[ns]' in str(df_fa[col].dtype):\n            df.at[col,'Max/Min']=str(df_fa[col].max())+'/'+str(df_fa[col].min())\n        df.at[col,'Sample_values']=list(df_fa[col].unique())\n    display(df_fa.head())       \n    return(df.fillna('-'))\n\n#FUNCTION FOR READING DICTIONARY ITEMS AND HANDLING KEYERROR\ndef get_val(x,col):\n    try:\n        y=x[col]\n    except:\n        y=np.nan\n    return(y)\n\n#FUNCTION FOR CALCULATING RMSE\ndef rmse(y,pred):\n    return(mean_squared_error(y,pred)**0.5)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# FEATURE SUMMARY TRAIN SET"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#CONVERTING timestamp TO DATATIME FIELD\ndf_train['timestamp']=pd.to_datetime(df_train['timestamp'])\n#FEATURE SUMMARY FOR TRAIN DATASET\nfeature_summary(df_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# UNDERSTANDING TRAIN FEATURES\n<table align=left >\n    <tr>\n        <th  bgcolor=\"cyan\"><b>FEATURE NAME</b></th>\n        <th  bgcolor=\"cyan\"><b>FEATURE DESCRIPTION</b></th>\n        <th  bgcolor=\"cyan\"><b>ADDITIONAL INFORMATION</b></th> \n    </tr>\n    <tr>\n        <td>building_id</td>\n        <td>a unique buildig identifier</td>\n        <td>Data contains 1449 unique builidings</td>\n    </tr>\n    <tr>\n        <td>meter</td>\n        <td>meter type</td>\n        <td>four different meter types. we can create models for each meter type</td>\n    </tr>\n    <tr>\n        <td>timestamp</td>\n        <td>timestamp for meter reading</td>\n        <td>we have readings for year 2016, starting from 2016-01-01 to 2016-12-31</td>\n    </tr>\n    <tr>\n        <td>meter_reading</td>\n        <td>target feature</td>\n        <td>target data is highly skewed</td>\n    </tr>\n</table>"},{"metadata":{},"cell_type":"markdown","source":"# UNDERSTANDING TARGET FEATURE <i>meter_reading</i>\n1. Max value is 21904700.0\n1. Min value is 0.0\n1. Mean value is 2117.12\n1. Only 8.01% observations have meter_reading greater or equal to 1000 units.\n1. Only 1.15% observations have meter_reading greater or equal to 5000 units.\n1. Only 0.47% observations have meter_reading greater or equal to 10,000 units.\n\n"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#PLOT FOR METER READING BY DATES\nplt.figure(figsize=(50,10))\nplt.title(\"METER READING BY DATES\",fontsize=40,color='b')\nplt.xlabel(\"Dates\",fontsize=40,color='b')\nplt.ylabel(\"Meter Reading\",fontsize=40,color='b')\nplt.xticks(fontsize=35)\nplt.yticks(fontsize=35)\nplt.plot(df_train['timestamp'],df_train['meter_reading'],color='green',linewidth=3)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#PIE CHART CHECKING DISTRIBUTION OF TARGET FEATURE\npie_labels=['METER READING LESS THAN 1000 UNITS : '+str(df_train['meter_reading'][df_train.meter_reading<1000.0].count()),\n            'METER READING GREATER AND EQUAL TO 1000 UNITS : '+str(df_train['meter_reading'][df_train.meter_reading>=1000.0].count())            \n           ]\npie_share=[df_train['meter_reading'][df_train.meter_reading<1000.0].count()/df_train['meter_reading'].count(),\n           df_train['meter_reading'][df_train.meter_reading>=1000.0].count()/df_train['meter_reading'].count()\n          ]\nfigureObject, axesObject = plt.subplots(figsize=(6,6))\npie_colors=('orange','grey')\npie_explode=(.15,.15)\naxesObject.pie(pie_share,labels=pie_labels,explode=pie_explode,autopct='%.2f%%',colors=pie_colors,startangle=45)\naxesObject.axis('equal')\nplt.title('OBSERVATION % WITH METER READING LESS THAN 1000 UNITS AND OTHERWISE',color='blue',fontsize=12)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#PIE CHART CHECKING DISTRIBUTION OF TARGET FEATURE\npie_labels=['METER READING LESS THAN 5000 UNITS : '+str(df_train['meter_reading'][df_train.meter_reading<5000.0].count()),\n            'METER READING GREATER AND EQUAL TO 5000 UNITS : '+str(df_train['meter_reading'][df_train.meter_reading>=5000.0].count())            \n           ]\npie_share=[df_train['meter_reading'][df_train.meter_reading<5000.0].count()/df_train['meter_reading'].count(),\n           df_train['meter_reading'][df_train.meter_reading>=5000.0].count()/df_train['meter_reading'].count()\n          ]\nfigureObject, axesObject = plt.subplots(figsize=(6,6))\npie_colors=('orange','grey')\npie_explode=(.50,.25)\naxesObject.pie(pie_share,labels=pie_labels,explode=pie_explode,autopct='%.2f%%',colors=pie_colors,startangle=45)\naxesObject.axis('equal')\nplt.title('OBSERVATION % WITH METER READING LESS THAN 5000 UNITS AND OTHERWISE',color='blue',fontsize=12)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#PIE CHART CHECKING DISTRIBUTION OF TARGET FEATURE\npie_labels=['METER READING LESS THAN 10,000 UNITS : '+str(df_train['meter_reading'][df_train.meter_reading<10000.0].count()),\n            'METER READING GREATER AND EQUAL TO 10,000 UNITS : '+str(df_train['meter_reading'][df_train.meter_reading>=10000.0].count())            \n           ]\npie_share=[df_train['meter_reading'][df_train.meter_reading<10000.0].count()/df_train['meter_reading'].count(),\n           df_train['meter_reading'][df_train.meter_reading>=10000.0].count()/df_train['meter_reading'].count()\n          ]\nfigureObject, axesObject = plt.subplots(figsize=(6,6))\npie_colors=('orange','grey')\npie_explode=(.50,.25)\naxesObject.pie(pie_share,labels=pie_labels,explode=pie_explode,autopct='%.2f%%',colors=pie_colors,startangle=45)\naxesObject.axis('equal')\nplt.title('OBSERVATION % WITH METER READING LESS THAN 10,000 UNITS AND OTHERWISE',color='blue',fontsize=12)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# DATA CATEGORIZATION BY <i>meter</i> TYPE\n1. Meter type 0 is 59.66% of total training observations\n1. Meter type 1 is 20.69% of total training observations\n1. Meter type 0 is 13.40% of total training observations\n1. Meter type 0 is 6.25% of total training observations\n"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#PIE CHART SHOWING DATA CATEGORIZATION BY METER TYPE\npie_labels=['METER TYPE 0 : '+str(df_train['meter'][df_train.meter==0].count()),\n            'METER TYPE 1 : '+str(df_train['meter'][df_train.meter==1].count()),\n            'METER TYPE 2 : '+str(df_train['meter'][df_train.meter==2].count()),\n            'METER TYPE 3 : '+str(df_train['meter'][df_train.meter==3].count())\n           ]\npie_share=[df_train['meter'][df_train.meter==0].count()/df_train['meter'].count(),\n           df_train['meter'][df_train.meter==1].count()/df_train['meter'].count(),\n           df_train['meter'][df_train.meter==2].count()/df_train['meter'].count(),\n           df_train['meter'][df_train.meter==3].count()/df_train['meter'].count()\n          ]\nfigureObject, axesObject = plt.subplots(figsize=(6,6))\npie_colors=('blue','orange','grey','green')\npie_explode=(.05,.05,.15,.05)\naxesObject.pie(pie_share,labels=pie_labels,explode=pie_explode,autopct='%.2f%%',colors=pie_colors,startangle=45)\naxesObject.axis('equal')\nplt.title('TRAIN DATA CATEGORIZATION BY METER TYPE',color='blue',fontsize=12)\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#FEATURE SUMMARY BY METER TYPE\nprint('FEATURE SUMMARY METER TYPE 0')\ndisplay(feature_summary(df_train[df_train.meter==0]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#PLOT METER READING BY DATES FOR METER TYPE 0 \nplt.figure(figsize=(50,10))\nplt.title(\"METER READING BY DATES FOR METER TYPE 0\",fontsize=40,color='b')\nplt.xlabel(\"Dates\",fontsize=40,color='b')\nplt.ylabel(\"Meter Reading\",fontsize=40,color='b')\nplt.xticks(fontsize=35)\nplt.yticks(fontsize=35)\nplt.plot(df_train['timestamp'][df_train.meter==0],df_train['meter_reading'][df_train.meter==0],color='blue',linewidth=3)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#FEATURE SUMMARY BY METER TYPE\nprint('FEATURE SUMMARY METER TYPE 1')\ndisplay(feature_summary(df_train[df_train.meter==1]))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#PLOT METER READING BY DATES FOR METER TYPE 1 \nplt.figure(figsize=(50,10))\nplt.title(\"METER READING BY DATES FOR METER TYPE 1\",fontsize=40,color='b')\nplt.xlabel(\"Dates\",fontsize=40,color='b')\nplt.ylabel(\"Meter Reading\",fontsize=40,color='b')\nplt.xticks(fontsize=35)\nplt.yticks(fontsize=35)\nplt.plot(df_train['timestamp'][df_train.meter==1],df_train['meter_reading'][df_train.meter==1],color='orange',linewidth=3)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#FEATURE SUMMARY BY METER TYPE\nprint('FEATURE SUMMARY METER TYPE 2')\ndisplay(feature_summary(df_train[df_train.meter==2]))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#PLOT METER READING BY DATES FOR METER TYPE 2 \nplt.figure(figsize=(50,10))\nplt.title(\"METER READING BY DATES FOR METER TYPE 2\",fontsize=40,color='b')\nplt.xlabel(\"Dates\",fontsize=40,color='b')\nplt.ylabel(\"Meter Reading\",fontsize=40,color='b')\nplt.xticks(fontsize=35)\nplt.yticks(fontsize=35)\nplt.plot(df_train['timestamp'][df_train.meter==2],df_train['meter_reading'][df_train.meter==2],color='grey',linewidth=3)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#FEATURE SUMMARY BY METER TYPE\nprint('FEATURE SUMMARY METER TYPE 3')\ndisplay(feature_summary(df_train[df_train.meter==3]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#PLOT METER READING BY DATES FOR METER TYPE 3\nplt.figure(figsize=(50,10))\nplt.title(\"METER READING BY DATES FOR METER TYPE 3\",fontsize=40,color='b')\nplt.xlabel(\"Dates\",fontsize=40,color='b')\nplt.ylabel(\"Meter Reading\",fontsize=40,color='b')\nplt.xticks(fontsize=35)\nplt.yticks(fontsize=35)\nplt.plot(df_train['timestamp'][df_train.meter==3],df_train['meter_reading'][df_train.meter==3],color='green',linewidth=3)\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# UNDERSTANDING <i>building_id</i>\n<font color='red'>Work in prgress...</font>"},{"metadata":{},"cell_type":"markdown","source":"# UNDERSTANDING <i>timestamp</i>\n<font color='red'>Work in prgress...</font>"},{"metadata":{},"cell_type":"markdown","source":"# FEATURE SUMMARY BUILDING METADATA SET"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#FEATURE SUMMARY FOR BUILDING METADATA DATASET\nfeature_summary(df_building_metadata)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# UNDERSTANDING BUILDING METADATA FEATURES\n<table align=left >\n    <tr>\n        <th  bgcolor=\"cyan\"><b>FEATURE NAME</b></th>\n        <th  bgcolor=\"cyan\"><b>FEATURE DESCRIPTION</b></th>\n        <th  bgcolor=\"cyan\"><b>ADDITIONAL INFORMATION</b></th> \n    </tr>\n    <tr>\n        <td>site_id</td>\n        <td>a unique site identifier</td>\n        <td>Data contains 16 unique sites</td>\n    </tr>\n    <tr>\n        <td>building_id</td>\n        <td>a unique buildig identifier</td>\n        <td>Data contains 1449 unique builidings</td>\n    </tr>\n    <tr>\n        <td>primary_use</td>\n        <td>primary use of the building</td>\n        <td>feature have string values, can be conveted into dummies</td>\n    </tr>\n    <tr>\n        <td>square_feet</td>\n        <td>building carpet area in square feets</td>\n        <td>on null values</td>\n    </tr>\n    <tr>\n        <td>year_built</td>\n        <td>year in which building was build</td>\n        <td>feature has 774 null values, can be filled with most occuring value</td>\n    </tr>\n    <tr>\n        <td>floor_count</td>\n        <td>number of floors in the building</td>\n        <td>1094 null values, can be filled with mean</td>\n    </tr>\n</table>"},{"metadata":{},"cell_type":"markdown","source":"# FEATURE SUMMARY WEATHER TRAIN SET"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#CONVERTING timestamp TO DATATIME FIELD IN WEATHER TRAIN DATASET AND EXTRACTING OTHER TIME FEATURES\ndf_weather_train['timestamp']=pd.to_datetime(df_weather_train['timestamp'])\ndf_weather_train['month']=df_weather_train.timestamp.dt.month\ndf_weather_train['year']=df_weather_train.timestamp.dt.year\ndf_weather_train['day']=df_weather_train.timestamp.dt.day\ndf_weather_train['hour']=df_weather_train.timestamp.dt.hour\ndf_weather_train['week_day']=df_weather_train.timestamp.apply(lambda x:x.weekday())\ndf_weather_train['week']=df_weather_train.timestamp.apply(lambda x:x.isocalendar()[1])\n#FEATURE SUMMARY FOR WEATHER TRAIN DATASET\nfeature_summary(df_weather_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# UNDERSTANDING WEATHER TRAIN FEATURES\n<table align=left >\n    <tr>\n        <th  bgcolor=\"cyan\"><b>FEATURE NAME</b></th>\n        <th  bgcolor=\"cyan\"><b>FEATURE DESCRIPTION</b></th>\n        <th  bgcolor=\"cyan\"><b>ADDITIONAL INFORMATION</b></th> \n    </tr>\n    <tr>\n        <td>site_id</td>\n        <td>a unique site identifier</td>\n        <td>Data contains 16 unique sites</td>\n    </tr>\n    <tr>\n        <td>timestamp</td>\n        <td>timestamp for weather conditions</td>\n        <td>we have readings for year 2016, starting from 2016-01-01 to 2016-12-31</td>\n    </tr>\n    <tr>\n        <td>air_temperature</td>\n        <td>air temperature for given site and timestamp</td>\n        <td>have 55 null values, can be filled with mean or we can predict temperature using other features in train weather table</td>\n    </tr>\n    <tr>\n        <td>cloud_coverage</td>\n        <td>cloud coverage for given site and timestamp</td>\n        <td>have 69173 null values, can be filled with mean or we can predict cloud coverage using other features in train weather table</td>\n    </tr>\n    <tr>\n        <td>dew_temperature</td>\n        <td>dew_temperature for given site and timestamp</td>\n        <td>have 113 null values, can be filled with mean or we can predict cloud coverage using other features in train weather table</td>\n    </tr>\n    <tr>\n        <td>precip_depth_1_hr</td>\n        <td>precipitation for given site and timestamp</td>\n        <td>have 50289 null values, can be filled with mean or we can predict cloud coverage using other features in train weather table</td>\n    </tr>\n    <tr>\n        <td>sea_level_pressure</td>\n        <td>sea level pressure for given site and timestamp</td>\n        <td>have 10618 null values, can be filled with mean or we can predict cloud coverage using other features in train weather table</td>\n    </tr>\n    <tr>\n        <td>wind_direction</td>\n        <td>wind direction for given site and timestamp</td>\n        <td>have 6268 null values, can be filled with mean or we can predict cloud coverage using other features in train weather table</td>\n    </tr>\n    <tr>\n        <td>wind_speed</td>\n        <td>wind speed for given site and timestamp</td>\n        <td>have 304 null values, can be filled with mean or we can predict cloud coverage using other features in train weather table</td>\n    </tr>\n</table>"},{"metadata":{},"cell_type":"markdown","source":"# FEATURE SUMMARY WEATHER TEST SET"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n#CONVERTING timestamp TO DATATIME FIELD IN WEATHER TEST DATASET AND EXTRACTING OTHER TIME FEATURES\ndf_weather_test['timestamp']=pd.to_datetime(df_weather_test['timestamp'])\ndf_weather_test['month']=df_weather_test.timestamp.dt.month\ndf_weather_test['year']=df_weather_test.timestamp.dt.year\ndf_weather_test['day']=df_weather_test.timestamp.dt.day\ndf_weather_test['hour']=df_weather_test.timestamp.dt.hour\ndf_weather_test['week_day']=df_weather_test.timestamp.apply(lambda x:x.weekday())\ndf_weather_test['week']=df_weather_test.timestamp.apply(lambda x:x.isocalendar()[1])\n#FEATURE SUMMARY FOR WEATHER TRAIN DATASET\nfeature_summary(df_weather_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# APPENDING WEATHER TRAIN AND TEST TO CALCULATE MEANS FOR MISSING VALUES"},{"metadata":{"trusted":true},"cell_type":"code","source":"#HORIZONTALLY APPENDING WEATHER TRAIN AND TEST\ndf_weather=pd.concat([df_weather_train,df_weather_test],axis=0,ignore_index=True)\n#FEATURE SUMMARY FOR COMBINED WEATER DATASET\nfeature_summary(df_weather)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#CALCULATING MEANS FOR SITE ID AND WEEK\ndf_calc_means=df_weather[['site_id','week','air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr',\n            'sea_level_pressure','wind_direction','wind_speed']].groupby(['site_id','week']).mean().reset_index()\ncols=['air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr',\n            'sea_level_pressure','wind_direction','wind_speed']\n\n#ROUNDING OFF MEANS TO 2 DECIMAL PLACES\ndf_calc_means[cols]=df_calc_means[cols].round(2)\n\n#REMOVING NULL VALUES FROM CALCULATED MEANS DATAFRAME\ndf_calc_means['cloud_coverage'].replace(np.nan,round(df_calc_means['cloud_coverage'].mean(),2),inplace=True)\ndf_calc_means['precip_depth_1_hr'].replace(np.nan,round(df_calc_means['precip_depth_1_hr'].mean(),2),inplace=True)\ndf_calc_means['sea_level_pressure'].replace(np.nan,round(df_calc_means['sea_level_pressure'].mean(),2),inplace=True)\n\nprint('FEATURE SUMMARY FOR CALCULATED MEANS BY SITE ID AND WEEK')\nfeature_summary(df_calc_means)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# JOINING TRAIN SETS\n1. First Join Train set with Building Metadata on building_id to populate building related information. Lets call joined set as df_train_BM\n2. Second Join between df_train_BM and df_weather_train on site_id and timestamp. Lets call joined set as df_train_BMW"},{"metadata":{},"cell_type":"markdown","source":"# JOINING BUILDING METADATA WITH TRAIN SET"},{"metadata":{"trusted":true},"cell_type":"code","source":"#JOINING TRAIN SET AND BUILDING METADATA\ndf_train_BM=pd.merge(df_train,df_building_metadata,how='left',on='building_id')\nfeature_summary(df_train_BM)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# UNDERSTANDING BUILDING <i>primary_use</i> FEATURE\n<i>primary_use</i> feature has 16 different categories"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"%%time\n#UNDERSTANDING BUILDING PRIMARY_USER FEATURE\npu_ls=list(df_train_BM['primary_use'].unique())\ndf_pu=pd.DataFrame(pu_ls,columns=['primary_use'])\ndf_pu['% Distribution']=df_pu['primary_use'].apply(lambda x:round(df_train_BM['primary_use'][df_train_BM.primary_use==x].count()/\n                                                   df_train_BM['primary_use'].count(),4)*100)\ndf_pu['Number_of_observations']=df_pu['primary_use'].apply(lambda x:df_train_BM['primary_use'][df_train_BM.primary_use==x].count())\ndf_pu['Avg_consumption']=df_pu['primary_use'].apply(lambda x:round(df_train_BM['meter_reading'][df_train_BM.primary_use==x].mean(),2))\ndf_pu['Avg_sq_feet']=df_pu['primary_use'].apply(lambda x:round(df_train_BM['square_feet'][df_train_BM.primary_use==x].mean(),2))\ndf_pu['Consumption_per_sq_feet']=df_pu['primary_use'].apply(lambda x:round(df_train_BM['meter_reading'][df_train_BM.primary_use==x].sum()/\n                                                                          df_train_BM['square_feet'][df_train_BM.primary_use==x].sum(),4))\ndisplay(df_pu)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"%%time\n\n#PIE CHART SHOWING DATA CATEGORIZATION BY METER TYPE\npie_labels=[]\npie_share=[]\n\nfor pu in pu_ls:\n    pie_labels.append(pu+' : '+str(df_train_BM['primary_use'][df_train_BM.primary_use==pu].count()))\n    pie_share.append(df_train_BM['primary_use'][df_train_BM.primary_use==pu].count()/df_train_BM['primary_use'].count())                  \n    \nfigureObject, axesObject = plt.subplots(figsize=(15,15))\n\npie_explode=(.1,.1,.1,.1,.89,.89,.89,.1,.99,.99,.99,.99,.99,.99,.99,.99)\naxesObject.pie(pie_share,labels=pie_labels,explode=pie_explode,autopct='%.2f%%',startangle=45)\naxesObject.axis('equal')\nplt.title('TRAIN DATA CATEGORIZATION BY PRIMARY USE OF BUILDING',color='blue',fontsize=12)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# UNDERSTANDING RELATIONSHIP BETWEEN <i>primary_use</i> AND <i>meter</i> FEATURES"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#UNDERSTANDING RELATIONSHIP BETWEEN primary_use AND meter FEATURES\ndf=df_train_BM[['building_id','meter','primary_use']].groupby(['meter','primary_use']).count().reset_index()\ndf.columns=['meter_type','primary_use','observation_count']\ndisplay(df)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# REPLACING NULL VALUES FOR <i>year_built</i> AND <i>floor_count</i> FEATURES\n1. Replacing NULL year_built by mode of year_built\n1. Replacing NULL floor_count by mean of floor_count\n1. There can be other ways replacing NULL values. We will be exploring those while improving our model\n"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#VALUES REPLACING NULL VALUES\nprint('Mean for floor_count is:',round(df_train_BM['floor_count'].mean(),0))\nprint('Mode for year_built is:',df_train_BM['year_built'].mode()[0])\n\n#REPLACING NULL VALUES\ndf_train_BM['floor_count'].replace(np.nan,round(df_building_metadata['floor_count'].mean(),0),inplace=True)\ndf_train_BM['year_built'].replace(np.nan,df_building_metadata['year_built'].mode()[0],inplace=True)\n\n#FEATURE SUMMARY AFTER REPLACING NULL VALUES FOR FEATURES floor_count AND year_built\nprint('Feature summary after replacing NULL values')\nfeature_summary(df_train_BM)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# CONVERTING <i> primary_use</i> FEATURE TO DUMMIES"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"# #CREATING DUMMIES FOR pirmary_use FEATURE\n# df_train_BMF=pd.concat([df_train_BM,pd.get_dummies(df_train_BM['primary_use'],prefix='pu')],axis=1)\n# df_train_BMF.drop('primary_use',axis=1,inplace=True)\n\n# #FEATURE SUMMARY POST DUMMY CREATION\n# print('FEATURE SUMMARY AFTER CREATING DUMMIES')\n# feature_summary(df_train_BMF)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del df_train\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# JOINING JOINED(TRAIN,BUILDING METADATA) WITH WEATHER TRAIN SET"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"%%time\n# JOINING JOINED(TRAIN,BUILDING METADATA) WITH WEATHER TRAIN SET ON site_id AND timestamp\ncols=['site_id','timestamp','air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr',\n            'sea_level_pressure','wind_direction','wind_speed']\ndf_train_BMW=pd.merge(df_train_BM,df_weather_train[cols],how='left',on=['site_id','timestamp'])\nfeature_summary(df_train_BMW)","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"#CLEARING DATAFRAMES\ndel df_train_BM\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# SOME BASIC FEATURE ENGINEERING\n- Separating month, day of the week, day, hour from timestamp"},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"%%time\n#EXTRACTING INFORMATION FROM timestamp FEATURE\ndf_train_BMW['month']=df_train_BMW.timestamp.dt.month\ndf_train_BMW['day']=df_train_BMW.timestamp.dt.day\ndf_train_BMW['hour']=df_train_BMW.timestamp.dt.hour\ndf_train_BMW['week_day']=df_train_BMW.timestamp.apply(lambda x:x.weekday())\ndf_train_BMW['week']=df_train_BMW.timestamp.apply(lambda x:x.isocalendar()[1])\n\n#GARBAGE COLLECTION\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"#FEATURE SUMMARY FOR NEW FEATURES\nlfe=['month','day','hour','week_day','week']\nprint('FEATURE SUMMARY FOR GENERATING CALCULATED FEATURES')\nfeature_summary(df_train_BMW[lfe])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# REPLACING NULL VALUES WITH CALCULATED MEANS\n\n1. Following features have NULL values <i>air_temperature, cloud_coverage, dew_temperature, precip_depth_1_hr, sea_level_pressure, wind_direction,wind_speed </i>\n1. NULL values will be replaced with the means calculated for <i>site_id</i> and <i>week</i> as climatic features are highly influenced by time and location\n\n<font color='red' align='left'>Work in progress...</font>"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n#REPLACING NULL VALUES IN WEATHER RELATED FIELDS\nfor i in range(0,df_calc_means.shape[0]):\n    print('replaceing null for site_id: ',df_calc_means.iloc[i,].site_id,' ; week ',df_calc_means.iloc[i,].week,' ; count ',i)\n    df_train_BMW[['site_id','week','air_temperature']][(df_train_BMW.site_id==df_calc_means.iloc[i,].site_id) & (df_train_BMW.week==df_calc_means.iloc[i,].week)].replace(np.nan,df_calc_means.iloc[i,].air_temperature,inplace=True)\n    df_train_BMW[['site_id','week','cloud_coverage']][(df_train_BMW.site_id==df_calc_means.iloc[i,].site_id) & (df_train_BMW.week==df_calc_means.iloc[i,].week)].replace(np.nan,df_calc_means.iloc[i,].cloud_coverage,inplace=True)\n    df_train_BMW[['site_id','week','dew_temperature']][(df_train_BMW.site_id==df_calc_means.iloc[i,].site_id) & (df_train_BMW.week==df_calc_means.iloc[i,].week)].replace(np.nan,df_calc_means.iloc[i,].dew_temperature,inplace=True)\n    df_train_BMW[['site_id','week','precip_depth_1_hr']][(df_train_BMW.site_id==df_calc_means.iloc[i,].site_id) & (df_train_BMW.week==df_calc_means.iloc[i,].week)].replace(np.nan,df_calc_means.iloc[i,].precip_depth_1_hr,inplace=True)\n    df_train_BMW[['site_id','week','sea_level_pressure']][(df_train_BMW.site_id==df_calc_means.iloc[i,].site_id) & (df_train_BMW.week==df_calc_means.iloc[i,].week)].replace(np.nan,df_calc_means.iloc[i,].sea_level_pressure,inplace=True)\n    df_train_BMW[['site_id','week','wind_direction']][(df_train_BMW.site_id==df_calc_means.iloc[i,].site_id) & (df_train_BMW.week==df_calc_means.iloc[i,].week)].replace(np.nan,df_calc_means.iloc[i,].wind_direction,inplace=True)\n    df_train_BMW[['site_id','week','wind_speed']][(df_train_BMW.site_id==df_calc_means.iloc[i,].site_id) & (df_train_BMW.week==df_calc_means.iloc[i,].week)].replace(np.nan,df_calc_means.iloc[i,].wind_speed,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#FEATURE SUMMARY POST REPLACING WEATHER NULL VALUES\nfeature_summary(df_train_BMW)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# BUILDING PREDICTOR"},{"metadata":{"trusted":true},"cell_type":"code","source":"def ASHRAE_predict_lgb(X,y,i): \n    \n\n    params = {'num_leaves': 31,\n              'objective': 'regression',\n              'learning_rate': 0.1,\n              \"boosting\": \"gbdt\",\n              \"bagging_freq\": 5,\n              \"bagging_fraction\": 0.1,\n              \"feature_fraction\": 0.9,\n              \"metric\": 'rmse',\n              }\n\n    k=1\n    splits=2\n    avg_score=0\n\n\n    kf = KFold(n_splits=splits, shuffle=True, random_state=200)\n    print('\\nStarting KFold iterations...')\n    for train_index,test_index in kf.split(X):\n\n        \n        df_X=X[train_index,:]\n        df_y=y[train_index]\n        val_X=X[test_index,:]\n        val_y=y[test_index]\n\n        \n        dtrain = lgb.Dataset(df_X, label=df_y)\n        dvalid = lgb.Dataset(val_X, label=val_y)\n        model=lgb.train(params, dtrain, 10000, valid_sets = [dtrain, dvalid],\n                        verbose_eval=2000, early_stopping_rounds=500)\n\n        preds_x=pd.Series(model.predict(val_X))\n        preds_x=[x if x>=0 else 0 for x in preds_x]\n        acc=rmse(val_y,preds_x)\n        print('Iteration:',k,'  rmsle:',acc)\n        #SAVING MODEL\n        Pkl_Filename = \"Pickle_Model_\"+str(k)+\"_combi_\"+str(i)+\".pkl\"  \n\n        with open(Pkl_Filename, 'wb') as file:\n            pickle.dump(model, file)\n        print('MODEL SAVED...')\n        if k==1:\n            score=acc\n            preds=pd.Series(preds_x)\n            acct=pd.Series(val_y)\n        \n        else:\n            preds=preds.append(pd.Series(preds_x))\n            acct=acct.append(pd.Series(val_y))\n            if score<acc:\n                score=acc\n                \n        avg_score=avg_score+acc        \n        k=k+1\n    print('\\n Best score:',score,' Avg Score:',avg_score/splits)\n#     preds=preds/splits\n    return(acct,preds)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n#TRAINING MODELS\nfor i in range(0,df.shape[0]):\n    #SPLITTING TRAINING DATA BY METER TYPE\n    print('TRAINING MODEL FOR METER TYPE: ',df.iloc[i,0],' AND PRIMARY USE:',df.iloc[i,1])  \n    X=df_train_BMW[(df_train_BMW.meter==df.iloc[i,0]) & (df_train_BMW.primary_use==df.iloc[i,1])].drop(['building_id','timestamp','meter','meter_reading','site_id','primary_use'],axis=1).values\n    y=np.log1p(df_train_BMW['meter_reading'][(df_train_BMW.meter==df.iloc[i,0]) & (df_train_BMW.primary_use==df.iloc[i,1])].values)\n    \n    #FITTING MODEL\n    val_y,preds_x=ASHRAE_predict_lgb(X,y,i)\n#     print(val_y.shape,preds_x.shape)\n    if i==0:\n        preds=pd.Series(preds_x)\n        acct=pd.Series(val_y)\n    else:\n        preds=preds.append(preds_x)\n        acct=acct.append(val_y)\n           \n    del X,y\n    gc.collect()\n    \n    \n# print(acct.shape,preds.shape)\nprint('OVER ALL ACCURACY:',rmse(acct,preds))    \n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del df_train_BMW\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"41697600/20","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# PREDICTING METER READING"},{"metadata":{"trusted":true},"cell_type":"code","source":"# #READING SAMPLE SUBMISSION FILE\n# submission=pd.read_csv(path1+'sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %%time\n# #READING TEST DATA IN CHUNKS\n# c_size=2084880\n# k=1\n# subf=pd.DataFrame()\n# for df_test in pd.read_csv(path1+'test.csv',chunksize=c_size):\n#     print(df_test.shape)\n#     print('Predicting chunk:',k,' of 20')\n    \n#     df_test['timestamp']=pd.to_datetime(df_test['timestamp'])\n    \n#     #JOINING WITH BUILDING METADATA\n#     df_test_BM=pd.merge(df_test,df_building_metadata,how='left',on='building_id')\n    \n#     #GARBAGE COLLECTION\n#     del df_test\n#     gc.collect()\n    \n#     #REPLACING NULL VALUES\n#     df_test_BM['floor_count'].replace(np.nan,round(df_building_metadata['floor_count'].mean(),0),inplace=True)\n#     df_test_BM['year_built'].replace(np.nan,df_building_metadata['year_built'].mode()[0],inplace=True)\n    \n    \n#     # JOINING JOINED(TRAIN,BUILDING METADATA) WITH WEATHER TEST SET ON site_id AND timestamp\n#     cols=['site_id','timestamp','air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr',\n#             'sea_level_pressure','wind_direction','wind_speed']\n#     df_test_BMW=pd.merge(df_test_BM,df_weather_test[cols],how='left',on=['site_id','timestamp'])\n    \n#     #GARBAGE COLLECTION\n#     del df_test_BM\n#     gc.collect()\n    \n#     #EXTRACTING INFORMATION FROM timestamp FEATURE\n#     df_test_BMW['month']=df_test_BMW.timestamp.dt.month\n#     df_test_BMW['day']=df_test_BMW.timestamp.dt.day\n#     df_test_BMW['hour']=df_test_BMW.timestamp.dt.hour\n#     df_test_BMW['week_day']=df_test_BMW.timestamp.apply(lambda x:x.weekday())\n#     df_test_BMW['week']=df_test_BMW.timestamp.apply(lambda x:x.isocalendar()[1])\n    \n#     print('Data Preparation Done')\n#     for i in range(0,df.shape[0]):\n#         sub=pd.DataFrame()\n        \n#         #SPLITTING TRAINING DATA BY METER TYPE\n#         print('PREDICTING FOR METER TYPE: ',df.iloc[i,0],' AND PRIMARY USE:',df.iloc[i,1])  \n#         X=df_test_BMW[(df_test_BMW.meter==df.iloc[i,0]) & (df_test_BMW.primary_use==df.iloc[i,1])].drop(['building_id','timestamp','meter','row_id','site_id','primary_use'],axis=1).values\n#         sub['row_id']=df_test_BMW['row_id'][(df_test_BMW.meter==df.iloc[i,0]) & (df_test_BMW.primary_use==df.iloc[i,1])].values\n        \n        \n        \n#         gc.collect()\n        \n#         if X.shape[0]!=0:\n#             Pkl_Filename1 = \"Pickle_Model_\"+str(1)+\"_combi_\"+str(i)+\".pkl\"  \n#             Pkl_Filename2 = \"Pickle_Model_\"+str(2)+\"_combi_\"+str(i)+\".pkl\" \n        \n        \n#             with open(path+Pkl_Filename1, 'rb') as file:\n#                 model1 = pickle.load(file)\n        \n#             with open(path+Pkl_Filename2, 'rb') as file:\n#                 model2 = pickle.load(file)\n        \n#             sub['meter_reading1']=pd.Series(model1.predict(X))\n# #             sub['meter_reading1']=[x if x>=0 else 0 for x in sub['meter_reading1']]\n        \n#             sub['meter_reading1']=sub['meter_reading1']+pd.Series(model1.predict(X))\n#             sub['meter_reading1']=round(sub['meter_reading1'],4)/2\n#             sub['meter_reading1']=np.expm1(sub['meter_reading1'])\n        \n#             subf=pd.concat([subf,sub],axis=0,ignore_index=True)\n#             print('Shape of sub predicted chunk:',sub.shape)\n#         else:\n#             print('No Rows found:',X.shape)\n    \n#     print('Shape of final predicted chunk(2084880,2):',subf.shape)\n#     df_test_BMW\n#     gc.collect()\n#     k=k+1\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# subf['meter_reading1']=[x if x>=0 else 0 for x in subf['meter_reading1']]\n# print('Shape of final predicted set (41697600,2):',subf.shape)\n# subf.to_csv('sub_initial.csv',index=False)\n# subf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# #CREATING SUBMISSION FILE\n# submission_f=pd.merge(submission,subf,how='left',on='row_id')\n# submission_f.drop('meter_reading',axis=1,inplace=True)\n# submission_f.columns=['row_id','meter_reading']\n# submission_f.to_csv('submission.csv', index=False)\n# submission_f","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %%time\n# #JOINING TRAIN SET AND BUILDING METADATA\n# df_test_BM=pd.merge(df_test,df_building_metadata,how='left',on='building_id')\n# print('AFTER JOINING OF BUILDING METADATA WITH TRAIN SET')\n# feature_summary(df_test_BM)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# #VALUES REPLACING NULL VALUES\n# print('Mean for floor_count is:',round(df_test_BM['floor_count'].mean(),0))\n# print('Mode for year_built is:',df_test_BM['year_built'].mode()[0])\n\n# #REPLACING NULL VALUES\n# df_test_BM['floor_count'].replace(np.nan,round(df_test_BM['floor_count'].mean(),0),inplace=True)\n# df_test_BM['year_built'].replace(np.nan,df_test_BM['year_built'].mode()[0],inplace=True)\n\n# #FEATURE SUMMARY AFTER REPLACING NULL VALUES FOR FEATURES floor_count AND year_built\n# print('Feature summary after replacing NULL values')\n# feature_summary(df_test_BM)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %%time\n# # JOINING JOINED(TRAIN,BUILDING METADATA) WITH WEATHER TRAIN SET ON site_id AND timestamp\n# cols=['site_id','timestamp','air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr',\n#             'sea_level_pressure','wind_direction','wind_speed']\n# df_test_BMW=pd.merge(df_test_BM,df_weather_test[cols],how='left',on=['site_id','timestamp'])\n# feature_summary(df_test_BMW)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# #CLEARING DATAFRAMES\n# del df_test_BM\n# gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 41697600/20","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# %%time\n# #EXTRACTING INFORMATION FROM timestamp FEATURE\n# df_test_BMW['month']=df_test_BMW.timestamp.apply(lambda x:x.month)\n# df_test_BMW['day']=df_test_BMW.timestamp.apply(lambda x:x.day)\n# df_test_BMW['hour']=df_test_BMW.timestamp.apply(lambda x:x.hour)\n# df_test_BMW['week_day']=df_test_BMW.timestamp.apply(lambda x:x.weekday())\n# df_test_BMW['week']=df_test_BMW.timestamp.apply(lambda x:x.isocalendar()[1])\n\n# #GARBAGE COLLECTION\n# gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#JOINING TRAIN SET WITH BUILDING METADATA ON site_id\n# df_train_building=df_train.join(df_build_meta,)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# df_test=pd.read_csv(path1+'test.csv',nrows=100000)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# df_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# df_submission=pd.read_csv(path1+'sample_submission.csv',usecols=['row_id'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# feature_summary(df_submission)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# df_weather_test=pd.read_csv(path1+'weather_test.csv')\n# feature_summary(df_weather_test)","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}