.. _tabular-api-ref: ===================== Tabular API Reference ===================== Complete API reference for NeurEco Tabular models: Regressor, Classifier, and Compressor. .. contents:: On this page :local: :depth: 2 Import ====== .. code-block:: python from NeurEco import NeurEcoTabular as tab Regressor ========= .. code-block:: python class tab.Regressor Regression model for predicting continuous values. **File extension:** ``.ednn`` Constructor ----------- .. code-block:: python model = tab.Regressor(dll_path=None) **Parameters:** - ``dll_path`` *(str, optional)* — Path to NeurEco binaries. If None, uses default installation path. Methods ------- build ^^^^^ .. code-block:: python status = model.build(config) Train the model using the provided configuration. **Parameters:** - ``config`` *(RegressorBuildConfig)* — Build configuration object **Returns:** ``int`` — Status code (0 = success) **Raises:** - ``ConfigurationError`` — Invalid configuration parameters - ``ArrayShapeMismatchError`` — Data shapes incompatible - ``ModelOperationError`` — Build failed evaluate ^^^^^^^^ .. code-block:: python outputs = model.evaluate(inputs, vec=None, gradient_cache=False) Run inference on input data. **Parameters:** - ``inputs`` *(ndarray or list)* — Input data, shape ``(n_samples, n_inputs)`` or list of arrays - ``vec`` *(ndarray, optional)* — Custom weights (uses trained weights if None) - ``gradient_cache`` *(bool)* — Cache inputs for gradient computation **Returns:** ``ndarray`` or ``list`` — Predictions with same structure as inputs **Raises:** - ``ModelNotReadyError`` — No model loaded/built - ``ArrayShapeMismatchError`` — Input shape mismatch - ``DataContainsNaNError`` — Inputs contain NaN compute_error ^^^^^^^^^^^^^ .. code-block:: python error = model.compute_error(predictions, targets) Compute L2 relative error between predictions and targets. **Parameters:** - ``predictions`` *(ndarray)* — Model predictions - ``targets`` *(ndarray)* — Ground truth values **Returns:** ``float`` — L2 relative error (0.0 = perfect, 1.0 = 100% error) load / save ^^^^^^^^^^^ .. code-block:: python model.load(path) model.save(path) Load or save model from/to disk. **Parameters:** - ``path`` *(str)* — File path (extension optional) **Returns:** ``int`` — Status code (0 = success) ``load`` reads a saved model file only. To load a model from a checkpoint, use ``load_model_from_checkpoint``. get_number_of_networks_from_checkpoint / load_model_from_checkpoint ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: python n = model.get_number_of_networks_from_checkpoint(path) model.load_model_from_checkpoint(path, model_index) Get the number of models saved in a checkpoint, or load one of them. **Parameters:** - ``path`` *(str)* --- Checkpoint path (``.checkpoint`` is added when the path does not end with it) - ``model_index`` *(int)* --- Model index (0-based) The build log and the GUI number checkpoints from 1: "Checkpoint N" there is ``model_index`` N - 1 here. **Returns:** ``int`` --- The number of models (``get_number_of_networks_from_checkpoint``), or a status code, 0 = success (``load_model_from_checkpoint``) get_input_count / get_output_count ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: python n_inputs = model.get_input_count() n_outputs = model.get_output_count() Get number of input/output features. **Returns:** ``int`` get_weights / set_weights ^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: python weights = model.get_weights() model.set_weights(weights) Get or set model weights. **Parameters (set):** - ``weights`` *(ndarray)* — Weight array, shape ``(n_parameters, 1)`` **Returns (get):** ``ndarray`` — Weight array export_onnx ^^^^^^^^^^^ .. code-block:: python status = model.export_onnx(path, precision="float32") Export to ONNX format. **Parameters:** - ``path`` *(str)* — Output file path - ``precision`` *(str)* — ``"float32"``, ``"float16"``, or ``"float64"`` (legacy ``"float"``/``"double"`` still accepted) **Returns:** ``int`` — Status code export_c ^^^^^^^^ .. code-block:: python status = model.export_c(path, precision="float32") Export to C header file. **Parameters:** - ``path`` *(str)* — Output .h file path - ``precision`` *(str)* — ``"float32"`` or ``"float64"`` (legacy ``"float"``/``"double"`` still accepted) **Returns:** ``int`` — Status code export_vba ^^^^^^^^^^ .. code-block:: python status = model.export_vba(path, precision="float32") Export to VBA (Visual Basic for Applications). **Parameters:** - ``path`` *(str)* — Output file path - ``precision`` *(str)* — ``"float32"`` or ``"float64"`` (legacy ``"float"``/``"double"`` still accepted) **Returns:** ``int`` — Status code export_fmu ^^^^^^^^^^ .. code-block:: python status = model.export_fmu(path) Export to FMU format. **Parameters:** - ``path`` *(str)* — Output .fmu file path **Returns:** ``int`` — Status code .. note:: Requires NeurEco Embed license. sensitivity ^^^^^^^^^^^ .. code-block:: python sensitivity = model.sensitivity(inputs, id_output) Compute sensitivity of an output with respect to each input. **Parameters:** - ``inputs`` *(ndarray)* — Input data - ``id_output`` *(int)* — Output index to analyze **Returns:** ``ndarray`` — Sensitivity values for each input feature perform_input_sweep ^^^^^^^^^^^^^^^^^^^ .. code-block:: python model.perform_input_sweep( input_feature, input_id, input_interval, output_id, n_points=100, show=True, save_path=None ) Visualize how one input affects the output. **Parameters:** - ``input_feature`` *(ndarray)* — Reference input sample (1D) - ``input_id`` *(int)* — Index of input to sweep - ``input_interval`` *(list)* — ``[min, max]`` range - ``output_id`` *(int)* — Output to plot - ``n_points`` *(int)* — Number of sweep points - ``show`` *(bool)* — Display plot - ``save_path`` *(str)* — Path to save figure plot_network ^^^^^^^^^^^^ .. code-block:: python model.plot_network(save_address=None, show=True) Visualize the neural network architecture. **Parameters:** - ``save_address`` *(str)* — Path to save PNG - ``show`` *(bool)* — Display plot gradient ^^^^^^^^ .. code-block:: python pw, px = model.gradient(w, x, py) Compute backward derivative (backpropagation). **Parameters:** - ``w`` *(ndarray)* — Weights - ``x`` *(ndarray)* — Inputs - ``py`` *(ndarray)* — Output perturbation **Returns:** ``tuple`` — (weight gradient, input gradient) forward_derivative ^^^^^^^^^^^^^^^^^^ .. code-block:: python dy = model.forward_derivative(w, dw, x, dx=None) Compute forward derivative (tangent mode). **Parameters:** - ``w`` *(ndarray)* — Weights - ``dw`` *(ndarray)* — Weight perturbation - ``x`` *(ndarray)* — Inputs - ``dx`` *(ndarray, optional)* — Input perturbation **Returns:** ``ndarray`` — Output perturbation delete ^^^^^^ .. code-block:: python model.delete() Free native memory. **Always call when done.** RegressorBuildConfig ==================== .. code-block:: python config = tab.RegressorBuildConfig( # Required input_data, output_data, # Optional validation / test data validation_input_data=None, validation_output_data=None, test_input_data=None, test_output_data=None, # Validation settings valid_percentage=33.33, validation_indices=None, write_validation_indexes_to="", # Output paths write_model_to="", checkpoint_address="", # Resume settings checkpoint_to_start_build_from="", start_build_from_model_number=-1, freeze_structure=False, # GPU settings use_gpu=False, gpu_id=0, # Normalization settings inputs_scaling="auto", inputs_shifting="auto", outputs_scaling="auto", outputs_shifting="auto", inputs_normalize_per_feature=True, outputs_normalize_per_feature=False, # Build settings initial_beta_reg=0.1, links_maximum_number=0, disconnect_inputs_if_possible=True, final_learning=True, field_output=False, ) **Parameters:** .. list-table:: :header-rows: 1 :widths: 34 16 50 * - Parameter - Default - Description * - ``input_data`` - (required) - Training inputs: array or list of arrays, shape ``(n_samples, n_inputs)`` * - ``output_data`` - (required) - Training outputs: array or list of arrays, shape ``(n_samples, n_outputs)`` * - ``validation_input_data`` - ``None`` - Optional validation inputs (same format as ``input_data``) * - ``validation_output_data`` - ``None`` - Optional validation outputs * - ``test_input_data`` - ``None`` - Optional test inputs (monitored during the build, never used for training) * - ``test_output_data`` - ``None`` - Optional test outputs * - ``valid_percentage`` - ``33.33`` - Percentage of training data used for validation when no validation set is given (10–50) * - ``validation_indices`` - ``None`` - Explicit 1-based indices of the samples to use for validation (overrides ``valid_percentage``) * - ``write_validation_indexes_to`` - ``""`` - Path to save the chosen validation indices as a CSV file * - ``write_model_to`` - ``""`` - Path to save the final trained model (``.ednn``) * - ``checkpoint_address`` - ``""`` - Path for the checkpoint file written during the build * - ``checkpoint_to_start_build_from`` - ``""`` - Path to an existing checkpoint to resume the build from * - ``start_build_from_model_number`` - ``-1`` - Model index within that checkpoint to resume from (``-1`` = last). The build log and the GUI number checkpoints from 1: "Checkpoint N" there is index N - 1 here * - ``freeze_structure`` - ``False`` - When resuming, retrain only the weights and keep the existing network structure (requires ``final_learning=True``) * - ``use_gpu`` - ``False`` - Use the GPU for the build * - ``gpu_id`` - ``0`` - GPU device id to use when ``use_gpu`` is ``True`` * - ``inputs_scaling`` - ``"auto"`` - Input scaling: ``"none"``, ``"auto"``, ``"max_centered"``, ``"max"``, ``"std"`` * - ``inputs_shifting`` - ``"auto"`` - Input shifting: ``"none"``, ``"auto"``, ``"min_centered"``, ``"mean"`` * - ``outputs_scaling`` - ``"auto"`` - Output scaling (same options as ``inputs_scaling``) * - ``outputs_shifting`` - ``"auto"`` - Output shifting (same options as ``inputs_shifting``) * - ``inputs_normalize_per_feature`` - ``True`` - Normalize each input feature independently (``True``) or globally (``False``) * - ``outputs_normalize_per_feature`` - ``False`` - Normalize each output feature independently (``True``) or globally (``False``) * - ``initial_beta_reg`` - ``0.1`` - Initial regularization coefficient (see :ref:`regularization-coefficient`) * - ``links_maximum_number`` - ``0`` - Maximum number of links (trainable parameters) in the network (``0`` = unlimited) * - ``disconnect_inputs_if_possible`` - ``True`` - Allow NeurEco to prune the links from the inputs each time it changes the network structure and, when ``final_learning`` is True, to disconnect the unused inputs in the final steps; with ``False``, no link from an input is ever pruned * - ``final_learning`` - ``True`` - Final pruning, a last pass that disconnects unused inputs (if ``disconnect_inputs_if_possible`` is True) and a training pass that includes validation; ``False`` skips all three (see :ref:`final-learning`) * - ``field_output`` - ``False`` - Flag the output as a single physical field, not independent scalars (distinct from ``outputs_normalize_per_feature``; see :ref:`field-output-vs-normalization`) Classifier ========== .. code-block:: python class tab.Classifier Classification model for predicting discrete classes. **File extension:** ``.ednn`` Same methods as ``Regressor``, with these differences: - Output data must be one-hot encoded - ``compute_error`` returns classification error rate ClassifierBuildConfig --------------------- Same parameters as ``RegressorBuildConfig``. .. note:: Output data must be one-hot encoded: shape ``(n_samples, n_classes)`` Compressor ========== .. code-block:: python class tab.Compressor Autoencoder for dimensionality reduction. **File extension:** ``.ednn`` Additional Methods ------------------ separate_models ^^^^^^^^^^^^^^^ .. code-block:: python encoder = Tabular.Compressor() decoder = Tabular.Compressor() model.separate_models(encoder, decoder) Split a built Compressor into its encoder (compression) and decoder (decompression) sub-models. **Parameters:** - ``encoder`` *(Compressor)* — Receives the encoder sub-model - ``decoder`` *(Compressor)* — Receives the decoder sub-model **Returns:** ``int`` — Status code (0 = success) .. note:: The encoder and decoder are also written directly at build time via the ``write_compression_model_to`` and ``write_decompression_model_to`` options of :class:`CompressorBuildConfig`; load them back with ``Compressor.load``. Compressing and reconstructing ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Once you have the encoder and decoder, compress and reconstruct with the normal ``evaluate`` call, and read the compressed dimension from the result shape: .. code-block:: python compressed = encoder.evaluate(inputs) # lower-dimensional representation reconstructed = decoder.evaluate(compressed) # back to the input space latent_dim = compressed.shape[1] # size of the compressed space CompressorBuildConfig --------------------- .. code-block:: python config = tab.CompressorBuildConfig( input_data, compress_tolerance=0.01, # ... other parameters same as RegressorBuildConfig ) **Additional Parameter:** - ``compress_tolerance`` *(float)* — Reconstruction error tolerance (default: 0.01) Example Usage ============= Regression ---------- .. code-block:: python from NeurEco import NeurEcoTabular as tab import numpy as np # Prepare data X_train = np.random.randn(1000, 5) Y_train = np.random.randn(1000, 2) # Build model = tab.Regressor() config = tab.RegressorBuildConfig( input_data=X_train, output_data=Y_train, write_model_to="./regressor.ednn" ) model.build(config) # Evaluate predictions = model.evaluate(X_test) error = model.compute_error(predictions, Y_test) print(f"Error: {100*error:.2f}%") # Cleanup model.delete() Classification -------------- .. code-block:: python from NeurEco import NeurEcoTabular as tab import numpy as np # One-hot encode labels n_classes = 3 Y_onehot = np.eye(n_classes)[labels] # Build model = tab.Classifier() config = tab.ClassifierBuildConfig( input_data=X_train, output_data=Y_onehot, write_model_to="./classifier.ednn" ) model.build(config) # Predict probs = model.evaluate(X_test) predictions = np.argmax(probs, axis=1) model.delete()