{"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\"}\nweather_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\nweather_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, nrows = 10000000)\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)\nprint('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\ndel weather_dtype","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weather_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"metadata.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I'll delete the column floor_count as it has over 70% of missing data"},{"metadata":{"trusted":true},"cell_type":"code","source":"metadata.drop('floor_count',axis=1,inplace=True)","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":{},"cell_type":"markdown","source":"merge data"},{"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()\ntrain = 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))\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Encode primary_use to numbers"},{"metadata":{"trusted":true},"cell_type":"code","source":"le = LabelEncoder()\n\ntrain['primary_use']= le.fit_transform(train['primary_use']).astype(\"uint8\")\n#test['primary_use']= le.fit_transform(test['primary_use']).astype(\"uint8\")\nprint (train.shape)#, test.shape)\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del le","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","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":"del idx_to_drop","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.drop('timestamp',axis=1,inplace=True)\n#test.drop('timestamp',axis=1,inplace=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\n# Fill NA\ncols = ['year_built', 'air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr','sea_level_pressure','wind_direction','wind_speed']\nfor col in cols:\n    train[col].fillna(np.nanmean(train[col].tolist()),inplace=True)\n    #test[col].fillna(np.nanmean(test[col].tolist()),inplace=True)\n    '''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cols = train.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\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\ndel 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)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n%%time\nimputed_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\")\nimputed_data['sea_level_pressure'] = imputed_data['sea_level_pressure'].astype(\"uint16\")\nimputed_data['wind_speed'] = imputed_data['wind_speed'].astype(\"uint8\")\nimputed_data['cloud_coverage'] = imputed_data['cloud_coverage'].astype(\"uint8\")\nimputed_data['Month'] = imputed_data['Month'].astype(\"uint8\")\nimputed_data['meter'] = imputed_data['meter'].astype(\"uint8\")\nimputed_data['Hour'] = imputed_data['Hour'].astype(\"uint8\")\n    \nimputed_data['primary_use'] = imputed_data['primary_use'].astype(\"uint8\")\nimputed_data['DayOfWeek'] = imputed_data['DayOfWeek'].astype(\"uint8\")\nimputed_data['DayOfMonth'] = imputed_data['DayOfMonth'].astype(\"uint8\")\nimputed_data['wind_direction'] = imputed_data['wind_direction'].astype(\"uint16\") \ngc.collect()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"imputed_data.dtypes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''from sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import RandomForestRegressor\nclf = RandomForestRegressor(n_estimators=100)\nclf = clf.fit(train, y)\nclf.feature_importances_  \n\nmodel = SelectFromModel(clf, prefit=True)\ntrain_new = model.transform(train)\ntrain_new.shape               \n\ngc.collect()\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#test_new = model.transform(test)\n#test_new.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#X_train, X_test, y_train, y_test = train_test_split(train, y, train_size=0.7, test_size=0.3, random_state=0, shuffle=True)\n#X_train.shape, X_test.shape","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.7, test_size=0.3, \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 = ['building_id','Month','meter','Hour','primary_use','DayOfWeek','DayOfMonth']#\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()\n\ntrain.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":"ser = pd.DataFrame(rf.feature_importances_,train.columns,columns=['Importance']).sort_values(by='Importance')\nser[ser['Importance']>0.0001]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del ser","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.metrics import mean_squared_error\nparameters = {'n_estimators':[50,75,100, 125,150], \n              'max_features':['auto',25, 50, 75, 100], \n              'max_depth': [None, 2,4,6,8]}\nrf = RandomForestRegressor()\nclf = GridSearchCV(rf, parameters)\nclf.fit(train, y_train)\n\n#sorted(clf.cv_results_.keys())'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_columns = train.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#from sklearn.metrics import mean_squared_error\n#preds = clf.predict(X_test)\n#mse = mean_squared_error(y_test, preds)\n#print(mse)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#clf.best_params_\n#clf.best_score_\n#clf.n_splits_","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"del test\ndel train\ndel X_train\ndel X_test\n","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\"}\nweather_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\ntest = pd.read_csv(\"../input/ashrae-energy-prediction/test.csv\", parse_dates=['timestamp'], usecols=['building_id','meter','timestamp'], dtype=train_dtype)\nweather_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.drop('floor_count',axis=1,inplace=True)\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del metadata_dtype\ndel weather_dtype\ndel train_dtype","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['Month'] = test['timestamp'].dt.month.astype(\"uint8\")\ntest['DayOfMonth'] = test['timestamp'].dt.day.astype(\"uint8\")\ntest['DayOfWeek'] = test['timestamp'].dt.dayofweek.astype(\"uint8\")\ntest['Hour'] = test['timestamp'].dt.hour.astype(\"uint8\")\ngc.collect()","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()\ntest  = pd.merge(test,weather_test,on=['site_id','timestamp'],how='left')\nprint (\"Testing Data+Metadata+Weather Shape {}\".format(test.shape))\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"le = LabelEncoder()\ntest['primary_use']= le.fit_transform(test['primary_use']).astype(\"uint8\")\ntest.shape\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.drop('timestamp',axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del le\ndel metadata\ndel weather_test","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\n# Fill NA\ncols = ['year_built', 'air_temperature','cloud_coverage','dew_temperature','precip_depth_1_hr','sea_level_pressure','wind_direction','wind_speed']\nfor col in cols:\n    #train[col].fillna(np.nanmean(train[col].tolist()),inplace=True)\n    test[col].fillna(np.nanmean(test[col].tolist()),inplace=True)\n    \ngc.collect()    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntest['square_feet'] = test['square_feet'].astype(\"uint32\")\ntest['year_built'] = test['year_built'].astype('uint16')\ntest['air_temperature'] = test['air_temperature'].astype('uint8')\ntest['cloud_coverage'] = test['cloud_coverage'].astype('uint8')\ntest['dew_temperature'] = test['dew_temperature'].astype('uint8')\ntest['precip_depth_1_hr'] = test['precip_depth_1_hr'].astype('uint8')\ntest['sea_level_pressure'] = test['sea_level_pressure'].astype('uint16')\ntest['wind_direction'] = test['wind_direction'].astype('uint16')\ntest['wind_speed'] = test['wind_speed'].astype('uint8')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#test.dtypes","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":"test = pd.get_dummies(test, columns=categorical_cols, sparse=True) #imputed_test\ntest.shape\ngc.collect()","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(df), step):\n    print(i)\n    predictions.extend(np.expm1(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(test.index,columns=['row_id'])\nSubmission['meter_reading'] = predictions\nSubmission['meter_reading'].clip(lower=0,upper=None,inplace=True)\nSubmission.to_csv(\"sneaky_weasels.csv\",index=None)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Submission.head()","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}