{"cells":[{"metadata":{},"cell_type":"markdown","source":"This kernel is mainly based on https://www.kaggle.com/isaienkov/lightgbm-fe-1-19 . I made some adjustments "},{"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[\"quarter\"] = train[\"timestamp\"].dt.quarter\ntrain[\"month\"] = train[\"timestamp\"].dt.month\ntrain[\"weekday\"] = train[\"timestamp\"].dt.weekday\ntrain[\"hour\"] = train[\"timestamp\"].dt.hour\ntrain[\"quarter\"] = train[\"quarter\"].astype(np.uint8)\ntrain[\"month\"] = train[\"month\"].astype(np.uint8)\ntrain[\"weekday\"] = train['weekday'].astype(np.uint8)\ntrain[\"hour\"] = train['hour'].astype(np.uint8)\ntrain['square_feet'] = np.log(train['square_feet'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train[\"timestamp\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#train['wind_direction'] = train['wind_direction'].apply(degToCompass)\n#train['beaufort_scale'] = train['beaufort_scale'].astype(np.uint8)\n#train[\"wind_direction\"] = train['wind_direction'].astype(np.uint8)\ntrain[\"meter\"] = train['meter'].astype(np.uint8)\ntrain[\"site_id\"] = train['site_id'].astype(np.uint8)","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 = [\"building_id\",\"site_id\", \"meter\",\"primary_use\", \"quarter\",\"month\",\"weekday\", \"hour\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"drop_cols = [\"sea_level_pressure\", \"wind_direction\"]\n\nnumericals = [\"square_feet\", \"air_temperature\", \"cloud_coverage\",\n              \"dew_temperature\", 'precip_depth_1_hr',\"wind_speed\",\"relative humidity\",\"year_built\",\"floor_count\"]\n\nfeat_cols = categoricals + numericals","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[\"relative humidity\"] = train[\"dew_temperature\"] / train[\"air_temperature\"] *100","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = train[~(train['meter'].isin([0]) & (train['meter_reading'].isin([0])))]    ## \n\ntrain = train[~(train[\"building_id\"].isin([1099]) & (train[\"meter\"].isin([2])))]  ##building 1099 meter 2\n\ntrain.head()","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.model_selection import KFold, StratifiedKFold\nfolds = 4\nseed = 666\n\nkf = StratifiedKFold(n_splits=folds, shuffle=True, random_state=seed)\nprint(kf)\n","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\n\nparams = {\n            'boosting_type': 'gbdt',\n            'objective': 'regression',\n            'metric': {'rmse'},\n            'subsample': 0.25,\n            'subsample_freq': 1,\n            'learning_rate': 0.4,\n            'num_leaves': 20,\n            'feature_fraction': 0.9,\n            'lambda_l1': 1,  \n            'lambda_l2': 1\n            }\n\nfolds = 2\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=500,\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":"","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":"test = 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\")\n\ntest = test.merge(weather_test, left_on = [\"site_id\", \"timestamp\"], right_on = [\"site_id\", \"timestamp\"], how = \"left\")\ndel weather_test\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test[\"timestamp\"] = pd.to_datetime(test[\"timestamp\"])\ntest[\"hour\"] = test[\"timestamp\"].dt.hour\ntest[\"weekday\"] = test[\"timestamp\"].dt.weekday\ntest[\"month\"] = test[\"timestamp\"].dt.month\ntest[\"quarter\"] = test[\"timestamp\"].dt.quarter\ntest[\"quarter\"] = test[\"quarter\"].astype(np.uint8)\ntest[\"month\"] = test[\"month\"].astype(np.uint8)\ntest[\"weekday\"] = test['weekday'].astype(np.uint8)\ntest[\"hour\"] = test['hour'].astype(np.uint8)\n\ntest['square_feet'] = np.log(test['square_feet'])\n\ntest[\"meter\"] = test['meter'].astype(np.uint8)\ntest[\"site_id\"] = test['site_id'].astype(np.uint8)\ntest[\"relative humidity\"] = test[\"dew_temperature\"] / test[\"air_temperature\"] *100\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":{"trusted":true},"cell_type":"code","source":" gbm.feature_importance()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(feat_cols)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\na = gbm.feature_importance()\nb = feat_cols\nsns.barplot(x=a, y=b)","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}