{"cells":[{"metadata":{"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":"building_df = pd.read_csv(\"../input/ashrae-energy-prediction/building_metadata.csv\")\nweather_train = pd.read_csv(\"../input/ashrae-energy-prediction/weather_train.csv\")\ntrain = pd.read_csv(\"../input/ashrae-energy-prediction/train.csv\")\n\ntrain = train.merge(building_df, left_on = \"building_id\", right_on = \"building_id\", how = \"left\")\ntrain = train.merge(weather_train, left_on = [\"site_id\", \"timestamp\"], right_on = [\"site_id\", \"timestamp\"])\ndel weather_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train[\"timestamp\"] = pd.to_datetime(train[\"timestamp\"])\ntrain[\"hour\"] = train[\"timestamp\"].dt.hour\ntrain[\"day\"] = train[\"timestamp\"].dt.day\ntrain[\"year\"] = train[\"timestamp\"].dt.year\ntrain[\"weekend\"] = train[\"timestamp\"].dt.weekday\ntrain[\"month\"] = train[\"timestamp\"].dt.month\ntrain['year_built'] = train['year_built']-1900\ntrain['square_feet'] = np.log(train['square_feet'])\n\ndel train[\"timestamp\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train[\"year\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\nle = LabelEncoder()\ntrain[\"primary_use\"] = le.fit_transform(train[\"primary_use\"])\n\ncategoricals = [\"site_id\", \"building_id\", \"primary_use\", \"hour\", \"day\", \"weekend\", \"month\", \"meter\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"drop_cols = [\"precip_depth_1_hr\", \"sea_level_pressure\", \"wind_direction\", \"wind_speed\"]\n\nnumericals = [\"square_feet\", \"year_built\", \"air_temperature\", \"cloud_coverage\",\n              \"dew_temperature\"]\n\nfeat_cols = categoricals + numericals","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"target = np.log1p(train[\"meter_reading\"])\n\ndel train[\"meter_reading\"] \n\ntrain = train.drop(drop_cols, axis = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import mean_squared_error\nimport lightgbm as lgb\nfrom sklearn.model_selection import KFold, StratifiedKFold\nfrom tqdm import tqdm\n\nparams = {\n            'boosting_type': 'gbdt',\n            'objective': 'regression',\n            'metric': {'rmse'},\n            'subsample': 0.2,\n            'learning_rate': 0.1,\n            'feature_fraction': 0.9,\n            'bagging_fraction': 0.9,\n            'alpha': 0.1, \n            'lambda': 0.1\n            }\n\nfolds = 3\nseed = 666\n\nkf = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed)\n\nmodels = []\nfor train_index, val_index in kf.split(train, train['building_id']):\n    train_X = train[feat_cols].iloc[train_index]\n    val_X = train[feat_cols].iloc[val_index]\n    train_y = target.iloc[train_index]\n    val_y = target.iloc[val_index]\n    lgb_train = lgb.Dataset(train_X, train_y, categorical_feature=categoricals)\n    lgb_eval = lgb.Dataset(val_X, val_y, categorical_feature=categoricals)\n    gbm = lgb.train(params,\n                lgb_train,\n                num_boost_round=300,\n                valid_sets=(lgb_train, lgb_eval),\n               early_stopping_rounds=100,\n               verbose_eval = 100)\n    models.append(gbm)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\ndel train, train_X, val_X, lgb_train, lgb_eval, train_y, val_y, target\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#preparing test data\ntest = pd.read_csv(\"../input/ashrae-energy-prediction/test.csv\")\ntest = test.merge(building_df, left_on = \"building_id\", right_on = \"building_id\", how = \"left\")\ndel building_df\ngc.collect()\ntest[\"primary_use\"] = le.transform(test[\"primary_use\"])\n\nweather_test = pd.read_csv(\"../input/ashrae-energy-prediction/weather_test.csv\")\nweather_test = weather_test.drop(drop_cols, axis = 1)\n\ntest = test.merge(weather_test, left_on = [\"site_id\", \"timestamp\"], right_on = [\"site_id\", \"timestamp\"], how = \"left\")\ndel weather_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test[\"timestamp\"] = pd.to_datetime(test[\"timestamp\"])\ntest[\"hour\"] = test[\"timestamp\"].dt.hour.astype(np.uint8)\ntest[\"year\"] = test[\"timestamp\"].dt.year.astype(np.uint16)\ntest[\"day\"] = test[\"timestamp\"].dt.day.astype(np.uint8)\ntest[\"weekend\"] = test[\"timestamp\"].dt.weekday.astype(np.uint8)\ntest[\"month\"] = test[\"timestamp\"].dt.month.astype(np.uint8)\ntest['year_built'] = test['year_built']-1900\ntest['square_feet'] = np.log(test['square_feet'])\n\ntest = test[feat_cols]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"i=0\nres=[]\nstep_size = 50000\nfor j in tqdm(range(int(np.ceil(test.shape[0]/50000)))):\n    res.append(np.expm1(sum([model.predict(test.iloc[i:i+step_size]) for model in models])/folds))\n    i+=step_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"res = np.concatenate(res)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('/kaggle/input/ashrae-energy-prediction/sample_submission.csv')\nsubmission['meter_reading'] = res\nsubmission.loc[submission['meter_reading']<0, 'meter_reading'] = 0\nsubmission.to_csv('submission.csv', index=False)\nsubmission","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}