{"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":{"trusted":true},"cell_type":"code","source":"# Original code from https://www.kaggle.com/gemartin/load-data-reduce-memory-usage by @gemartin\n# Modified to support timestamp type, categorical type\n# Modified to add option to use float16 or not. feather format does not support float16.\nfrom pandas.api.types import is_datetime64_any_dtype as is_datetime\nfrom pandas.api.types import is_categorical_dtype\n\ndef reduce_mem_usage(df, use_float16=False):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        if is_datetime(df[col]) or is_categorical_dtype(df[col]):\n            # skip datetime type or categorical type\n            continue\n        col_type = df[col].dtype\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if use_float16 and c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            df[col] = df[col].astype('category')\n\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def load_data(dataset): \n    df = reduce_mem_usage(pd.read_csv(\"/kaggle/input/ashrae-energy-prediction/{}.csv\".format(dataset), parse_dates=[\"timestamp\"]))\n    building_metadata = pd.read_csv(\"/kaggle/input/ashrae-energy-prediction/building_metadata.csv\").groupby(\"building_id\").first().fillna(-1)\n    weather_data = reduce_mem_usage(pd.read_csv(\"/kaggle/input/ashrae-energy-prediction/weather_{}.csv\".format(dataset), parse_dates=[\"timestamp\"])\\\n        .groupby(\"site_id\").apply(lambda x: x.sort_values(\"timestamp\").ffill().bfill().groupby(\"timestamp\").first().resample(rule=\"H\").first()).drop(columns=\"site_id\"))\n    df = df.join(other=building_metadata, on=\"building_id\")\n    df = df.join(other=weather_data, on=[\"site_id\", \"timestamp\"]).fillna(-1)\n    df[\"hour_of_day\"] = df.timestamp.dt.hour\n    return pd.get_dummies(reduce_mem_usage(df))[['timestamp', 'meter', 'building_id', 'square_feet', 'year_built', 'floor_count', 'air_temperature',\n       'cloud_coverage', 'dew_temperature', 'precip_depth_1_hr',\n       'sea_level_pressure', 'wind_direction', 'wind_speed', 'hour_of_day',\n       'primary_use_Education', \n       'primary_use_Lodging/residential', 'primary_use_Office'] + ([] if dataset == \"test\" else [\"meter_reading\"])]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = load_data(\"train\").sample(4000000)\ndf[\"meter_reading\"] = np.log1p(df.meter_reading)\ndf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from seaborn import distplot\n# distplot(df.meter_reading)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df[\"meter_id\"] = df[\"building_id\"].apply(str) + \"_\" + df[\"meter\"].apply(str)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from seaborn import scatterplot\n# scatterplot(x=\"square_feet\", y=\"meter_reading\", data=df.groupby(\"meter_id\").max(), hue=\"meter\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# scatterplot(x=\"square_feet\", y=\"meter_reading\", data=df[df.meter == 0].groupby(\"meter_id\").max())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# scatterplot(x=\"square_feet\", y=\"meter_reading\", data=df[df.meter == 1].groupby(\"meter_id\").max())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# scatterplot(x=\"square_feet\", y=\"meter_reading\", data=df[df.meter == 2].groupby(\"meter_id\").max())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# scatterplot(x=\"square_feet\", y=\"meter_reading\", data=df[df.meter == 3].groupby(\"meter_id\").max())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"It seems reasonable to simply remove all meters that have reported a value above 11, based on these scatterplots."},{"metadata":{"trusted":true},"cell_type":"code","source":"df = df[~df.meter_id.isin(df[df.meter_reading > 11].meter_id)]\n# scatterplot(x=\"square_feet\", y=\"meter_reading\", data=df.groupby(\"meter_id\").max(), hue=\"meter\").set_title(\"Scatterplot of meter readings after outlier removal\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# distplot(df.meter_reading).set_title(\"Distribution of meter readings after outlier removal\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from seaborn import lineplot\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\n# lineplot(data=df.groupby(\"timestamp\")[\"meter_reading\"].agg(lambda c: np.expm1(c).sum()).resample(rule=\"D\").sum()).set_title(\"Total energy usage over time\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Clear seasonal pattern can be observed in the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\nfrom lightgbm import LGBMRegressor\n# from sklearn.ensemble import RandomForestRegressor\n\nr = LGBMRegressor(n_estimators=447, learning_rate=0.1616975721056746, max_depth=13, num_leaves=127, min_child_samples=16, reg_alpha=0.01, reg_lambda=0.00001, verbose=2, n_jobs=-1)\nattributes = ['meter', 'square_feet', 'year_built', 'floor_count', 'air_temperature',\n       'cloud_coverage', 'dew_temperature', 'precip_depth_1_hr',\n       'sea_level_pressure', 'wind_direction', 'wind_speed', 'hour_of_day',\n       'primary_use_Education', \n       'primary_use_Lodging/residential', 'primary_use_Office']\ntrain_columns = attributes + [\"meter_reading\"]\ndf = df[train_columns + [\"timestamp\"]]\nsdf = df.sort_values(\"timestamp\").drop(\"timestamp\", axis=1)\ntrain_X, train_y = sdf[attributes], sdf[\"meter_reading\"]\ndel df\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import mean_squared_log_error\nfrom sklearn.metrics.scorer import make_scorer\n\ndef rmsle(y_true, y_pred, **kwargs):\n    score = np.sqrt(mean_squared_log_error(np.expm1(y_true), np.clip(np.expm1(y_pred), 0, None)))\n    print(\"RMSLE: {}\".format(score))\n    return score\n\nrmsle_scorer = make_scorer(rmsle, greater_is_better=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from sklearn.metrics.scorer import make_scorer\n# from sklearn.model_selection import TimeSeriesSplit\n# from sklearn.feature_selection import RFECV\n\n# rfecv = RFECV(estimator=r, step=1, cv=TimeSeriesSplit(n_splits=5), verbose=1, scoring=make_scorer(rmsle))\n# rfecv.fit(train_X, train_y)\n\n# print(\"Optimal number of features : %d\" % rfecv.n_features_)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# import matplotlib.pyplot as plt\n# plt.figure()\n# plt.xlabel(\"Number of features selected\")\n# plt.ylabel(\"Cross validation score (nb of correct classifications)\")\n# plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)\n# plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# sorted(list(zip(rfecv.ranking_, train_X.columns)), reverse=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from scipy.stats import uniform, randint\n# from sklearn.model_selection import RandomizedSearchCV, TimeSeriesSplit\n\n# # distributions = dict(n_estimators=randint(50, 500), max_depth=randint(2, 15), learning_rate=uniform(loc=0, scale=0.3), num_leaves=randint(2, 128), min_child_samples=randint(5, 200), \n# #                      reg_alpha=uniform(loc=0, scale=0.1), reg_lambda=uniform(loc=0, scale=0.1))\n# distributions = dict(reg_alpha=[10**i for i in range(-5,1)], reg_lambda=[10**i for i in range(-5,1)])\n# rscv = RandomizedSearchCV(r, distributions, scoring=make_scorer(rmsle, greater_is_better=False), cv=TimeSeriesSplit(n_splits=5), n_iter=10, verbose=2)\n# search = rscv.fit(train_X, train_y)\n# print(\"Best score: {}\".format(search.best_score_))\n# print(search.best_params_)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from scipy.stats import sem, t\n# from scipy import mean\n\n# def get_mean_confidence_diff(confidence, values):\n#     n = len(values)\n#     m = mean(values)\n#     std_err = sem(values)\n#     diff = std_err * t.ppf((1 + confidence) / 2, n - 1)\n#     return diff","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from sklearn.model_selection import cross_val_score, TimeSeriesSplit\n\n# scores = cross_val_score(r, train_X, train_y, scoring=rmsle_scorer, cv=TimeSeriesSplit(n_splits=5))\n\n# print(\"RMSLE (95% confidence): {:.2f} (+/- {:.2f})\".format(-scores.mean(), get_mean_confidence_diff(0.95, scores)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"r.fit(train_X, train_y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train_X\ndel train_y\ngc.collect()\ntest_df = load_data(\"test\")\ntest_df = test_df[attributes]\ntest_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = r.predict(test_df)\npredictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv('/kaggle/input/ashrae-energy-prediction/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission[\"meter_reading\"] = np.expm1(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.to_csv('submission.csv', index=False, float_format='%.4f')","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}