{"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":"# Import library \nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold\nfrom tqdm import tqdm\nimport gc\nimport lightgbm as lgb","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Read in the data**\n\nRead in the data and have a basic understanding of what's going on"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Read in data\ndf_train = pd.read_csv('../input/ashrae-energy-prediction/train.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print (\"The number of unique building:\", df_train.building_id.nunique())\nprint (\"The number of building_id range:\", df_train.building_id.min(), \"-\", df_train.building_id.max())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"There are 1448 buildings with id 0 - 1448."},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.timestamp = pd.to_datetime(df_train.timestamp)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print (\"The number of timestamp range:\", df_train.timestamp.min(), \"-\", df_train.timestamp.max())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test = pd.read_csv('../input/ashrae-energy-prediction/test.csv')","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_test.info()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Well, interesting enough, the test data is even more than training data "},{"metadata":{"trusted":true},"cell_type":"code","source":"print (\"The number of unique building in test:\", df_test.building_id.nunique())\nprint (\"The number of building_id range:\", df_test.building_id.min(), \"-\", df_test.building_id.max())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Obviously, these are the same building as compared to the training data"},{"metadata":{"trusted":true},"cell_type":"code","source":"print (\"The number of timestamp range in test:\", df_test.timestamp.min(), \"-\", df_test.timestamp.max())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"This is obviously using 1 years of data to train for prediction of 2 years data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Read in data\ndf_meta = pd.read_csv('../input/ashrae-energy-prediction/building_metadata.csv')\ndf_meta.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_meta.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_w_train = pd.read_csv('../input/ashrae-energy-prediction/weather_train.csv')\ndf_w_test = pd.read_csv('../input/ashrae-energy-prediction/weather_test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_w_train.head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_w_test.head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = df_train.merge(df_meta, on='building_id', how='left')\ndf_w_train.timestamp = pd.to_datetime(df_w_train.timestamp)\ndf_train = df_train.merge(df_w_train, on=['site_id', 'timestamp'], how='left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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_train = reduce_mem_usage(df_train)\ndf_test = reduce_mem_usage(df_test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Data visualization**\n\nFirst, visualizing the target (meter reading)"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Separate dataframe into different section based on the \ndf_elec = df_train[df_train['meter'] == 0]\ndf_chill = df_train[df_train['meter'] == 1]\ndf_steam = df_train[df_train['meter'] == 2]\ndf_hot = df_train[df_train['meter'] == 3]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Extract the date\ndf_elec['date'] = df_elec['timestamp'].dt.date\ndf_chill['date'] = df_chill['timestamp'].dt.date\ndf_steam['date'] = df_steam['timestamp'].dt.date\ndf_hot['date'] = df_hot['timestamp'].dt.date","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Extract the hour\ndf_elec['hour'] = df_elec['timestamp'].dt.hour\ndf_chill['hour'] = df_chill['timestamp'].dt.hour\ndf_steam['hour'] = df_steam['timestamp'].dt.hour\ndf_hot['hour'] = df_hot['timestamp'].dt.hour","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Obtain the mean value at each date\ndf_elec_date_groupby = df_elec.groupby('date').agg({'meter_reading':'mean'}).reset_index()\ndf_chill_date_groupby = df_chill.groupby('date').agg({'meter_reading':'mean'}).reset_index()\ndf_steam_date_groupby = df_steam.groupby('date').agg({'meter_reading':'mean'}).reset_index()\ndf_hot_date_groupby = df_hot.groupby('date').agg({'meter_reading':'mean'}).reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Obtain the mean value at each hour\ndf_elec_hour_groupby = df_elec.groupby('hour').agg({'meter_reading':'mean'}).reset_index()\ndf_chill_hour_groupby = df_chill.groupby('hour').agg({'meter_reading':'mean'}).reset_index()\ndf_steam_hour_groupby = df_steam.groupby('hour').agg({'meter_reading':'mean'}).reset_index()\ndf_hot_hour_groupby = df_hot.groupby('hour').agg({'meter_reading':'mean'}).reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"f,axes = plt.subplots(2,2, figsize = (20,20))\nax11 = sns.lineplot(x = 'date', y = 'meter_reading', data = df_elec_date_groupby, ax = axes[0][0]).set_title('Electricity')\nax12 = sns.lineplot(x = 'date', y = 'meter_reading', data = df_chill_date_groupby, ax = axes[1][0]).set_title('Chill Water')\nax13 = sns.lineplot(x = 'date', y = 'meter_reading', data = df_steam_date_groupby, ax = axes[0][1]).set_title('Steam')\nax14 = sns.lineplot(x = 'date', y = 'meter_reading', data = df_hot_date_groupby, ax = axes[1][1]).set_title('Hot Water')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"As can seen, all four readings varies quite a lot with the dates and season\n\n**Electricity**\n1. Peaked at the summer time\n2. There are quite frequent ups-and-downs (need to investigate more)\n\n**Steam**\n\nThe steam data looks awkawrd, there is very little steam between 07-2016 to 11-2016, and there is a sudden big spike on 11-2016\n\n**Chill Water**\n1. Generally follows a reverse-V shape\n2. There are two big spikes between 09-2019 to 11-2016\n\n**Hotwater**\n1. The most consumption is during winter time\n2. Spikes on 12-2016"},{"metadata":{},"cell_type":"markdown","source":"**The overall meter reading on the hour basis**"},{"metadata":{"trusted":true},"cell_type":"code","source":"f,axes = plt.subplots(2,2, figsize = (20,20))\nax21 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_hour_groupby, ax = axes[0][0]).set_title('Electricity')\nax22 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_chill_hour_groupby, ax = axes[1][0]).set_title('Chill Water')\nax23 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_steam_hour_groupby, ax = axes[0][1]).set_title('Steam')\nax24 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_hot_hour_groupby, ax = axes[1][1]).set_title('Hot Water')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Breakdown this into more granular level**\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_steam_edu = df_steam[df_steam['primary_use'] =='Education']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ax = sns.lineplot(x = 'date', y = 'meter_reading', data = df_steam_edu).set_title('Steam for Education')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_steam_office = df_steam[df_steam['primary_use'] =='Office']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ax = sns.lineplot(x = 'date', y = 'meter_reading', data = df_steam_office).set_title('Steam for Office Building')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_steam_residential = df_steam[df_steam['primary_use'] =='Lodging/residential']\nax = sns.lineplot(x = 'date', y = 'meter_reading', data = df_steam_residential).set_title('Steam for Residential Building')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_chill_edu = df_chill[df_chill['primary_use'] =='Education']\ndf_chill_office = df_chill[df_chill['primary_use'] =='Office']\ndf_chill_residential = df_chill[df_chill['primary_use'] =='Lodging/residential']\ndf_chill_public = df_chill[df_chill['primary_use'] =='Public services']\nf,axes = plt.subplots(2,2, figsize = (20,20))\nax21 = sns.lineplot(x = 'date', y = 'meter_reading', data = df_chill_edu, ax = axes[0][0]).set_title('Chill - Education')\nax22 = sns.lineplot(x = 'date', y = 'meter_reading', data = df_chill_office, ax = axes[1][0]).set_title('Chill - Office')\nax23 = sns.lineplot(x = 'date', y = 'meter_reading', data = df_chill_residential, ax = axes[0][1]).set_title('Chill - Residential')\nax24 = sns.lineplot(x = 'date', y = 'meter_reading', data = df_chill_public, ax = axes[1][1]).set_title('Chill - Public')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**As from other thread, the weather file is not in local time**\n\n**Now let's check whether the train test file is at the local time**"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Group by site_id \ndf_elec_gb = df_elec.groupby(['site_id', 'hour'])['meter_reading'].mean().reset_index()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_elec_gb_site1 = df_elec_gb[df_elec_gb['site_id'] == 1]\ndf_elec_gb_site2 = df_elec_gb[df_elec_gb['site_id'] == 2]\ndf_elec_gb_site3 = df_elec_gb[df_elec_gb['site_id'] == 3]\ndf_elec_gb_site4 = df_elec_gb[df_elec_gb['site_id'] == 4]\ndf_elec_gb_site5 = df_elec_gb[df_elec_gb['site_id'] == 5]\ndf_elec_gb_site6 = df_elec_gb[df_elec_gb['site_id'] == 6]\ndf_elec_gb_site7 = df_elec_gb[df_elec_gb['site_id'] == 7]\ndf_elec_gb_site8 = df_elec_gb[df_elec_gb['site_id'] == 8]\nf,axes = plt.subplots(4,2, figsize = (20,20))\nax21 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_gb_site1, ax = axes[0][0]).set_title('Site1')\nax22 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_gb_site2, ax = axes[1][0]).set_title('Site2')\nax23 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_gb_site3, ax = axes[0][1]).set_title('Site3')\nax24 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_gb_site4, ax = axes[1][1]).set_title('Site4')\nax21 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_gb_site5, ax = axes[2][0]).set_title('Site5')\nax22 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_gb_site6, ax = axes[3][0]).set_title('Site6')\nax23 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_gb_site7, ax = axes[2][1]).set_title('Site7')\nax24 = sns.lineplot(x = 'hour', y = 'meter_reading', data = df_elec_gb_site8, ax = axes[3][1]).set_title('Site8')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Looks like the train and test data are at the local time, so need to tune the weather time to local time**"},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}