.. _ga training:

GA Training
===========

.. container:: lang-en

   Trains a predictive model while a **genetic algorithm** optimises three
   things at once, as ``ec2ce_ga.R`` / ``train_ga.R`` do: **instance
   selection** (which *spot-cycle* groups of the training set are used),
   **feature selection** (Gray-coded section of the individual, as in R) and
   **algorithm and hyper-parameters** (which algorithm, with which grid
   combination).

   **Inputs**: **Training** (table with class ``CLASS`` and meta attributes
   ``SPOT_ID``, ``IDX``, ``TIME`` — the output of **SuperDataset**, possibly
   after *Impute*; rows without class are dropped), **Test** (optional; same
   structure, for ``hold-out`` validation) and **Learner** (several; any node
   of Orange's *Model* pane — each connected learner is one more candidate,
   with the parameters set in its node).

   **Outputs**: **Reduced Data** (training with only the selected groups and
   features), **Reduced Test**, **Model** (trained with the chosen algorithm
   on the reduced data; connect to *Predictions*), **Learner** (the chosen
   algorithm already configured; connect to *Test & Score*), **Validation
   Predictions** (``GROUP``, ``SPOT_ID``, ``TIME``, ``ACTUAL``, ``PRED``,
   ``SCORE`` per group, like R's ``_GA_predictions.csv``: predictions of the
   final model on each group, as ``lou_loyo_validation``) and **GA Evolution**
   (per iteration: mean, SD, best, worst fitness and time; plot it with *Line
   Plot*).

   **Internal validation and fitness**

   - *CV*: for each selected group, train on the other selected groups and
     evaluate on it (leave-one-group-out).
   - *hold-out*: evaluate each group of the Test table training on the
     selected training groups, excluding the same group
     (``leave_one_spotyear_out``) or its whole cycle (``leave_one_year_out``).
     *Evaluate only the test groups that are also selected* is
     ``allowFilterTestsHoldOut``.
   - The fitness is minus the mean of the per-group scores. Regression:
     ``MAE``, ``MAE.High`` / ``MAE.Low`` (only values above / below the
     segmentation quantile) and ``RAE.R2``; classification: ``HRD.HRCH`` and
     ``CHR.v1``. An individual without features, without groups or whose model
     fails gets fitness ``-1000000``. Features completely missing in the
     train or test of a fold are removed, as in R.

   **Algorithms**: the catalogue offers **Gradient Boosting**, **Random
   Forest**, **XGBoost**, **SVM**, **kNN** and **Tree** with Orange's native
   learners (regression or classification version depending on the class)
   and an editable hyper-parameter grid per algorithm (comma-separated
   values; the GA picks one combination). Orange imputes missing values
   before training, so superdatasets with gaps can be used directly.

   **Genetic algorithm**: the same scheme as R's GA package in ``ga_optim``:
   linear-rank selection, single-point crossover, one-bit mutation per
   individual, elitism (percentage of the population) and stop after N
   iterations without improvement. The population is evaluated in parallel
   (processes) and repeated individuals are served from a cache. **Cancel**
   stops at the end of the current iteration and sends the best individual
   found.

   **Differences with the R code**: the algorithms are Orange learners (with
   automatic imputation) rather than R's ``gbm``/``ranger``/``xgboost`` with
   their exact grids; only ``by-spot&year`` instance selection is
   implemented (generalised to the chosen cycle type); no files are written.

.. container:: lang-es

   Entrena un modelo predictivo optimizando con un **algoritmo genético** tres
   cosas a la vez, como ``ec2ce_ga.R`` / ``train_ga.R``: la **selección de
   instancias** (qué grupos *spot-ciclo* del entrenamiento se usan), la
   **selección de atributos** (sección del individuo en código Gray, como en
   R) y el **algoritmo e hiperparámetros** (qué algoritmo, y con qué
   combinación de su rejilla).

   **Entradas**: **Training** (tabla con clase ``CLASS`` y metadatos
   ``SPOT_ID``, ``IDX``, ``TIME`` — la salida de **SuperDataset**,
   opcionalmente pasada por *Impute*; las filas sin clase se descartan),
   **Test** (opcional; misma estructura, para la validación ``hold-out``) y
   **Learner** (varios; cualquier nodo del panel *Model* de Orange — cada
   learner conectado es un candidato más, con los parámetros fijados en su
   nodo).

   **Salidas**: **Reduced Data** (el entrenamiento con solo los grupos y
   atributos seleccionados), **Reduced Test**, **Model** (entrenado con el
   algoritmo elegido sobre los datos reducidos; conectable a *Predictions*),
   **Learner** (el algoritmo elegido ya configurado; conectable a *Test &
   Score*), **Validation Predictions** (``GROUP``, ``SPOT_ID``, ``TIME``,
   ``ACTUAL``, ``PRED`` y ``SCORE`` por grupo, como el fichero
   ``_GA_predictions.csv`` de R: predicciones del modelo final sobre cada
   grupo, igual que ``lou_loyo_validation``) y **GA Evolution** (por
   iteración: media, desviación, mejor y peor aptitud y tiempo; para
   representar con *Line Plot*).

   **Validación interna y aptitud**

   - *CV*: para cada grupo seleccionado se entrena con el resto de grupos
     seleccionados y se evalúa sobre él (leave-one-group-out).
   - *hold-out*: se evalúa cada grupo de la tabla de Test entrenando con los
     grupos seleccionados del entrenamiento, excluyendo el mismo grupo
     (``leave_one_spotyear_out``) o todo su ciclo (``leave_one_year_out``).
     *Evaluar solo los grupos del test también seleccionados* equivale a
     ``allowFilterTestsHoldOut``.
   - La aptitud es el opuesto de la media de las puntuaciones por grupo. Para
     regresión: ``MAE``, ``MAE.High`` / ``MAE.Low`` (solo valores por encima /
     debajo del cuantil de segmentación) y ``RAE.R2``; para clasificación:
     ``HRD.HRCH`` y ``CHR.v1``. Un individuo sin atributos, sin grupos o cuyo
     modelo falla recibe la aptitud ``-1000000``. En cada pliegue se eliminan
     los atributos completamente ausentes en el train o en el test, como en R.

   **Algoritmos**: el catálogo trae **Gradient Boosting**, **Random Forest**,
   **XGBoost**, **SVM**, **kNN** y **Árbol** con los learners nativos de
   Orange (versión de regresión o de clasificación según la clase) y una
   rejilla de hiperparámetros editable por algoritmo (valores separados por
   comas; el GA elige una combinación). Orange imputa los valores ausentes
   antes de entrenar, así que los superdatasets con huecos se pueden usar
   directamente.

   **Algoritmo genético**: mismo esquema que el paquete GA de R usado en
   ``ga_optim``: selección por rango lineal, cruce de un punto, mutación de
   un bit por individuo, elitismo (porcentaje de la población) y parada por
   N iteraciones sin mejora. La población se evalúa en paralelo (procesos) y
   los individuos repetidos se reutilizan de una caché. **Cancelar** detiene
   el proceso al final de la iteración en curso y emite el mejor individuo
   encontrado.

   **Diferencias respecto al código R**: los algoritmos son learners de
   Orange (con imputación automática), no ``gbm``/``ranger``/``xgboost`` de R
   con sus rejillas exactas; solo se implementa la selección de instancias
   ``by-spot&year`` (generalizada al tipo de ciclo elegido); no se escriben
   ficheros.
