{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Data preparation using fastai TabularPandas"},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastai.tabular.all import *","execution_count":null,"outputs":[]},{"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\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 read-only \"../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# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Train.csv exploration"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/ashrae-energy-prediction/train.csv\", parse_dates=['timestamp'], infer_datetime_format=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"meter_dict = {\n    0: 'electricity',\n    1: 'chilled_water',\n    2: 'steam',\n    3: 'hot_water'\n}","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### EDA"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['meter'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (12,10))\ntrain.hist(['meter_reading'], bins = 50)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"(train['meter_reading']==0).sum()/len(train)*100 # percentage of meter readings = 0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Weather_train.csv exploration"},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train = pd.read_csv(\"../input/ashrae-energy-prediction/weather_train.csv\", parse_dates=['timestamp'],\n                            infer_datetime_format=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Building_metadata.csv exporation"},{"metadata":{"trusted":true},"cell_type":"code","source":"building = pd.read_csv('../input/ashrae-energy-prediction/building_metadata.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"building.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"building.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"building.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Merge and Convert"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = train.merge(building, on='building_id', how='left')\ntrain = train.merge(weather_train, on=['site_id','timestamp'], how='left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dep_var = 'meter_reading'\ntrain[dep_var] = np.log(train[dep_var]+1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"This is a fastai function used to add datetime components of a datetime object"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = add_datepart(train, 'timestamp')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.columns","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We drop the timestampYear column because it has only 1 value (2016)"},{"metadata":{"trusted":true},"cell_type":"code","source":"train.drop('timestampYear', axis=1, inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Here we convert the dataframe to a TabularPandas object"},{"metadata":{"trusted":true},"cell_type":"code","source":"procs = [Categorify, FillMissing]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Our validation set should be the last month of the training data because the test set is also comprised of dates in 2017, i.e., we should choose our validation set so that we can forecast the meter reading for future time in a building."},{"metadata":{"trusted":true},"cell_type":"code","source":"cond = train.timestampMonth <= 11\ntrain_idxs = np.where(cond)[0]\nvalid_idxs = np.where(~cond)[0]\nsplits = (list(train_idxs), list(valid_idxs))\nlen(train_idxs), len(valid_idxs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['timestampWeek'] = train['timestampWeek'].astype('int64')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cont, cat = cont_cat_split(train, dep_var = dep_var)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cont","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cat","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"to = TabularPandas(train, procs, cat, cont, y_names=dep_var, splits=splits)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(to.train), len(to.valid)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"save_pickle('../working/to.pkl', to)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We need to convert the columns to a less bulky datatype so that we can train models on this large dataset. These datatypes are chosen so that they are the smallest datatype which doesn't affect the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"types = {\n    'building_id':'int16',\n    'meter':'int8',\n    'meter_reading':'float64',\n    'site_id': 'int8',\n    'air_temperature': 'float16',\n    'cloud_coverage': 'int8',\n    'dew_temperature': 'float16',\n    'precip_depth_1_hr': 'int16',\n    'sea_level_pressure': 'float32',\n    'wind_direction': 'int16',\n    'wind_speed': 'float16',\n    'square_feet': 'int32',\n    'year_built': 'int16',\n    'floor_count': 'int8',\n    'timestampMonth': 'int8',\n    'timestampDay': 'int8',\n    'timestampDayofweek': 'int8',\n    'timestampDayofyear': 'int16',\n    'timestampWeek': 'int8'\n}","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}