{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"\n\nclass 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)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nclass 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).reset_index(drop=True)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.ensemble import RandomForestRegressor\nfrom sklearn.linear_model import LinearRegression\n\nclass MyRegressor(object):\n    def __init__(self, ml_params, nmm_params, tgt_variable='meter_reading'):\n        self.ml = [RandomForestRegressor(**ml_params) for i in range(4)]\n        self.naive_mean_model = NaiveMeanModel(**nmm_params)\n        self.tgt_variable = tgt_variable\n        \n        self.mean = None\n        self.std = None\n        \n    def fit(self, X):\n        self.naive_mean_model.fit(X)\n        X['stat'] = self.naive_mean_model.predict(X)\n        \n        for i in range(4):\n            self.ml[i].fit(X[X['meter']==i].drop(columns=['timestamp',self.tgt_variable,'meter']), X.loc[X['meter']==i,self.tgt_variable])\n        \n        return self\n    \n    def predict(self, X):\n        X['stat'] = self.naive_mean_model.predict(X)\n        cols_to_drop = list({'row_id', 'timestamp', self.tgt_variable} & set(X.columns))\n        \n        X['prediction'] = 0\n        for i in range(4):\n            X.loc[X['meter']==i, 'prediction'] = self.ml[i].predict(X[X['meter']==i].drop(columns=cols_to_drop+['meter','prediction']))\n        \n        return X['prediction']\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Main"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport gc\n\nfrom os import path\n\nfrom matplotlib import pyplot as plt\n%matplotlib inline","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')))\nweather = reduce_mem_usage(pd.read_csv('/kaggle/input/ashrae/fixed_weather_df.csv')).drop(columns='Unnamed: 0')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prepare Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"WEATHER_FETURES_WITH_NANS = ['air_temperature', 'cloud_coverage', 'dew_temperature', 'precip_depth_1_hr', 'sea_level_pressure', 'wind_direction', 'wind_speed']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def prepare_data(df, build_metadata, weather_metadata, is_test=False):\n    df['timestamp'] = pd.to_datetime(df['timestamp'])\n    df = df.sort_values('timestamp')\n    \n    if not is_test:\n        primary_use_dict = {el:i for i, el in enumerate(build_metadata['primary_use'].unique())}\n        build_metadata['primary_use'] = build_metadata['primary_use'].map(primary_use_dict)\n        \n    if not is_test:\n        weather_metadata['timestamp'] = pd.to_datetime(weather_metadata['timestamp'])\n        weather_metadata = weather_metadata.sort_values('timestamp')\n        \n        for f in WEATHER_FETURES_WITH_NANS:\n            weather_metadata[f] = weather_metadata[f].fillna(weather_metadata[f].median())\n    \n    df = df.merge(build_metadata, on='building_id', how='left')\n    df = df.merge(weather_metadata, on=['site_id','timestamp'], how='left')\n    \n    df['day_of_week'] = df['timestamp'].dt.weekday\n    df['hour'] = df['timestamp'].dt.hour\n    \n    df['year_built'] = df['year_built'].fillna(df['year_built'].median())\n    df['floor_count'] = df['floor_count'].fillna(df['floor_count'].median())\n    for f in WEATHER_FETURES_WITH_NANS:\n            df[f] = df[f].fillna(df[f].median())\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, weather)\ntest = prepare_data(test, building_metadata, weather, is_test=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del building_metadata\ndel weather\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Random Forest Regressor"},{"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].reset_index(drop=True))\n        pred = model.predict(data.iloc[test_idx].reset_index(drop=True))\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":"rf_model = MyRegressor(ml_params={'n_estimators':50, 'criterion':'mse', 'max_depth':17, 'max_features':'sqrt', 'n_jobs':4}, \n                       nmm_params={'values_to_count_mean':['building_id','meter','day_of_week','hour'], 'target_variable_name':'meter_reading'})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rf_res = time_val(train, rf_model)\nprint('Result: {} +/- {}'.format(round(np.mean(rf_res),5), round(np.std(rf_res),5)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Predict"},{"metadata":{"trusted":true},"cell_type":"code","source":"rf_model.fit(train)\ntest['meter_reading'] = rf_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":{"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}