{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Utils"},{"metadata":{"trusted":true},"cell_type":"code","source":"class MonthTimeValidation(object):\n    def __init__(self, month_to_test_set=2, time_col='timestamp'):\n        self.month_to_test_set = month_to_test_set\n        self.time_col = time_col\n        \n    def split(self, df):\n        split_col = df[self.time_col].dt.month\n        split_col = split_col.reset_index(drop=True)\n        \n        for max_month in range(1,13-self.month_to_test_set):\n            train_idx = split_col[split_col <= max_month].index.tolist()\n            test_idx = split_col[(split_col > max_month) & (split_col <= max_month+self.month_to_test_set)].index.tolist()\n            yield train_idx, test_idx\n            \nimport numpy as np\n\n\ndef reduce_mem_usage(df, verbose=True):\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() / 1024**2    \n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col_type in numerics:\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 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    end_mem = df.memory_usage().sum() / 1024**2\n    if verbose: print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n    return df\n\n\nfrom sklearn.metrics import mean_squared_error\n\ndef LRMSE(y_true, y_pred):\n    return (mean_squared_error(y_true,y_pred))**(1/2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class NaiveMeanModel(object):\n    def __init__(self, values_to_count_mean, target_variable_name, value_to_fillna=0):\n        self.values_to_count_mean = values_to_count_mean\n        self.target_variable_name = target_variable_name\n        self.value_to_fillna = value_to_fillna\n        \n        self.counted_stats = None \n        \n    def fit(self, X, y=None):\n        if len(set(self.values_to_count_mean) & set(X.columns)) < len(self.values_to_count_mean):\n            raise ValueError('Columns to count stats not in df')\n            \n        self.counted_stats = X.groupby(self.values_to_count_mean)[self.target_variable_name].mean().reset_index()\n        \n    def predict(self, X):\n        if self.target_variable_name in X.columns:\n            prediction =  X.merge(self.counted_stats, on=self.values_to_count_mean, how='left')[self.target_variable_name+'_y']\n        else:\n            prediction =  X.merge(self.counted_stats, on=self.values_to_count_mean, how='left')[self.target_variable_name]\n            \n        print(str(prediction.isna().sum()) + ' Nan detected')\n        return prediction.fillna(self.value_to_fillna)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Main"},{"metadata":{"trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport gc\n\nfrom os import path","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Read data"},{"metadata":{"trusted":true},"cell_type":"code","source":"data_path = '/kaggle/input/ashrae-energy-prediction/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = reduce_mem_usage(pd.read_csv(path.join(data_path,'train.csv')))\ntest = reduce_mem_usage(pd.read_csv(path.join(data_path,'test.csv')))\n\nbuilding_metadata = reduce_mem_usage(pd.read_csv(path.join(data_path,'building_metadata.csv')))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prepare Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"def prepare_data(df, build_metadata, is_test=False):\n    df['timestamp'] = pd.to_datetime(df['timestamp'])\n    df = df.sort_values('timestamp')\n    \n    df = df.merge(build_metadata, on='building_id', how='left')\n    \n    df['day_of_week'] = df['timestamp'].dt.weekday\n    df['hour'] = df['timestamp'].dt.hour\n    \n    if not is_test:\n        df['meter_reading'] = np.log1p(df['meter_reading'])\n    \n    return df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = prepare_data(train, building_metadata)\ntest = prepare_data(test, building_metadata, is_test=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del building_metadata\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# NaiveMeanModel"},{"metadata":{},"cell_type":"markdown","source":"## Validation"},{"metadata":{"trusted":true},"cell_type":"code","source":"def time_val(data, model, metric=LRMSE, target_var_name='meter_reading'):\n    time_validation_split = MonthTimeValidation()\n    \n    results = []\n    for train_idx, test_idx in time_validation_split.split(data):\n        model.fit(data.iloc[train_idx])\n        pred = model.predict(data.iloc[test_idx])\n        itter_metric = metric(data.iloc[test_idx][target_var_name], pred)\n        \n        print('Itter metric: '+str(itter_metric))\n        results.append(itter_metric)\n        \n        gc.collect()\n        \n    return results","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"naive_mean_model = NaiveMeanModel(['building_id','meter','day_of_week','hour'],'meter_reading')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"naive_mean_model_results = time_val(train, naive_mean_model)\nprint('Result: {} +/- {}'.format(round(np.mean(naive_mean_model_results),5), round(np.std(naive_mean_model_results),5)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"naive_mean_model.fit(train)\ntest['meter_reading'] = naive_mean_model.predict(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['meter_reading'] = np.expm1(test['meter_reading'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test[['row_id','meter_reading']].to_csv('naive_mean_predictor.csv', index=False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3.6 venv","language":"python","name":"venv"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.8"}},"nbformat":4,"nbformat_minor":1}