{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#import numpy as np # linear algebra\n#import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport gc\n\n# matplotlib and seaborn for plotting\n#import matplotlib.pyplot as plt\n\n#import seaborn as sns\n#import matplotlib.patches as patches\n#import plotly\n#from plotly import tools, subplots\n#import plotly.offline as py\n#py.init_notebook_mode(connected=True)\n#import plotly.graph_objs as go\n#import plotly.express as px\npd.set_option('max_columns', 150)\n\n#py.init_notebook_mode(connected=True)\n#from plotly.offline import init_notebook_mode, iplot\n#init_notebook_mode(connected=True)\n#import plotly.graph_objs as go\n\nimport os\nimport random\nimport math\nimport psutil\nimport pickle\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder","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\"}\n#weather_dtype = {\"site_id\":\"uint8\",'air_temperature':\"float16\",'cloud_coverage':\"float16\",'dew_temperature':\"float16\",'precip_depth_1_hr':\"float16\",\n                 #'sea_level_pressure':\"float32\",'wind_direction':\"float16\",'wind_speed':\"float16\"}\ntrain_dtype = {'meter':\"uint8\",'building_id':'uint16'}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\n#weather_train = pd.read_csv(\"../input/ashrae-energy-prediction/weather_train.csv\", parse_dates=['timestamp'], dtype=weather_dtype)\n\n\nmetadata = pd.read_csv(\"../input/ashrae-energy-prediction/building_metadata.csv\", dtype=metadata_dtype)\n\ntrain = pd.read_csv(\"../input/ashrae-energy-prediction/train.csv\", parse_dates=['timestamp'], dtype=train_dtype)\n#test = pd.read_csv(\"../input/ashrae-energy-prediction/test.csv\", parse_dates=['timestamp'], usecols=['building_id','meter','timestamp'], dtype=train_dtype)\n#weather_test = pd.read_csv(\"../input/ashrae-energy-prediction/weather_test.csv\", parse_dates=['timestamp'], dtype=weather_dtype)\nprint('Size of train_df data', train.shape)\n#print('Size of weather_train_df data', weather_train.shape)\n#print('Size of weather_test_df data', weather_test.shape)\nprint('Size of building_meta_df data', metadata.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train_dtype\ndel metadata_dtype\n#del weather_dtype","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#metadata.drop('floor_count',axis=1,inplace=True)\nmetadata = metadata[['year_built', 'square_feet', 'building_id', 'site_id']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntrain = pd.merge(train,metadata,on='building_id',how='left')\n#test  = pd.merge(test,metadata,on='building_id',how='left')\nprint (\"Training Data+Metadata Shape {}\".format(train.shape))\n#print (\"Testing Data+Metadata Shape {}\".format(test.shape))\ngc.collect()\n#train = pd.merge(train,weather_train,on=['site_id','timestamp'],how='left')\n#test  = pd.merge(test,weather_test,on=['site_id','timestamp'],how='left')\nprint (\"Training Data+Metadata+Weather Shape {}\".format(train.shape))\n#print (\"Testing Data+Metadata+Weather Shape {}\".format(test.shape))\n#gc.collect()","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['Month'] = train['timestamp'].dt.month.astype(\"uint8\")\ntrain['DayOfMonth'] = train['timestamp'].dt.day.astype(\"uint8\")\ntrain['DayOfWeek'] = train['timestamp'].dt.dayofweek.astype(\"uint8\")\ntrain['Hour'] = train['timestamp'].dt.hour.astype(\"uint8\")'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Drop nonsense entries\n# As per the discussion in the following thread, https://www.kaggle.com/c/ashrae-energy-prediction/discussion/117083, there is some discrepancy in the meter_readings for different ste_id's and buildings. It makes sense to delete them\nidx_to_drop = list((train[(train['site_id'] == 0) & (train['timestamp'] < \"2016-05-21 00:00:00\")]).index)\nprint (len(idx_to_drop))\ntrain.drop(idx_to_drop,axis='rows',inplace=True)\n\n# dropping all the electricity meter readings that are 0, after considering them as anomalies.\nidx_to_drop = list(train[(train['meter'] == 0) & (train['meter_reading'] == 0)].index)\nprint(len(idx_to_drop))\ntrain.drop(idx_to_drop,axis='rows',inplace=True)\n\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.drop('timestamp',axis=1,inplace=True)\ntrain.drop('building_id',axis=1,inplace=True)\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del idx_to_drop","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ncols = train.columns\n\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer\nimp_mean = IterativeImputer(random_state=0)\nimp_mean.fit(train)\nimputed_data = pd.DataFrame(data=imp_mean.transform(train), columns = cols)\n\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train\ndel metadata\n#del weather_train\ndel cols","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imputed_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = imputed_data['meter_reading']\nimputed_data.drop('meter_reading',axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n%%time\n#imputed_data['building_id'] = imputed_data['building_id'].astype(\"uint16\")\nimputed_data['site_id'] = imputed_data['site_id'].astype(\"uint8\") \nimputed_data['square_feet'] = imputed_data['square_feet'].astype(\"uint32\") \nimputed_data['year_built'] = imputed_data['year_built'].astype(\"uint16\")\n\n#imputed_data['Month'] = imputed_data['Month'].astype(\"uint8\")\nimputed_data['meter'] = imputed_data['meter'].astype(\"uint8\")\n#imputed_data['Hour'] = imputed_data['Hour'].astype(\"uint8\")\n    \n#imputed_data['DayOfWeek'] = imputed_data['DayOfWeek'].astype(\"uint8\")\n#imputed_data['DayOfMonth'] = imputed_data['DayOfMonth'].astype(\"uint8\")\n\ngc.collect()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(imputed_data, y, \n                                                    train_size=0.5, test_size=0.5, \n                                                    random_state=0)\n\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"categorical_cols = ['meter', 'site_id']\ntrain = pd.get_dummies(X_train, columns=categorical_cols, sparse=True)\n\ntest = pd.get_dummies(X_test, columns=categorical_cols, sparse=True)\n\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del X_train\ndel X_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_squared_log_error\nrf = RandomForestRegressor()\nrf.fit(train, y_train)\npreds = rf.predict(test)\nrmsle = np.sqrt(mean_squared_log_error( y_test, preds))\nprint(rmsle)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_columns = train.columns","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"del test\ndel train\ndel preds","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\"}\ntrain_dtype = {'meter':\"uint8\",'building_id':'uint16'}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntest = pd.read_csv(\"../input/ashrae-energy-prediction/test.csv\", parse_dates=['timestamp'], usecols=['building_id','meter','timestamp'], dtype=train_dtype)\n#weather_test = pd.read_csv(\"../input/ashrae-energy-prediction/weather_test.csv\", parse_dates=['timestamp'], dtype=weather_dtype)\nmetadata = pd.read_csv(\"../input/ashrae-energy-prediction/building_metadata.csv\", dtype=metadata_dtype)\nmetadata = metadata[['year_built', 'square_feet', 'building_id', 'site_id']]\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del metadata_dtype\ndel train_dtype","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntest  = pd.merge(test,metadata,on='building_id',how='left')\nprint (\"Testing Data+Metadata Shape {}\".format(test.shape))\ngc.collect()\n#test  = pd.merge(test,weather_test,on=['site_id','timestamp'],how='left')\nprint (\"Testing Data+Metadata+Weather Shape {}\".format(test.shape))\n#gc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.drop('timestamp',axis=1,inplace=True)\ntest.drop('building_id',axis=1,inplace=True)\ndel metadata\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ncols = test.columns\nimp_mean.fit(test)\nimputed_test = pd.DataFrame(data=imp_mean.transform(test), columns = cols)\n\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imputed_test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nimputed_test['square_feet'] = imputed_test['square_feet'].astype(\"uint32\")\nimputed_test['year_built'] = imputed_test['year_built'].astype('uint16')\nimputed_test['site_id'] = imputed_test['site_id'].astype(\"uint8\") \nimputed_test['square_feet'] = imputed_test['square_feet'].astype(\"uint32\") \nimputed_test['year_built'] = imputed_test['year_built'].astype(\"uint16\")\n\nimputed_test['meter'] = imputed_test['meter'].astype(\"uint8\")\ngc.collect()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.get_dummies(imputed_test, columns=categorical_cols, sparse=True) #imputed_test\n\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del imputed_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = test[train_columns]\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\npredictions = []\nstep = 50000\nfor i in range(0, len(test), step):\n    print(i)\n    predictions.extend(rf.predict(df.iloc[i: min(i+step, len(df)), :]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nSubmission = pd.DataFrame(df.index,columns=['row_id'])\nSubmission['meter_reading'] = predictions\nSubmission['meter_reading'].clip(lower=0,upper=None,inplace=True)\nSubmission.to_csv(\"non_paramtric.csv\",index=None)","execution_count":null,"outputs":[]},{"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}