API Reference¶
This page provides complete documentation for all AGNBoost classes and functions.
Overview¶
AGNBoost consists of two main classes:
- Catalog: For data loading, management, and feature engineering
- AGNBoost: For machine learning model training, tuning, and prediction
Catalog Class¶
The Catalog class is your entry point for working with astronomical data. It handles loading data from various formats, validates photometric bands, creates features, and manages data splits.
Key Features¶
- Load FITS files, CSV files, or pandas DataFrames
- Automatic photometric band validation
- Feature engineering (colors, transformations)
- Train/validation/test data splitting
- Signal-to-noise filtering
A class for loading, managing, and manipulating astronomical data.
The Catalog class provides tools for loading astronomical data from various formats, performing feature engineering, data validation, and preparing data for machine learning workflows. It supports FITS files, CSV files, and pandas DataFrames.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
DataFrame
|
The main astronomical dataset. |
features_df |
DataFrame
|
Engineered features for machine learning. |
allowed_bands |
dict
|
Dictionary storing the information (column name in data, shorthand name, and wavelength) for the used photometric bands |
valid_columns |
dict
|
Dictionary storing the the photometric bands from allowed_bands that are found in the stored data. |
train_indices |
Index
|
Indices for training data split. |
val_indices |
Index
|
Indices for validation data split. |
trainval_indices |
Index
|
Indices for combined training + validation data split. |
test_indices |
Index
|
Indices for test data split. |
custom_feature_func |
callable
|
User created function to create custom features. |
Examples:
Basic usage with a FITS file:
from agnboost import Catalog
# Load data
catalog = Catalog(path="jwst_data.fits")
# Create features
catalog.create_feature_dataframe()
# Split data
catalog.split_data(test_size=0.2, val_size=0.2)
Loading data from a pandas DataFrame:
create_color_dataframe
staticmethod
¶
Calculate photometric colors from band flux measurements.
Creates all possible non-reciprocal photometric colors from the provided band data. Colors are calculated as log10(flux_i / flux_j) where band_i has a longer wavelength than band_j. This follows standard astronomical convention where colors like (J-H) represent log10(flux_J / flux_H).
The bands are automatically sorted by wavelength in descending order (longest to shortest wavelength) to ensure consistent color naming and calculation. For example, with bands at 2.2μm, 1.6μm, and 1.2μm, this will create colors like: - 2.2μm/1.6μm (longer/shorter) - 2.2μm/1.2μm - 1.6μm/1.2μm
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing flux measurements for each object.
Must have columns corresponding to the band names in the |
required |
bands
|
dict
|
required |
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame or None: DataFrame containing computed color columns with the same index as the input data. Column names follow the format "shorthand_i/shorthand_j" where shorthand_i corresponds to the longer wavelength band. Returns None if fewer than 2 bands are provided. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a band name in the |
ValueError
|
If flux values are zero or negative (causing log10 calculation errors). |
Examples:
Basic color calculation:
Using with a Catalog instance:
import pandas as pd
import numpy as np
from agnboost import Catalog
catalog = Catalog(path="jwst_data.fits")
valid_bands = catalog.get_valid_bands()
colors = Catalog.create_color_dataframe(catalog.get_data(), valid_bands)
Notes
- Colors are calculated as log10(longer_wavelength_flux / shorter_wavelength_flux)
- Zero or negative flux values will produce NaN or infinite values in the colors
- The method creates n*(n-1)/2 colors for n input bands
- Band sorting by wavelength ensures consistent color naming across different datasets
- Color names use shorthand identifiers for readability (e.g., 'F200W/F150W' vs full names)
See Also
create_feature_dataframe: Higher-level method that includes color creation transform: For applying custom transformations to individual columns
remove_negative_fluxes
staticmethod
¶
Remove negative and zero flux values by replacing them with NaN.
Negative or zero flux measurements are often unphysical in astronomical data and can cause issues with logarithmic calculations (magnitudes, colors). This method identifies such values in photometric band columns and replaces them with NaN to prevent downstream calculation errors while preserving the data structure.
This is particularly important for: - Magnitude calculations: mag = -2.5 * log10(flux) - Color calculations: color = log10(flux1 / flux2) - Feature transforamtions that use logarithmic transformations
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
DataFrame containing astronomical measurements.
Must include columns corresponding to the band names specified in |
required |
bands
|
dict
|
required |
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame or None: Copy of the input DataFrame with negative and zero flux values replaced by NaN in the specified band columns. Other columns remain unchanged. Returns None if an error occurs during processing. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a band column name is not found in the DataFrame columns. |
Exception
|
For any other processing errors (logged and returns None). |
Examples:
Clean flux measurements before magnitude calculation:
Use with a Catalog instance:
import pandas as pd
import numpy as np
from agnboost import Catalog
catalog = Catalog(path="survey_data.fits")
valid_bands = catalog.get_valid_bands()
clean_data = Catalog.remove_negative_fluxes(catalog.get_data(), valid_bands)
# Now safe to calculate magnitudes and colors
magnitudes = -2.5 * np.log10(clean_data[band_columns])
Integration with feature engineering:
# Clean data before creating features
catalog = Catalog(path="photometry.fits")
bands = catalog.get_valid_bands()
# Remove problematic values
clean_data = Catalog.remove_negative_fluxes(catalog.data, bands)
catalog.data = clean_data
# Now create features safely
catalog.create_feature_dataframe()
Notes
- Automatically called by the dop_nan() Catalog class method
- Only modifies columns specified in the
bandsdictionary - Non-band columns (IDs, coordinates, etc.) are left unchanged
- Creates a copy of the input data, preserving the original
- Zero flux values are also replaced as they cause issues with log calculations
- NaN values can be handled by downstream methods like
drop_nan() - The method logs warnings for each column where negative values are found
See Also
drop_nan: Remove rows with NaN values after cleaning create_feature_dataframe: Higher-level method that may use cleaned data sn_cut: Alternative approach using signal-to-noise thresholds
get_features_from_phots ¶
Generate the feature data frame for a single row (i.e., a single source) of data.
Uses either the default feature creation, or if a custom feature function has previously been used to create features, it will call that.
By default, the created features will include: 1. Log photometry: log10(flux) for each band 2. Colors: log10(flux_i / flux_j) for all band pairs 3. Squared colors: (color)² terms
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phot_df
|
DataFrame
|
DataFrame containing photometric flux measurements. Must have columns corresponding to the valid photometric bands found during catalog initialization. Typically this would be a subset of the main catalog data containing only the validated band columns. |
required |
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: DataFrame containing engineered features with the same index as the input photometric data. Feature columns include: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If photometric DataFrame contains non-positive values that prevent log calculations. |
AttributeError
|
If custom_feature_func is not callable when provided. |
KeyError
|
If required band columns are missing from the photometric DataFrame. |
Examples:
Default feature engineering with JWST bands:
import pandas as pd
import numpy as np
from agnboost import Catalog
# Load catalog with JWST data
catalog = Catalog(path="jwst_photometry.fits")
# Get photometric data for valid bands only
valid_bands = catalog.get_valid_bands()
phot_data = catalog.get_data()[list(valid_bands.keys())]
# Generate features
features = catalog.get_features_from_phots(phot_data)
print(f"Created {features.shape[1]} features from {phot_data.shape[1]} bands")
# Example output columns:
# ['jwst.nircam.F115W', 'jwst.nircam.F150W', 'jwst.nircam.F200W', # log phot
# 'F200W/F150W', 'F200W/F115W', 'F150W/F115W', # colors
# 'F200W/F150W^2', 'F200W/F115W^2', 'F150W/F115W^2'] # squared colors
Notes
- Data cleaning: Ensure input data doesn't contain negative or zero flux values before calling this method, as log calculations will fail
- Custom functions: If using custom_feature_func, ensure it has only a (data) non-default parameter and returns a DataFrame with the same index
- NaN handling: Any NaN values in input photometry will propagate through the feature calculations
See Also
create_feature_dataframe: Higher-level method that handles the complete pipeline create_color_dataframe: Standalone color calculation method remove_negative_fluxes: Data cleaning for problematic flux values
create_feature_dataframe ¶
Create feature dataframe to use with AGNBoost.
Uses either the default feature creation, or if a custom feature function is provided, that function will be used for feature creation.
By default, the created features will include: 1. Log photometry: log10(flux) for each band 2. Colors: log10(flux_i / flux_j) for all band pairs 3. Squared colors: (color)² terms
The resulting feature dataframe is stored as self.features_df and can be used
directly with AGNBoost models for training and prediction. If a custom feature function
is provided, it will saved into self.custom_func
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
custom_func
|
callable
|
Custom function to generate features from the data. Must accept the catalog's data as input and return a pandas DataFrame with the same index as the original data. If None, uses the default feature pipeline. Defaults to None. |
None
|
silent
|
bool
|
If True, suppresses logging output about feature creation. Useful for batch processing or when called repeatedly. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame or None: DataFrame containing engineered features with the same
index as the catalog data. Also stored as |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If custom function returns DataFrame with different length than catalog data. |
Exception
|
If custom function returns DataFrame with mismatched index. |
Examples:
Default feature engineering:
from agnboost import Catalog
# Load astronomical data
catalog = Catalog(path="jwst_observations.fits")
# Create default features
features = catalog.create_feature_dataframe()
print(f"Created {features.shape[1]} features for {features.shape[0]} objects")
# Features are automatically stored
assert catalog.features_df is not None
print("Feature columns:", list(catalog.features_df.columns))
Using with custom feature function:
def polynomial_features(data):
"""Create polynomial features from photometric data."""
import pandas as pd
import numpy as np
# Get valid bands (this would be passed from catalog context)
feature_df = pd.DataFrame(index=data.index)
# Example: create polynomial features for first few bands
band_cols = [col for col in data.columns if 'jwst' in col][:3]
for band in band_cols:
if band in data.columns:
# Linear, quadratic, and cubic terms
feature_df[f"{band}_log"] = np.log10(data[band])
feature_df[f"{band}_log2"] = np.log10(data[band])**2
feature_df[f"{band}_log3"] = np.log10(data[band])**3
return feature_df
# Use custom function
catalog = Catalog(path="survey_data.fits")
custom_features = catalog.create_feature_dataframe(custom_func=polynomial_features)
Notes
- Data validation: Requires valid photometric bands identified during catalog initialization
- Index preservation: All feature operations maintain the original data index
- Memory usage: Default pipeline roughly triples the feature count (bands + colors + squared colors)
- NaN handling: Method reports NaN counts but doesn't remove them (use
drop_nan()if needed) - Custom functions: Must return DataFrame with identical index to original data
- Storage: Result is automatically stored as
self.features_dffor later use - Error recovery: Returns None on failure while logging specific error details
Default Feature Set
For n photometric bands, creates approximately:
- n log-photometry features: One per validated band
- n(n-1)/2 color features: All unique band pair combinations
- n(n-1)/2 squared color features: Squared versions of colors
- Total: n + n(n-1) ≈ n² features for large n
See Also
get_features: Retrieve stored features (creates them if needed) remove_negative_fluxes: Clean data before feature creation split_data: Create train/validation/test splits of features get_features_from_phots: Lower-level feature creation from photometry subset
transform ¶
Apply a transformation function to a column and save the result.
This method provides a flexible way to transform data in a specified column using any callable function. The transformation can either replace the original column (inplace=True) or create a new column with the transformed data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column_name
|
str
|
Name of the column to transform. Must exist in the loaded dataset. The column can contain any data type that the transformation function can handle. |
required |
transform_func
|
callable
|
required | |
new_column_name
|
str or None, default=None
|
Name for the transformed column. If None and not inplace, will automatically generate a name using f"{column_name}transformed" or f"{column_name}" if the function has a recognizable name attribute. |
None
|
inplace
|
bool, default=False
|
If True, overwrite the original column with transformed data. If False, create a new column with the transformed data, preserving the original column. |
False
|
Returns:
| Type | Description |
|---|---|
|
pandas.Series or None: The transformed column as a pandas.Series if successful, with proper indexing matching the original DataFrame. Returns None if transformation fails due to errors, invalid inputs, or missing data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the specified column_name is not found in the DataFrame. |
TypeError
|
If transform_func is not callable. |
Exception
|
For any transformation execution errors (logged and returns None). |
Examples:
Photometry logarithmic transformation:
```python
# Apply log10 transformation directly to the column
import numpy as np
catalog.transform('phot_col', np.log10)
```
Notes
- The method automatically handles conversion of transformation results to pandas.Series
- Validates all input parameters before attempting transformation
- Maintains original DataFrame index in the transformed data
- Function names are automatically detected for column naming when possible
get_targets ¶
Extract target columns from the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_names
|
(str or list
|
Name(s) of target column(s) to extract. |
required |
drop_na
|
(bool, default=False
|
If True, drop rows with NA values in any of the target columns. |
required |
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame or pandas.Series: Target column(s). Returns a Series if a single target name is provided, or a DataFrame if multiple targets are requested. |
get_train_len ¶
Get the length of the training split
Returns:
| Name | Type | Description |
|---|---|---|
int |
The length of the training set, or None if it doesn't exist |
get_val_len ¶
Get the length of the validation split
Returns:
| Name | Type | Description |
|---|---|---|
int |
The length of the validation set, or None if it doesn't exist |
get_test_len ¶
Get the length of the test split
Returns:
| Name | Type | Description |
|---|---|---|
int |
The length of the testing set, or None if it doesn't exist |
get_features ¶
Get the feature dataframe, creating it if it doesn't exist.
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: The feature dataframe. |
get_feature_names ¶
Get the feature names dataframe, creating it if it doesn't exist.
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: The names of the feature dataframe columns. |
get_length ¶
Get the length saved data from the Catalog instance.
Returns:
| Type | Description |
|---|---|
|
int or None: The length of the saved data, or else None |
get_valid_bands ¶
Get information about valid band columns in the data.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary of valid band columns with their metadata. |
get_valid_bands_list ¶
Get information about valid band columns in the data.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary of valid band columns with their metadata. |
get_band_wavelengths ¶
Get a dictionary mapping band columns to their wavelengths.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary mapping column names to wavelengths in microns. |
get_band_shorthands ¶
Get a dictionary mapping band columns to their shorthand names.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary mapping column names to shorthand identifiers. |
sn_cut ¶
Perform a signal-to-noise ratio cut on the specified columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
dict or None
|
None
|
|
threshold
|
float, default=3.0
|
Minimum S/N ratio to keep a row. |
3.0
|
inplace
|
bool, default=False
|
If True, modifies the data in place; otherwise, returns a copy. |
False
|
suffix
|
str, default='_err'
|
Suffix to append to band names to find error columns, if columns=None. |
'_err'
|
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame or None: Filtered dataframe if inplace=False, otherwise None. |
get_data ¶
Return the loaded dataframe.
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: The loaded data. |
get_columns ¶
Return the column names of the loaded dataframe.
Returns:
| Name | Type | Description |
|---|---|---|
list |
List of column names. |
get_subset ¶
Get a subset of the data by columns and/or rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
list, default=None
|
List of column names to include. If None, includes all columns. |
None
|
rows
|
slice, list, default=None
|
Rows to include. Can be a slice (e.g., slice(0, 100)), a list of indices,or None to include all rows. |
None
|
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame or None: Subset of the data, or None if no data to load. |
save_to_csv ¶
Save the current data to a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_path
|
str
|
Path to save the CSV file. |
required |
index
|
bool, default=False
|
Whether to include the index in the saved file. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if successful, False otherwise. |
drop_nan ¶
Drop rows with NaN values in specified columns or validated columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
list or None, default=None
|
List of column names to check for NaN. If None, uses all validated columns. |
None
|
inplace
|
bool, default=False
|
If True, performs operation in-place and returns None. If False, returns a copy of the data with rows dropped. |
False
|
how
|
str, default='any'
|
How to drop nan values. Options are: 'any' : Drop if any of the specified columns has NaN 'all' : Drop only if all of the specified columns have NaN |
'any'
|
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame or None: The DataFrame with NaN rows dropped, or None if inplace=True. |
split_data ¶
Split the data into train, validation, and test sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
test_size
|
float, default=0.2
|
Proportion of the data to use for testing (0.0 to 1.0). |
0.2
|
val_size
|
float, default=0.2
|
Proportion of the data to use for validation (0.0 to 1.0). |
0.2
|
random_state
|
int or None, default=None
|
Random seed for reproducibility. |
None
|
stratify_col
|
str or None, default=None
|
Column name to use for stratified splitting. If provided, ensures proportional representation of this column's values in all splits. For continuous columns, binning will be applied. |
None
|
n_bins
|
int, default=10
|
Number of bins to use when stratifying on a continuous column. Only used when stratify_col is a continuous variable. |
10
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(train_indices, val_indices, test_indices) - Indices for each split |
get_split_df ¶
get_split_df(split_type='train', include_features=True, include_target=None, return_DMatrix=False, missing=np.nan)
Get a dataframe for the specified data split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
split_type
|
str, default='train'
|
Which data split to use. Options: 'train', 'val'/'validation', or 'test'. |
'train'
|
include_features
|
bool, default=True
|
If True, include the feature columns in the result. |
True
|
include_target
|
str, list, or None, default=None
|
Target column(s) to include. If None, no target columns are included. |
None
|
return_DMatrix
|
bool, default = False
|
Whether to return a XGBoost DMatrix instead of a pandas Dataframe. |
False
|
missing
|
int, float, or None, default=np.nan
|
Value to represent missing values in XGBoost. |
nan
|
Returns:
| Type | Description |
|---|---|
|
pandas.DataFrame: DataFrame for the specified split with requested columns. |
AGNBoost Class¶
The AGNBoost class provides the machine learning functionality, including model training, hyperparameter tuning, and prediction with uncertainty quantification.
Key Features¶
- XGBoostLSS integration for distributional modeling
- Hyperparameter optimization
- Model persistence and loading
- Multi-target support
- Comprehensive logging and validation
A machine learning framework for simultaneous AGN identification and photometric redshift estimation.
AGNBoost utilizes the XGBoostLSS algorithm to predict both the fraction of mid-IR 3-30 μm emission attributable to an AGN power law (fracAGN) and photometric redshift from JWST NIRCam and MIRI photometry. The framework analyzes 121 input features derived from multi-band infrared observations, including original magnitudes, color indices, and their squared values to enhance AGN discrimination. The computational efficiency and scalability make AGNBoost well-suited for large-scale JWST surveys requiring rapid AGN identification and redshift estimation.
Attributes:
| Name | Type | Description |
|---|---|---|
models_dir |
str
|
Directory path for storing/loading trained models. |
models |
dict
|
Dictionary containing trained XGBoostLSS models for each target variable. |
model_info |
dict
|
Dictionary storing metadata and performance information for each model. |
feature_names |
list
|
Feature (column) names used for model input. |
target_variables |
dict
|
Dictionary mapping target variable names to their probability distributions. |
logger |
Logger
|
Logger instance for this AGNBoost object. |
ALLOWED_DISTS |
list
|
Class-level list of allowed probability distributions ['ZABeta', 'Beta']. |
Examples:
Basic usage with default settings:
from agnboost import AGNBoost
# Initialize with defaults
agnboost = AGNBoost()
# Train models (assuming you have training data)
agnboost.train(training_data)
# Make predictions
predictions = agnboost.predict(test_data)
Initialize with custom target variables:
Initialize with custom features:
features = ['F115W', 'F150W', 'F200W', 'F277W', 'F770W', 'F1000W', 'F1130W']
agnboost = AGNBoost(feature_names=features)
get_models ¶
Get the feature dataframe, creating it if it doesn't exist.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary containing all models. Model values will be None if a model has not been loaded or trained. |
tune_model ¶
tune_model(model_name, param_grid, dtune, split_type='train', max_minutes=10, nfold=2, early_stopping_rounds=100)
Tune hyperparameters for the specified model with Optuna.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Name of the model to tune. Must be in self.model_names. |
required |
param_grid
|
dict
|
required | |
dtune
|
DMatrix or DataFrame or Catalog
|
Data to use for tuning. If DataFrame or Catalog, will be converted to DMatrix. |
required |
max_minutes
|
int, default=10
|
Maximum duration for tuning in minutes. |
10
|
nfold
|
int, default=2
|
Number of cross-validation folds. |
2
|
early_stopping_rounds
|
int, default=100
|
Number of rounds without improvement before early stopping. |
100
|
Returns:
| Type | Description |
|---|---|
|
dict or None: Dictionary containing best parameters and tuning metrics. Returns None if error is encountered. |
retrieve_dist
staticmethod
¶
Retrieve a configured XGBoostLSS model.
Creates and returns an XGBoostLSS object with the specified probability distribution and configuration parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist_name
|
str
|
Name of the probability distribution to use. Must be one of the values in ALLOWED_DISTS ['ZABeta', 'Beta']. |
required |
response_fn
|
str
|
Response function for the distribution parameters. Common options include 'exp', 'softplus'. If None and params is provided, uses value from params. Defaults to None. |
None
|
stab
|
str
|
Stabilization method for gradients and Hessians to improve model convergence. Options include 'None', 'L2', 'MAD'. If None and params is provided, uses value from params. Defaults to None. |
None
|
loss_fn
|
str
|
Loss function to use for training. Typically 'nll' (negative log-likelihood). If None and params is provided, uses value from params. Defaults to None. |
None
|
params
|
dict
|
Dictionary containing distribution parameters. If provided, overrides individual parameter arguments. Expected keys: 'stabilization', 'response_fn', 'loss_fn'. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
XGBoostLSS |
Configured XGBoostLSS model with the specified distribution, or None if an error occurs during object creation. |
Raises:
| Type | Description |
|---|---|
Exception
|
If there's an error creating the XGBoostLSS object, logs the error and returns None. |
Examples:
Create a ZABeta distribution with default parameters:
Create a Beta distribution with custom parameters:
Create using a parameters dictionary:
custom_objective
staticmethod
¶
custom_objective(trial, hp_dict, dist, d_train, nfold, num_boost_round, early_stopping_rounds, seed)
Custom objective function for Optuna hyperparameter optimization.
Defines the optimization objective for tuning hyperparameters using Optuna. The function constructs hyperparameter combinations based on the provided search space, trains models using cross-validation, and returns the validation loss for optimization. Supports automatic pruning of unpromising trials and handles various parameter types including categorical, float, and integer parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trial
|
Trial
|
Optuna trial object used for suggesting hyperparameter values and managing the optimization process. |
required |
hp_dict
|
dict
|
Dictionary defining the hyperparameter search space. Each key is a parameter name, and values are tuples of (param_type, param_constraints) where param_type is one of ['categorical', 'float', 'int', 'none'] and param_constraints define the search range or options. |
required |
dist
|
str
|
Name of the probability distribution to use. Must be one of the values in ALLOWED_DISTS ['ZABeta', 'Beta']. |
required |
d_train
|
DMatrix
|
Training data in XGBoost DMatrix format for cross-validation. |
required |
nfold
|
int
|
Number of folds for cross-validation during hyperparameter optimization. |
required |
num_boost_round
|
int
|
Maximum number of boosting rounds to train. |
required |
early_stopping_rounds
|
int
|
Number of rounds with no improvement after which training will be stopped early. |
required |
seed
|
int
|
Random seed for reproducible results across trials. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
The minimum cross-validation test score (loss) achieved by the model with the suggested hyperparameters. Lower values indicate better performance. |
Notes
The function automatically handles special XGBoostLSS parameters ('stabilization', 'response_fn', 'loss_fn') separately from standard XGBoost parameters to avoid warnings during model training. It also implements Optuna's XGBoost pruning callback to terminate unpromising trials early, improving optimization efficiency.
custom_tune_function
staticmethod
¶
custom_tune_function(hp_dict, dist, dtrain, n_trials=None, max_minutes=10, num_boost_round=500, nfold=10, early_stopping_rounds=20, seed=123, metrics=None)
Perform hyperparameter optimization for AGNBoost models using Optuna. This offers the same functionality of XGBoostLSS's built-in hyperparameter tuning, but also allows the tuning of distributional parameters.
Automatically selects the optimal hyperparameter tuning strategy based on the search space characteristics. Uses grid search for purely categorical parameters and Bayesian optimization (TPE) for mixed or continuous parameter spaces. Implements pruning to terminate unpromising trials early and provides comprehensive optimization results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hp_dict
|
dict
|
Dictionary defining the hyperparameter search space. Each key is a parameter name, and values are tuples of (param_type, param_constraints) where param_type is one of ['categorical', 'float', 'int', 'none']. |
required |
dist
|
str
|
Name of the probability distribution to use. Must be one of the values in ALLOWED_DISTS ['ZABeta', 'Beta']. |
required |
dtrain
|
DMatrix
|
Training data in XGBoost DMatrix format for cross-validation. |
required |
n_trials
|
int
|
Maximum number of optimization trials to run. If None and all parameters are categorical, uses grid search to try all combinations. Defaults to None. |
None
|
max_minutes
|
int
|
Maximum time limit for optimization in minutes. Optimization will stop after this duration regardless of n_trials. Defaults to 10. |
10
|
num_boost_round
|
int
|
Maximum number of boosting rounds for each trial. Defaults to 500. |
500
|
nfold
|
int
|
Number of folds for cross-validation during optimization. Defaults to 10. |
10
|
early_stopping_rounds
|
int
|
Number of rounds with no improvement after which training will be stopped early. Defaults to 20. |
20
|
seed
|
int
|
Random seed for reproducible optimization results. Defaults to 123. |
123
|
metrics
|
optional
|
Additional metrics to track during optimization. Currently unused. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
|
optuna.Study: Completed Optuna study object containing optimization results, including best parameters, trial history, and performance metrics. |
Notes
The function automatically determines the optimization strategy: if all parameters are categorical, it uses grid search to exhaustively try all combinations. Otherwise, it uses Tree-structured Parzen Estimator (TPE) for Bayesian optimization. Median pruning is applied to terminate unpromising trials early, improving efficiency. The optimal number of boosting rounds is automatically determined and included in the returned results.
plot_eval
staticmethod
¶
Plot the training and validation loss curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
evals
|
dict
|
Dict of model evaluations. |
required |
catalog
|
Catalog instance
|
Catalog object used for training. Used to scale the training/validation curves according to the training/validation sizes. |
required |
Returns:
| Type | Description |
|---|---|
|
matplotlib.pyplot.axis: The figure axis. |
train_model ¶
train_model(model_name, dtrain, dval=None, params=None, split_type='train', num_boost_round=1000, early_stopping_rounds=None, verbose_eval=False, custom_objective=None, custom_metric=None)
Train an AGNBoost model with the given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Name of the model to train. Must be in self.model_names. |
required |
dtrain
|
DMatrix or Catalog
|
Training data. If a Catalog, will create a DMatrix using the specified split. |
required |
dval
|
xgboost.DMatrix, bool, default=None
|
Validation data. If a DMatrix, use directly. If True and dtrain is a Catalog, create a validation DMatrix from the Catalog. If False or None, no validation data is used. |
None
|
params
|
dict, default=None
|
Dict of model hyperparameters to use If None, uses saved tuned_params from model_info if available, otherwise uses default parameters. |
None
|
split_type
|
str, default='train'
|
Which data split to use if dtrain is a Catalog. Options: 'train', 'val', 'test'. |
'train'
|
num_boost_round
|
int, default=1000
|
Number of boosting rounds. |
1000
|
early_stopping_rounds
|
int or None, default=50
|
Number of rounds without improvement before early stopping. If None, no early stopping is used. |
None
|
verbose_eval
|
int or bool, default=100
|
Controls XGBoost's logging frequency. If True, prints every round. If int, prints every verbose_eval rounds. If False, no logging. |
False
|
custom_objective
|
callable, default=None
|
Custom objective function for XGBoost. |
None
|
custom_metric
|
callable, default=None
|
Custom evaluation metric for XGBoost. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(trained_model, training_results) |
get_available_files
staticmethod
¶
Get all available files in the provided path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the directory to check. |
required |
Returns:
| Type | Description |
|---|---|
|
list or None: list of file paths, or None if the path does not exist. |
get_available_models ¶
Get all available models. Will either get all available models for the provided target, or will return a list of the avilable model types (e.g., fracAGN, redshift, etc.).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_name
|
str, default=None
|
name of model type to check. |
None
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the directory for the passed target does not yet exist. |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list of available models or model types. |
load_model ¶
Load a pre-trained model and its metadata from into the AGNBoost instance.
Deserializes a previously saved XGBoostLSS model from pickle or gzip format and restores it to the AGNBoost instance. Performs comprehensive validation including feature compatibility checks, model data structure verification, and metadata restoration. Supports automatic selection of the most recent model file if no specific filename is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Name of the target variable model to load. Must correspond to a valid model type (e.g., 'fagn', 'z_transformed'). |
required |
file_name
|
str
|
Specific filename of the model to load. If None, automatically selects the most recently modified file in the model subdirectory. Can include or omit the '.pkl' extension. Supports both '.pkl' and '.gz' formats. Defaults to None. |
None
|
overwrite
|
bool
|
Whether to overwrite an already loaded model in the AGNBoost instance. If False and a model is already loaded, the operation will fail. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if the model was loaded successfully, False if an error occurred during loading, validation, or if overwrite constraints were violated. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the model subdirectory doesn't exist or no model files are found in the expected directory. |
UnpicklingError
|
If the file is corrupted or not a valid pickle file. |
Exception
|
For other unexpected errors during the loading process. |
Examples:
Load the most recent model file automatically:
Load a specific model file:
# Load a specific model file
success = agnboost.load_model('z_transformed', 'my_redshift_model.pkl')
Load with filename without extension:
# The .pkl extension is automatically added
success = agnboost.load_model('fagn', 'final_agn_model')
Overwrite an existing loaded model:
# Replace currently loaded model with a different one
success = agnboost.load_model('fagn', 'newer_model.pkl', overwrite=True)
Load a compressed model:
# Automatically handles gzip compressed files
success = agnboost.load_model('z_transformed', 'compressed_model.pkl.gz')
Notes
The method performs several validation steps:
- Verifies input parameter types and values
- Checks model subdirectory existence
- Validates loaded model data structure
- Compares feature compatibility between saved and current models
- Ensures model names match expected targets
Feature compatibility is strictly enforced - the loaded model must have been trained with identical features to the current AGNBoost instance. Any mismatch will result in loading failure with detailed logging of differences.
The method supports both pickle (.pkl) and gzip-compressed (.pkl.gz) formats automatically based on file extension. Model metadata including training parameters, performance metrics, and timestamps are restored along with the model object.
If no specific filename is provided, the method automatically selects the most recently modified file in the model subdirectory, making it easy to load the latest trained model.
dmatrix_validate ¶
Validate and convert input data to XGBoost DMatrix format.
Handles multiple input data formats and converts them to the standardized DMatrix format required by XGBoost models. Supports Catalog objects with optional data split selection, and validates existing DMatrix objects. Performs feature extraction and handles missing value encoding for optimal XGBoost compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Catalog or DMatrix
|
Input data to validate and convert. If Catalog, extracts features and optionally applies data splitting. If DMatrix, validates and passes through unchanged. |
required |
split_use
|
str
|
Specific data split to use when data is a Catalog. Common values include 'train', 'val', 'test', 'trainval'. If None and data is a Catalog, uses the entire feature dataset. Ignored if data is already a DMatrix. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
|
xgboost.DMatrix or None: Validated DMatrix object ready for XGBoost operations, or None if validation fails or an error occurs during conversion. |
predict ¶
Generate predictions using an internal trained XGBoostLSS model for the specified target variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
pandas.DataFrame, Catalog, or xgboost.DMatrix
|
Input data for prediction. If Catalog, can optionally specify which data split to use. If DataFrame, must contain all required features. If DMatrix, used directly for prediction. |
required |
model_name
|
str
|
Name of the specific model to use for predictions. Must correspond to a trained model in the AGNBoost instance (e.g., 'fagn', 'z_transformed'). |
required |
split_use
|
str
|
Specific data split to use when data is a Catalog object. Common values include 'train', 'val', 'test', 'trainval'. Ignored if data is not a Catalog. Defaults to None. |
None
|
seed
|
int
|
Random seed for reproducible prediction results. Ensures consistent outputs across multiple prediction runs with identical inputs. Defaults to 123. |
123
|
Returns:
| Type | Description |
|---|---|
|
numpy.ndarray or None: Array of prediction expectation values for the target variable, or None if prediction fails due to data validation errors, model unavailability, or feature compatibility issues. |
Examples:
Predict AGN fractions on test data:
# Using a Catalog with test split
fagn_predictions = agnboost.predict(catalog, 'fagn', split_use='test')
Predict redshifts on new data:
Predict on validation set with custom seed:
# Reproducible predictions on validation data
predictions = agnboost.predict(catalog, 'fagn', split_use='val', seed=42)
Handle prediction errors gracefully:
predictions = agnboost.predict(data, 'fagn')
if predictions is not None:
print(f"Generated {len(predictions)} predictions")
else:
print("Prediction failed - check data and model status")
Notes
Prediction Type: Returns expectation values (means) of the predicted probability distributions rather than raw distribution parameters.
When using the pre-trained models: For AGN models, predictions typically represent fracAGN values (0-1 range). For redshift models, predictions represent transformed redshift values that may require inverse transformation to obtain physical redshift units.
prediction_uncertainty ¶
prediction_uncertainty(uncertainty_type, catalog, model_name, split_use=None, seed=123, M=10, num_permutation=100)
Estimate total predictive uncertainty for a trained model. Will return the model uncertainty, uncertainty due to photometric error, or the combination of the two depending on the value of 'uncertainty_type.' This allows for robust uncertainty quantification for AGNBoost estimates, accounting for all types of uncertainty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uncertainty_type
|
str
|
The type of uncertainty to estimate. Allowed values are: 'all', 'photometric', 'model' |
required |
catalog
|
Catalog instance
|
the Catalog object to take data from. |
required |
model_name
|
str
|
Name of the model to retrieve. Must be a key in the models dictionary and correspond to a valid target variable (e.g., 'fagn', 'z_transformed'). |
required |
split_use
|
str, default=None
|
Specific data split to use when data is a Catalog object. Common values include 'train', 'val', 'test', 'trainval'. Ignored if data is not a Catalog. Defaults to None. |
None
|
M
|
int, default=10
|
Number of models in the virtual ensemble. Controls the granularity of epistemic uncertainty estimation. Higher values provide more detailed uncertainty estimates but increase computation time. Defaults to 1. |
10
|
seed
|
int, default = 123
|
Random seed for reproducible uncertainty estimates. Ensures consistent results across multiple runs with identical inputs. Defaults to 123. |
123
|
num_permutation
|
int, default=100
|
Number of Monte Carlo iterations to run if calculating the uncertainty due to photometric uncertainty. |
100
|
Returns:
| Type | Description |
|---|---|
|
np.ndarray or None: Array of total uncertainty estimates for each input sample. For single samples, returns a scalar value. For multiple samples, returns an array with one uncertainty value per input. |
model_uncertainty
staticmethod
¶
model_uncertainty(model: model, data: DMatrix, dist_name: str, best_iter: int, M: int = 1, seed=123) -> np.array
Estimate total predictive uncertainty by decomposing epistemic and aleatoric components.
Implements uncertainty quantification for XGBoostLSS models using a virtual ensemble approach based on boosting iteration truncation. Creates multiple model snapshots at different training stages to approximate epistemic (model) uncertainty, while extracting aleatoric (data) uncertainty from the predicted distributions. Returns the total uncertainty as the combination of both components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
model
|
Trained XGBoostLSS model object containing the booster, distribution, and starting values needed for prediction. |
required |
data
|
DMatrix
|
Input data in XGBoost DMatrix format for which uncertainty estimates will be computed. Can contain single or multiple samples. |
required |
dist_name
|
str
|
Name of the probability distribution used by the model. Must match one of the supported distribution types (e.g., 'ZABeta', 'Beta'). |
required |
best_iter
|
int
|
Best iteration number from model training, typically obtained from early stopping or validation-based selection. Used as the reference point for creating the virtual ensemble. |
required |
M
|
int
|
Number of models in the virtual ensemble. Controls the granularity of epistemic uncertainty estimation. Higher values provide more detailed uncertainty estimates but increase computation time. Defaults to 1. |
1
|
seed
|
int
|
Random seed for reproducible uncertainty estimates. Ensures consistent results across multiple runs with identical inputs. Defaults to 123. |
123
|
Returns:
| Type | Description |
|---|---|
array
|
np.ndarray: Array of total uncertainty estimates for each input sample. For single samples, returns a scalar value. For multiple samples, returns an array with one uncertainty value per input. |
uncertainty_phot
staticmethod
¶
uncertainty_phot(model: model, catalog: Catalog, dist_name: str, num_permutation=100, seed=123) -> np.ndarray
Estimate the prediction uncertainty due to photometric uncertainty. Performs monte carlo, randomly sampling the photometric bands (assuming a normal flux distribution) accoridng to the photometric error bands stored in the catalog object's data. The standard deviation of the monte carlo preditions is taken to be the prediction uncertainty due to photometric uncertainty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
model
|
The trained model to use to make predictions. |
required |
catalog
|
Catalog instance
|
the Catalog object to take data from. |
required |
dist_name
|
str
|
The name of the probability distribution type to make predictions with This should correspond to the distribution stored in self.target_variables[model_name] |
required |
seed
|
int, default = 123
|
Random seed for reproducible uncertainty estimates. Ensures consistent results across multiple runs with identical inputs. Defaults to 123. |
123
|
num_permutation
|
int, default=100
|
Number of Monte Carlo iterations to run if calculating the uncertainty due to photometric uncertainty. |
100
|
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray or None: Array of the uncertainty estimates. |
Utility Functions¶
Helper functions for data processing, feature engineering, and model management.
log_message ¶
Log a message with the specified level.
Parameters:¶
message : str Message to log. level : str Log level (INFO, WARNING, ERROR).
validate_param_grid ¶
Validate that the parameter grid is correctly formatted.
Expected format: { "param_name": ["type", type_specific_value], ... }
Where "type" is one of: - "none": type_specific_value should be a list of specific values - "int": type_specific_value should be a dict with "low", "high", "log" keys - "float": type_specific_value should be a dict with "low", "high", "log" keys - "categorical": type_specific_value should be a list of possible values
Parameters:¶
param_grid : dict Dictionary of parameter grid specifications
Returns:¶
tuple (is_valid, error_message) - (True, None) if valid, (False, error_msg) if invalid