Train using Python implementation of Squared Error.
(strategy: str, ax: Optional[matplotlib.axes.Axes])
| 67 | |
| 68 | |
| 69 | def custom_rmse_model(strategy: str, ax: Optional[matplotlib.axes.Axes]) -> None: |
| 70 | """Train using Python implementation of Squared Error.""" |
| 71 | |
| 72 | def gradient(predt: np.ndarray, dtrain: xgb.DMatrix) -> np.ndarray: |
| 73 | """Compute the gradient squared error.""" |
| 74 | y = dtrain.get_label().reshape(predt.shape) |
| 75 | return predt - y |
| 76 | |
| 77 | def hessian(predt: np.ndarray, dtrain: xgb.DMatrix) -> np.ndarray: |
| 78 | """Compute the hessian for squared error.""" |
| 79 | return np.ones(predt.shape) |
| 80 | |
| 81 | def squared_log( |
| 82 | predt: np.ndarray, dtrain: xgb.DMatrix |
| 83 | ) -> Tuple[np.ndarray, np.ndarray]: |
| 84 | grad = gradient(predt, dtrain) |
| 85 | hess = hessian(predt, dtrain) |
| 86 | # both numpy.ndarray and cupy.ndarray works. |
| 87 | return grad, hess |
| 88 | |
| 89 | def rmse(predt: np.ndarray, dtrain: xgb.DMatrix) -> Tuple[str, float]: |
| 90 | y = dtrain.get_label().reshape(predt.shape) |
| 91 | v = np.sqrt(np.mean(np.power(y - predt, 2))) |
| 92 | return "PyRMSE", v |
| 93 | |
| 94 | X, y = gen_circle() |
| 95 | Xy = xgb.DMatrix(X, y) |
| 96 | results: Dict[str, Dict[str, List[float]]] = {} |
| 97 | # Make sure the `num_target` is passed to XGBoost when custom objective is used. |
| 98 | # When builtin objective is used, XGBoost can figure out the number of targets |
| 99 | # automatically. |
| 100 | booster = xgb.train( |
| 101 | { |
| 102 | "tree_method": "hist", |
| 103 | "num_target": y.shape[1], |
| 104 | "multi_strategy": strategy, |
| 105 | }, |
| 106 | dtrain=Xy, |
| 107 | num_boost_round=128, |
| 108 | obj=squared_log, |
| 109 | evals=[(Xy, "Train")], |
| 110 | evals_result=results, |
| 111 | custom_metric=rmse, |
| 112 | ) |
| 113 | |
| 114 | y_predt = booster.inplace_predict(X) |
| 115 | if ax: |
| 116 | plot_predt(y, y_predt, f"PyRMSE-{strategy}", ax) |
| 117 | |
| 118 | np.testing.assert_allclose( |
| 119 | results["Train"]["rmse"], results["Train"]["PyRMSE"], rtol=1e-2 |
| 120 | ) |
| 121 | |
| 122 | |
| 123 | if __name__ == "__main__": |
no test coverage detected