SIENTIAPDE-1321: Added equation related methods

This commit is contained in:
Kou-Kinoshita
2025-10-24 08:03:27 -03:00
parent 7826e68954
commit a80d65d7ba
4 changed files with 142 additions and 0 deletions

View File

@@ -175,6 +175,10 @@ class TrainingRepository:
)
tmr.r2_val = round(r2(tmr.y_test.astype(np.float64), tmr.y_pred.astype(np.float64)), 2)
# Extract model equation
tmr.equation = self._extract_model_equation(tmr.regr, params)
self.logger.info(
f'Model metrics calculated successfully - experiment run id: {params.experiment_run_id}'
)
@@ -249,3 +253,48 @@ class TrainingRepository:
scaler_params={} if params.use_scaler else None,
ar_var=params.target_variable if params.include_ar else None,
)
def _extract_model_equation(self, regr: LinearRegressionModel, params: TrainModelParams) -> dict:
"""
Extract the linear regression equation coefficients and create equation metadata.
This method extracts the coefficients and intercept from the trained model
and creates a structured dictionary containing the equation information
for serialization as JSON artifact.
Args:
regr: Trained LinearRegressionModel object
params: Training parameters containing variable information
Returns:
dict: Equation metadata containing:
- target_variable: Name of the target variable
- coefficients: Dictionary mapping variable names to coefficients
- intercept: Model intercept value
- equation_string: Human-readable equation string
- latex_equation: LaTeX formatted equation
"""
coefficients = regr.regr.coef_
intercept = regr.regr.intercept_
# Create coefficients dictionary
coefficients_dict = {}
for i, var in enumerate(params.variable_columns):
coefficients_dict[var] = float(coefficients[i])
# Create equation string
equation_parts = [f"{coef:.6f} * {var}" for var, coef in coefficients_dict.items()]
equation_string = f"{params.target_variable} = {intercept:.6f} + " + " + ".join(equation_parts)
# Create LaTeX equation
latex_parts = [f"{coef:.6f} \\cdot {var}" for var, coef in coefficients_dict.items()]
latex_equation = f"{params.target_variable} = {intercept:.6f} + " + " + ".join(latex_parts)
return {
'target_variable': params.target_variable,
'coefficients': coefficients_dict,
'intercept': float(intercept),
'equation_string': equation_string,
'latex_equation': latex_equation,
'model_type': 'Linear Regression'
}