{"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\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":{"trusted":true},"cell_type":"code","source":"from __future__ import division\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nfrom time import time\nimport datetime\nimport gc\npd.set_option('display.max_columns',100)\npd.set_option('display.max_rows',1500)\npd.set_option('display.float_format', lambda x: '%.5f' % x)\nfrom sklearn.model_selection import train_test_split,KFold,GroupKFold\nfrom sklearn.preprocessing import LabelEncoder\nimport lightgbm as lgb\n\nfrom plotly.offline import init_notebook_mode,iplot,plot\nimport plotly.graph_objects as go\ninit_notebook_mode(connected=True)\nimport plotly.figure_factory as ff","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#metadata_dtype = {'site_id':\"uint8\",'building_id':'uint16','square_feet':'float32','year_built':'float32','floor_count':\"float16\"}","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"df_data_train = pd.read_csv('/kaggle/input/ashrae-energy-prediction/train.csv',parse_dates=['timestamp'])\ndf_meta_train = pd.read_csv('/kaggle/input/ashrae-energy-prediction/building_metadata.csv')\ndf_weather_test = pd.read_csv('/kaggle/input/ashrae-energy-prediction/weather_test.csv',parse_dates=['timestamp'])\ndf_weather_train = pd.read_csv('/kaggle/input/ashrae-energy-prediction/weather_train.csv',parse_dates=['timestamp'])\ndf_data_test = pd.read_csv('/kaggle/input/ashrae-energy-prediction/test.csv',parse_dates=['timestamp'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Function to Reduce Memory**"},{"metadata":{"trusted":true},"cell_type":"code","source":"## Function to reduce the DF size\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_data_train = reduce_mem_usage(df_data_train)\ndf_weather_train = reduce_mem_usage(df_weather_train)\ndf_meta_train = reduce_mem_usage(df_meta_train)\ndf_data_test = reduce_mem_usage(df_data_test)\ndf_weather_test = reduce_mem_usage(df_weather_test)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def fill_weather_dataset(weather_df):\n    \n    # Find Missing Dates\n    time_format = \"%Y-%m-%d %H:%M:%S\"\n\n    # Add new Features\n    weather_df[\"datetime\"] = pd.to_datetime(weather_df[\"timestamp\"])\n    weather_df[\"day\"] = weather_df[\"datetime\"].dt.day\n    weather_df[\"week\"] = weather_df[\"datetime\"].dt.week\n    weather_df[\"month\"] = weather_df[\"datetime\"].dt.month\n    \n    # Reset Index for Fast Update\n    weather_df = weather_df.set_index(['site_id','day','month'])\n\n    air_temperature_filler = pd.DataFrame(weather_df.groupby(['site_id','day','month'])['air_temperature'].mean(),columns=[\"air_temperature\"])\n    weather_df.update(air_temperature_filler,overwrite=False)\n\n    # Step 1\n    cloud_coverage_filler = weather_df.groupby(['site_id','day','month'])['cloud_coverage'].mean()\n    # Step 2\n    cloud_coverage_filler = pd.DataFrame(cloud_coverage_filler.fillna(method='ffill'),columns=[\"cloud_coverage\"])\n\n    weather_df.update(cloud_coverage_filler,overwrite=False)\n\n    due_temperature_filler = pd.DataFrame(weather_df.groupby(['site_id','day','month'])['dew_temperature'].mean(),columns=[\"dew_temperature\"])\n    weather_df.update(due_temperature_filler,overwrite=False)\n\n    # Step 1\n    sea_level_filler = weather_df.groupby(['site_id','day','month'])['sea_level_pressure'].mean()\n    # Step 2\n    sea_level_filler = pd.DataFrame(sea_level_filler.fillna(method='ffill'),columns=['sea_level_pressure'])\n\n    weather_df.update(sea_level_filler,overwrite=False)\n\n    wind_direction_filler =  pd.DataFrame(weather_df.groupby(['site_id','day','month'])['wind_direction'].mean(),columns=['wind_direction'])\n    weather_df.update(wind_direction_filler,overwrite=False)\n\n    wind_speed_filler =  pd.DataFrame(weather_df.groupby(['site_id','day','month'])['wind_speed'].mean(),columns=['wind_speed'])\n    weather_df.update(wind_speed_filler,overwrite=False)\n\n    # Step 1\n    precip_depth_filler = weather_df.groupby(['site_id','day','month'])['precip_depth_1_hr'].mean()\n    # Step 2\n    precip_depth_filler = pd.DataFrame(precip_depth_filler.fillna(method='ffill'),columns=['precip_depth_1_hr'])\n\n    weather_df.update(precip_depth_filler,overwrite=False)\n\n    weather_df = weather_df.reset_index()\n    weather_df = weather_df.drop(['datetime','day','week','month'],axis=1)\n    return weather_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_weather_train = fill_weather_dataset(df_weather_train)\ndf_weather_test = fill_weather_dataset(df_weather_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Data Exploration and Analysis"},{"metadata":{},"cell_type":"markdown","source":"**Data merge**"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ndf_data_train = pd.merge(df_data_train,df_meta_train,on='building_id',how='left')\ndf_data_test  = pd.merge(df_data_test,df_meta_train,on='building_id',how='left')\nprint (\"Training Data Shape {}\".format(df_data_train.shape))\nprint (\"Testing Data Shape {}\".format(df_data_test.shape))\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_weather_train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_data_train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ndf_data_train = df_data_train.merge(df_weather_train,on=['site_id','timestamp'], how='left')\ndf_data_test  = df_data_test.merge(df_weather_test,on=['site_id','timestamp'], how='left')\nprint (\"Training Data Shape {}\".format(df_data_train.shape))\nprint (\"Testing Data Shape {}\".format(df_data_test.shape))\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for df in [df_data_train,df_data_test]:\n    df['square_feet'] = df['square_feet'].astype('float16')\n    df['Age'] = df['timestamp'].dt.year - df['year_built']\n    df['Age_isNa'] = df['year_built_isNa']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_data_train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_meta_train.info()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Merge Training Data with Mete Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_train_meta = df_data_train.merge(df_meta_train, how='left', on='building_id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_test_meta = df_data_test.merge(df_meta_train, how='left', on='building_id')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Converting meter reading of Site ID 0 to KwH"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_train_meta.loc[(df_merge_train_meta['site_id'] == 0) & (df_merge_train_meta['meter'] == 0),'meter_reading'] = \\\n      df_merge_train_meta[(df_merge_train_meta['site_id'] == 0) & (df_merge_train_meta['meter'] == 0)] \\\n      ['meter_reading'] * 0.293","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Merging of Weather Data witg trainign and meta data  together"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_train_all = df_merge_train_meta.merge(df_weather_train,on=['site_id','timestamp'], how='left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_test_all = df_merge_test_meta.merge(df_weather_test,on=['site_id','timestamp'], how='left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#df_merge_test_all.isna()\n#test_miss=pd.DataFrame({c:[sum(df_merge_test_all[c].isna()),(sum(df_merge_test_all[c].isna())/len(df_merge_test_all[c]))*100] \\\n #                           for c in df_merge_test_all.columns} ,index=['Total','%'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del test_miss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#train_miss=pd.DataFrame({c:[sum(df_merge_train_all[c].isna()),(sum(df_merge_train_all[c].isna())/len(df_merge_train_all[c]))*100] \\\n#                            for c in df_merge_train_all.columns} ,index=['Total','%'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Releasing individual Data frame which has already merged**"},{"metadata":{"trusted":true},"cell_type":"code","source":"del df_data_train\ndel df_weather_train\ndel df_data_test\ndel df_weather_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_train_all.dropna(axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_test_all.dropna(axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#df_merge_train_all.head(100)\ndf_merge_train_all = df_merge_train_all[(df_merge_train_all.meter_reading>0)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_test_all.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_train_all.info()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Dropping TImeStamp Column**"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_train_all.drop(['timestamp'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_test_all.drop(['timestamp'],axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Filtering based on Meter Type"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_merge_train_all.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_meterType_0_train = df_merge_train_all[(df_merge_train_all.meter == 0) & (df_merge_train_all.meter_reading>0)]\ndf_meterType_1_train = df_merge_train_all[(df_merge_train_all.meter == 1) & (df_merge_train_all.meter_reading>0)]\ndf_meterType_2_train = df_merge_train_all[(df_merge_train_all.meter == 2) & (df_merge_train_all.meter_reading>0)]\ndf_meterType_3_train = df_merge_train_all[(df_merge_train_all.meter == 3) & (df_merge_train_all.meter_reading>0)]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Test Data for each Meter Type"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_meterType_0_test = df_merge_test_all[df_merge_test_all.meter == 0]\ndf_meterType_1_test = df_merge_test_all[df_merge_test_all.meter == 1]\ndf_meterType_2_test = df_merge_test_all[df_merge_test_all.meter == 2]\ndf_meterType_3_test = df_merge_test_all[df_merge_test_all.meter == 3]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(np.unique(df_merge_test_all.primary_use)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Model selection Process **"},{"metadata":{"trusted":true},"cell_type":"code","source":"columns_list  = list(df_meterType_0_train.columns)\nfeatures = list(set(columns_list)-set(['meter_reading','primary_use']))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(features)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Seperating out the Out put variable "},{"metadata":{"trusted":true},"cell_type":"code","source":"y = df_meterType_0_train.meter_reading.values\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = df_meterType_0_train[features].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.4, random_state=101)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.linear_model import LinearRegression","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lm = LinearRegression()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lm.fit(X_train,y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(lm.intercept_)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = lm.predict(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.scatter(y_test,predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn import metrics","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('MAE:', metrics.mean_absolute_error(y_test, predictions))\nprint('MSE:', metrics.mean_squared_error(y_test, predictions))\nprint('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))","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":4}