{"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":"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport gc\n\n\n# matplotlib and seaborn for plotting\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\nimport matplotlib.patches as patches\n\nimport os\nimport random\nimport math\nimport psutil\nimport pickle\n\n#conda install -c conda-forge lightgbm\nfrom sklearn.ensemble import RandomForestRegressor as RF\nimport lightgbm as lgb\n\nfrom sklearn.model_selection import train_test_split,KFold\nfrom sklearn.preprocessing import LabelEncoder\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Import Data "},{"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'}\n\nweather_train = pd.read_csv(\"../input/ashrae-energy-prediction/weather_train.csv\", parse_dates=['timestamp'], dtype=weather_dtype)\nweather_test = pd.read_csv(\"../input/ashrae-energy-prediction/weather_test.csv\", parse_dates=['timestamp'], dtype=weather_dtype)\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)\ntest = pd.read_csv(\"../input/ashrae-energy-prediction/test.csv\", parse_dates=['timestamp'], usecols=['building_id','meter','timestamp'], dtype=train_dtype)\n\ntrain['meter'].replace({0:\"Electricity\",1:\"ChilledWater\",2:\"Steam\",3:\"HotWater\"},inplace=True)\ntest['meter'].replace({0:\"Electricity\",1:\"ChilledWater\",2:\"Steam\",3:\"HotWater\"},inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Drop column floor_count, more than 3/4 are missing observations\nmetadata.drop('floor_count',axis=1,inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Construct Month, Week, Hour features:\nfor df in [train, test]:\n    df['Month'] = df['timestamp'].dt.month.astype(\"uint8\")\n    df['DayOfMonth'] = df['timestamp'].dt.day.astype(\"uint8\")\n    df['DayOfWeek'] = df['timestamp'].dt.dayofweek.astype(\"uint8\")\n    df['Hour'] = df['timestamp'].dt.hour.astype(\"uint8\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Transform target variable. The idea is to squeeze outliers out\ntrain['meter_reading'] = np.log1p(train['meter_reading'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#As per visualisation made in https://www.kaggle.com/nroman/eda-for-ashrae, one might suspect seasonality inherent in data. Create season variable:\nfor df in [train, test]:\n    df['Season'] = ((df['Month']%12+3)//3).astype(\"uint8\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Process Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nmetadata['primary_use'].replace({\"Healthcare\":\"Other\",\"Parking\":\"Other\",\"Warehouse/storage\":\"Other\",\"Manufacturing/industrial\":\"Other\",\n                                \"Retail\":\"Other\",\"Services\":\"Other\",\"Technology/science\":\"Other\",\"Food sales and service\":\"Other\",\n                                \"Utility\":\"Other\",\"Religious worship\":\"Other\"},inplace=True)\nmetadata['square_feet'] = np.log(1+0.0003*metadata['square_feet'])\nmetadata['year_built'].fillna(-999, inplace=True)\nmetadata['year_built'] = metadata['year_built'].astype('int16')\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.merge(train,metadata,on='building_id',how='left')\ntest  = pd.merge(test,metadata,on='building_id',how='left')\nprint (\"Training Data+Metadata Shape {}\".format(train.shape))\nprint (\"Testing Data+Metadata Shape {}\".format(test.shape))\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.merge(train,weather_train,on=['site_id','timestamp'],how='left')\ntest  = pd.merge(test,weather_test,on=['site_id','timestamp'],how='left')\nprint (\"Training Data+Metadata+Weather Shape {}\".format(train.shape))\nprint (\"Testing Data+Metadata+Weather Shape {}\".format(test.shape))\ngc.collect()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Let's save some space:\nfor df in [train,test]:\n    df['square_feet'] = df['square_feet'].astype('float16')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Encode meter and primary_use features. \nle = LabelEncoder()\ntrain['primary_use']= le.fit_transform(train['primary_use']).astype(\"uint8\")\ntest['primary_use']= le.fit_transform(test['primary_use']).astype(\"uint8\")\ntrain['meter']= le.fit_transform(train['meter']).astype(\"uint8\")\ntest['meter']= le.fit_transform(test['meter']).astype(\"uint8\")\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Feature engineering"},{"metadata":{"trusted":true},"cell_type":"code","source":"#We will add interaction terms between season and some of the features:\n#Add interaction between primary_use and seasonality\nfor df in [train,test]:\n    df['primary_use_X_season']=df['primary_use']*df['Season']\n    df['primary_use_X_season']=df['primary_use_X_season'].astype(\"uint8\")\n\n#Add interaction between building_id and seasonality\nfor df in [train,test]:\n    df['building_id_X_season']=df['building_id']*df['Season']\n    df['building_id_X_season']=df['building_id_X_season'].astype(\"uint8\")\n\n#Add interaction between meter and seasonality\nfor df in [train,test]:\n    df['meter_X_season']=df['meter']*df['Season']\n    df['meter_X_season']=df['meter_X_season'].astype(\"uint8\")\n\n#Add interaction between site_id and seasonality\nfor df in [train,test]:\n    df['site_id_X_season']=df['site_id']*df['Season']\n    df['site_id_X_season']=df['site_id_X_season'].astype(\"uint8\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Replace Missing values:\ncols = ['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":"#Let's drop entries which seem nonsense as per discussion given in https://www.kaggle.com/robertobianco/time-series-study\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'] == \"Electricity\") & (train['meter_reading'] == 0)].index)\nprint(len(idx_to_drop))\ntrain.drop(idx_to_drop,axis='rows',inplace=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Drop timestamp feature:\ntrain.drop('timestamp',axis=1,inplace=True)\ntest.drop('timestamp',axis=1,inplace=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Split the data by train and validation splits:\ny = train['meter_reading']\ntrain.drop('meter_reading',axis=1,inplace=True)\n\nX_1_1 = train[:int(train.shape[0] / 2)]\nX_1_2 = train[int(train.shape[0] / 2):]\n\n\n\ny_1_1 = y[:int(train.shape[0] / 2)]\ny_1_2 = y[int(train.shape[0] / 2):]\n\n\ncategorical_cols = ['building_id_X_season','site_id_X_season','meter_X_season','primary_use_X_season','Season','building_id','site_id','Month','meter','Hour','primary_use','DayOfWeek','DayOfMonth']\n\n\nlgb_1= lgb.Dataset(X_1_1, y_1_1, categorical_feature=categorical_cols,free_raw_data=False)\nlgb_2 = lgb.Dataset(X_1_2, y_1_2, categorical_feature=categorical_cols,free_raw_data=False)\n\nparams = {'feature_fraction': 0.85, # 0.75\n          'bagging_fraction': 0.75,\n          'objective': 'regression',\n           \"num_leaves\": 40, # New\n          'max_depth': -1,\n          'learning_rate': 0.15,\n          \"boosting_type\": \"gbdt\",\n          \"bagging_seed\": 11,\n          \"metric\": 'rmse',\n          \"verbosity\": -1,\n          'reg_alpha': 0.5,\n          'reg_lambda': 0.5,\n          'random_state': 47\n         }\nvalidation_1 = [lgb_1, lgb_2]\nvalidation_2 = [lgb_2, lgb_1]\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"reg_1 = lgb.train(params, lgb_1, num_boost_round=1000, valid_sets=validation_1, verbose_eval=200, early_stopping_rounds=200)\nreg_2 = lgb.train(params, lgb_2, num_boost_round=1000, valid_sets=validation_2, verbose_eval=200, early_stopping_rounds=200)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Feature Importance Per Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"#Feature importance in each model:\nser = pd.DataFrame(reg_1.feature_importance(),train.columns,columns=['Importance']).sort_values(by='Importance')\nser['Importance'].plot(kind='bar',figsize=(10,6))\nplt.title(\"Feature Importance for first model\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nser = pd.DataFrame(reg_2.feature_importance(),train.columns,columns=['Importance']).sort_values(by='Importance')\nser['Importance'].plot(kind='bar',figsize=(10,6))\nplt.title(\"Feature Importance for second model\")\n\ndel X_1_1,X_1_2,y_1_1,y_1_2,weather_train,weather_test, metadata\ndel lgb_1,lgb_2\ndel train\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Predictions"},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = (reg_1.predict(test, num_iteration=reg_1.best_iteration)) / 2\n\ndel reg_1\ngc.collect()\n\n\npredictions += (reg_2.predict(test, num_iteration=reg_2.best_iteration)) / 2\n    \n\ndel reg_2\ngc.collect()\n\n\npredictions=np.expm1(predictions)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Submit"},{"metadata":{"trusted":true},"cell_type":"code","source":"Submission = pd.DataFrame(test.index,columns=['row_id'])\nSubmission['meter_reading'] = predictions\nSubmission['meter_reading'].clip(lower=0,upper=None,inplace=True)\nSubmission.to_csv(\"submission_3.csv\",index=None)\n\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":1}