|
| 1 | +import warnings |
| 2 | +import json |
| 3 | + |
| 4 | +import pandas as pd |
| 5 | +import torch |
| 6 | + |
| 7 | +from xgboost import XGBRegressor |
| 8 | +from unileaf_util.framework.transformers.data_encoder import DataEncoder |
| 9 | + |
| 10 | +from constants import fields |
| 11 | +from constants import cao_mapping |
| 12 | +from constants import LAND_USE_COLS |
| 13 | +from constants import COLS_MAP |
| 14 | +from constants import DIFF_LAND_USE_COLS |
| 15 | +from constants import XGBOOST_FILE_PATH |
| 16 | +from constants import LSTM_CONFIG_PATH |
| 17 | +from constants import LSTM_FILE_PATH |
| 18 | +from constants import CONTEXT_COLUMNS |
| 19 | +from constants import ALL_DIFF_LAND_USE_COLS |
| 20 | +from constants import XGBOOST_FEATURES |
| 21 | + |
| 22 | +# Silence xgboost warnings |
| 23 | +warnings.filterwarnings("ignore") |
| 24 | + |
| 25 | +class Predictor: |
| 26 | + """ |
| 27 | + Wraps XGBoost model and DataEncoder. |
| 28 | + To be updated later to handle LSTM/other models. |
| 29 | + """ |
| 30 | + |
| 31 | + def __init__(self): |
| 32 | + pass |
| 33 | + |
| 34 | + def run_predictor(self, context: pd.DataFrame, prescribed: pd.DataFrame) -> float: |
| 35 | + """ |
| 36 | + Runs predictor using context and prescription. |
| 37 | + """ |
| 38 | + pass |
| 39 | + |
| 40 | + |
| 41 | +class XGBoostPredictor(Predictor): |
| 42 | + def __init__(self, model_path=XGBOOST_FILE_PATH): |
| 43 | + """ |
| 44 | + :param model_path: Path to XGBoost model file |
| 45 | + """ |
| 46 | + super().__init__() |
| 47 | + self.predictor_model = XGBRegressor() |
| 48 | + self.predictor_model.load_model(model_path) |
| 49 | + |
| 50 | + self.encoder = DataEncoder(fields, cao_mapping) |
| 51 | + |
| 52 | + |
| 53 | + def run_predictor(self, context: pd.DataFrame, prescribed: pd.DataFrame) -> float: |
| 54 | + """ |
| 55 | + Runs predictor model. |
| 56 | + :param context: DataFrame of context. |
| 57 | + :param prescribed: DataFrame of prescribed land usage to be diffed. |
| 58 | + :return: Tuple of predicted ELUC and percentage of land use changed. |
| 59 | + """ |
| 60 | + |
| 61 | + # TODO: Encoder deletes columns not in it. Manual add c4per |
| 62 | + encoded_sample_context_df = self.encoder.encode_as_df(context) |
| 63 | + |
| 64 | + prescribed_actions_df = prescribed[LAND_USE_COLS].reset_index(drop=True) \ |
| 65 | + - context[LAND_USE_COLS].reset_index(drop=True) |
| 66 | + prescribed_actions_df.rename(COLS_MAP, axis=1, inplace=True) |
| 67 | + |
| 68 | + encoded_prescribed_actions_df = self.encoder.encode_as_df(prescribed_actions_df) |
| 69 | + |
| 70 | + # TODO: Hacky |
| 71 | + encoded_prescribed_actions_df["primn_diff"] = 0 |
| 72 | + encoded_prescribed_actions_df["primf_diff"] = 0 |
| 73 | + encoded_prescribed_actions_df["c4per_diff"] = 0 |
| 74 | + encoded_sample_context_df["c4per"] = 0 |
| 75 | + |
| 76 | + context_actions = pd.concat([encoded_sample_context_df, encoded_prescribed_actions_df], axis=1) |
| 77 | + |
| 78 | + pred = self.predictor_model.predict(context_actions[XGBOOST_FEATURES]) |
| 79 | + pred_df = pd.DataFrame(pred, columns=["ELUC"]) |
| 80 | + # Decode output |
| 81 | + out_df = self.encoder.decode_as_df(pred_df) |
| 82 | + return out_df.iloc[0, 0] |
| 83 | + |
| 84 | + |
| 85 | +class LSTMPredictor(Predictor): |
| 86 | + |
| 87 | + class LSTMModel(torch.nn.Module): |
| 88 | + def __init__(self, in_features, layers=1, hidden_dim=64, dropout=0): |
| 89 | + super().__init__() |
| 90 | + self.norm = torch.nn.LayerNorm(in_features) |
| 91 | + self.lstm = torch.nn.LSTM(in_features, hidden_dim, num_layers=layers, batch_first=True, dropout=dropout) |
| 92 | + self.ff = torch.nn.Linear(hidden_dim, 1) |
| 93 | + |
| 94 | + def forward(self, x): |
| 95 | + x = self.norm(x) |
| 96 | + x, _ = self.lstm(x) |
| 97 | + x = self.ff(x[:,-1,:]) |
| 98 | + x = torch.squeeze(x) |
| 99 | + return x |
| 100 | + |
| 101 | + def __init__(self, config_path=LSTM_CONFIG_PATH, model_path=LSTM_FILE_PATH): |
| 102 | + """ |
| 103 | + :param model_path: Path to XGBoost model file |
| 104 | + """ |
| 105 | + super().__init__() |
| 106 | + config = json.load(open(LSTM_CONFIG_PATH)) |
| 107 | + self.predictor_model = self.LSTMModel(in_features=len(CONTEXT_COLUMNS + ALL_DIFF_LAND_USE_COLS), **config) |
| 108 | + self.predictor_model.load_state_dict(torch.load(model_path)) |
| 109 | + self.predictor_model.eval() |
| 110 | + |
| 111 | + self.encoder = DataEncoder(fields, cao_mapping) |
| 112 | + |
| 113 | + |
| 114 | + def run_predictor(self, context: pd.DataFrame, prescribed: pd.DataFrame) -> float: |
| 115 | + """ |
| 116 | + Runs predictor model. |
| 117 | + :param context: DataFrame of context. |
| 118 | + :param prescribed: DataFrame of prescribed land usage to be diffed. |
| 119 | + :return: Tuple of predicted ELUC and percentage of land use changed. |
| 120 | + """ |
| 121 | + |
| 122 | + context_df = context.reset_index(drop=True) |
| 123 | + encoded_context_df = self.encoder.encode_as_df(context_df) |
| 124 | + # TODO: This is yucky because we have to add primn and primf 0 diffs since our |
| 125 | + # prescriptor doesn't handle them. |
| 126 | + prescribed_actions_df = prescribed[LAND_USE_COLS].reset_index(drop=True) \ |
| 127 | + - context_df[LAND_USE_COLS].iloc[[-1]].reset_index(drop=True) |
| 128 | + prescribed_actions_df.rename(COLS_MAP, inplace=True, axis=1) |
| 129 | + encoded_prescribed_actions_df = self.encoder.encode_as_df(prescribed_actions_df) |
| 130 | + |
| 131 | + # TODO: @IMPORTANT WE DONT PRESCRIBE C4PER. Does this destroy our df? |
| 132 | + encoded_prescribed_actions_df["primn_diff"] = 0 |
| 133 | + encoded_prescribed_actions_df["primf_diff"] = 0 |
| 134 | + encoded_prescribed_actions_df["c4per_diff"] = 0 |
| 135 | + encoded_context_df["c4per"] = 0 |
| 136 | + encoded_context_df["primn_diff"] = 0 |
| 137 | + encoded_context_df["primf_diff"] = 0 |
| 138 | + encoded_context_df["c4per_diff"] = 0 |
| 139 | + |
| 140 | + encoded_context_df.loc[encoded_context_df.index[-1], DIFF_LAND_USE_COLS] = encoded_prescribed_actions_df.loc[encoded_prescribed_actions_df.index[0], DIFF_LAND_USE_COLS] |
| 141 | + df_np = encoded_context_df[CONTEXT_COLUMNS + ALL_DIFF_LAND_USE_COLS].to_numpy() |
| 142 | + inp = torch.from_numpy(df_np) |
| 143 | + inp = inp.type(torch.FloatTensor) |
| 144 | + inp = inp.unsqueeze(0) |
| 145 | + |
| 146 | + out = self.predictor_model(inp) |
| 147 | + |
| 148 | + return out.item() |
0 commit comments