Data, Metrics, And Utilities¶
Data Cleaning¶
matgpr.data_cleaning
¶
normalize_column_names(df)
¶
Return a copy with consistent lowercase snake_case column names.
Use this as an early cleaning step so later functions can refer to stable feature names. Non-alphanumeric runs are converted to underscores, leading and trailing underscores are removed, and duplicate generated names receive a numeric suffix.
Source code in matgpr/data_cleaning.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
replace_missing_placeholders(df, placeholders=('', 'nan', 'none', 'null', 'na', 'n/a', '-'))
¶
Replace common string placeholders for missing values with np.nan.
Only object/string-like columns are inspected. Numeric columns are left unchanged so valid numeric zeros or negative values cannot be altered by accident.
Source code in matgpr/data_cleaning.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
drop_duplicate_rows(df, subset=None, *, reset_index=True)
¶
Remove duplicate rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input dataframe. |
required |
subset
|
Iterable[str] | None
|
Optional columns used to identify duplicates. When omitted, every column is considered. |
None
|
reset_index
|
bool
|
If |
True
|
Source code in matgpr/data_cleaning.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
drop_columns_by_missing_fraction(df, max_missing_fraction=0.5, *, return_dropped=False)
¶
Drop columns whose missing fraction is above max_missing_fraction.
max_missing_fraction=0.5 keeps columns with up to 50 percent missing
values and removes columns with more missing data than that.
Source code in matgpr/data_cleaning.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
impute_missing_values(df, *, strategy='median', columns=None, fill_value=None, return_imputer=False)
¶
Impute missing values in selected dataframe columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input dataframe. |
required |
strategy
|
str
|
Any |
'median'
|
columns
|
Iterable[str] | None
|
Columns to impute. If omitted, numeric columns are selected. |
None
|
fill_value
|
object | None
|
Replacement value used only when |
None
|
return_imputer
|
bool
|
If |
False
|
Source code in matgpr/data_cleaning.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
filter_iqr_outliers(df, columns, *, factor=1.5, drop_if='any', reset_index=True)
¶
Remove rows with IQR outliers in selected numeric columns.
Missing values are preserved by the filter. Use imputation before or after this step depending on whether missing values should influence the computed quartiles.
drop_if="any" keeps the historical behavior: a row is removed if it is
an outlier in at least one selected column. drop_if="all" removes a row
only when it is an outlier in every selected column.
Source code in matgpr/data_cleaning.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
Data Splitting¶
matgpr.data_splitting
¶
separate_features_target(df, target_column)
¶
Split a dataframe into feature columns X and target vector y.
This is the first modeling split: it separates the column to predict from the columns used as model inputs.
Source code in matgpr/data_splitting.py
12 13 14 15 16 17 18 19 20 21 22 23 24 | |
split_train_test(X, y, *, test_size=0.2, random_state=42, shuffle=True, stratify=None)
¶
Split features and targets into train/test sets.
Parameters mirror sklearn.model_selection.train_test_split so the
returned values are X_train, X_test, y_train, y_test.
Source code in matgpr/data_splitting.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
Preprocessing¶
matgpr.preprocessing
¶
identify_feature_types(X)
¶
Identify numeric and categorical feature columns in a dataframe.
Returns:
| Type | Description |
|---|---|
(numeric_features, categorical_features)
|
Lists that can be passed directly into |
Source code in matgpr/preprocessing.py
18 19 20 21 22 23 24 25 26 27 28 | |
build_scaler(name='standard')
¶
Create a scikit-learn feature scaler by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
|
'standard'
|
Source code in matgpr/preprocessing.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | |
build_preprocessor(*, numeric_features=None, categorical_features=None, scaler='standard', numeric_imputation='median', categorical_imputation='most_frequent')
¶
Build a reusable scikit-learn preprocessing transformer.
Fit this transformer only on training data, then reuse it for validation, test, or prediction data. Numeric columns are imputed and optionally scaled; categorical columns are imputed and one-hot encoded.
Source code in matgpr/preprocessing.py
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | |
Metrics¶
The numerical metric helpers keep scientifically undefined values as NaN.
Use the JSON-safe companion helpers when metrics must be serialized through a
strict JSON encoder or API response.
matgpr.metrics
¶
regression_metrics(y_true, y_pred, *, prefix='')
¶
Calculate common regression metrics for model analysis.
The returned dictionary contains R2, RMSE, MAE, and Pearson r. Use
prefix to distinguish train/test metrics when storing experiment
results, for example prefix="test" gives test_R2.
Source code in matgpr/metrics.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
train_test_regression_metrics(y_train_true, y_train_pred, y_test_true, y_test_pred)
¶
Calculate regression metrics for both train and test predictions.
Source code in matgpr/metrics.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
json_safe_metrics(metrics, *, include_warnings=True, warning_key='metric_warnings')
¶
Return a strict-JSON-safe copy of a metric dictionary.
Scientific metrics such as R2, Pearson r, or calibration correlations can
be undefined for legitimate edge cases, including one-sample splits or
constant arrays. The numerical metric helpers keep those values as
NaN. This helper converts non-finite scalar values to None so the
result can be serialized with json.dumps(..., allow_nan=False).
Source code in matgpr/metrics.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | |
json_safe_regression_metrics(y_true, y_pred, *, prefix='', include_warnings=True, warning_key='metric_warnings')
¶
Calculate regression metrics and return a strict-JSON-safe dictionary.
Source code in matgpr/metrics.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
json_safe_train_test_regression_metrics(y_train_true, y_train_pred, y_test_true, y_test_pred, *, include_warnings=True, warning_key='metric_warnings')
¶
Calculate train/test regression metrics with non-finite values as None.
Source code in matgpr/metrics.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |
PCA¶
matgpr.pca
¶
fit_pca(X, n_components=None, *, scale=False)
¶
Fit PCA and return component scores, the fitted PCA, and optional scaler.
DataFrames are reduced to numeric columns before PCA. Set scale=True to
fit a StandardScaler before PCA; the fitted scaler is returned so new
data can be transformed consistently.
Source code in matgpr/pca.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | |
summarize_pca(pca)
¶
Return explained and cumulative variance for a fitted PCA model.
Source code in matgpr/pca.py
44 45 46 47 48 49 50 51 52 53 | |
transform_pca(X, pca, *, scaler=None, imputer=None)
¶
Transform new data using an already-fitted PCA model.
Pass the same scaler and imputer used for training data so new data follows the identical preprocessing path.
When pca was fitted on a dataframe, the numeric columns of X must
match the training columns exactly, including their order. A mismatch
raises rather than silently producing scores from misaligned features.
Source code in matgpr/pca.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
Reporting¶
matgpr.reporting
¶
summarize_missingness(df)
¶
Return missing counts and fractions by column.
Source code in matgpr/reporting.py
16 17 18 19 20 21 22 23 24 25 | |
summarize_numeric_columns(df)
¶
Return descriptive statistics for numeric columns.
Source code in matgpr/reporting.py
28 29 30 | |
decompose_multifidelity_prediction(prediction, *, y_true=None, sample_labels=None, model_name='multi_fidelity_gpr', split='prediction')
¶
Return a per-sample component table for a multi-fidelity prediction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prediction
|
Object with a |
required | |
y_true
|
Optional measured high-fidelity values. When supplied, signed and absolute prediction errors are added. |
None
|
|
sample_labels
|
Sequence[object] | None
|
Optional sample identifiers. If omitted, integer positions are used. |
None
|
model_name
|
str
|
Labels stored in the returned dataframe for reporting and grouping. |
'multi_fidelity_gpr'
|
split
|
str
|
Labels stored in the returned dataframe for reporting and grouping. |
'multi_fidelity_gpr'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Per-sample rows with the high-fidelity prediction and any available low-fidelity, correction, and uncertainty components. |
Source code in matgpr/reporting.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
summarize_multifidelity_components(components, *, group_by=None)
¶
Summarize multi-fidelity prediction components for reports.
components can be either a per-sample dataframe, such as the
predictions table returned by multifidelity_learning_curve with
store_predictions=True, or a prediction object accepted by
:func:decompose_multifidelity_prediction.
The summary reports low-fidelity and correction contribution statistics,
uncertainty component statistics, reconstruction residuals, and prediction
error metrics when y_true is available.
Source code in matgpr/reporting.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
Artifact IO¶
log_experiment_result appends experiment rows to a schema-safe CSV log. When
new runs add or omit metric columns, the existing file is realigned to the
union of columns and remains readable by pandas.read_csv.
matgpr.io_utils
¶
save_artifact(artifact, path)
¶
Save a fitted preprocessor, model, or full pipeline with joblib.
Source code in matgpr/io_utils.py
17 18 19 20 21 | |
load_artifact(path)
¶
Load a joblib artifact saved by save_artifact.
Source code in matgpr/io_utils.py
24 25 26 | |
log_experiment_result(metrics, *, metadata=None, path='results.csv')
¶
Append one experiment result row to a schema-safe CSV file.
metadata is written before metric columns and is intended for values
such as model name, kernel, train size, random state, or feature set.
If the CSV already exists, the file is read, aligned to the union of old and new columns, and rewritten. Existing column order is preserved and new columns are appended at the end. This keeps experiment logs readable when later runs add or omit metrics.
Source code in matgpr/io_utils.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
Optional Dependencies¶
matgpr.optional_dependencies
¶
OptionalDependency
dataclass
¶
Metadata for an optional backend dependency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
import_name
|
str
|
Python import path used to import the package. |
required |
package_name
|
str
|
Package name users should install. |
required |
extra
|
str
|
|
required |
purpose
|
str
|
Short user-facing description of why the dependency is needed. |
required |
Source code in matgpr/optional_dependencies.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
require_optional_dependency(dependency, *, purpose=None, extra=None, package_name=None)
¶
Import an optional dependency or raise a clear installation message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dependency
|
str | OptionalDependency
|
Registered dependency name, Python import name, or explicit
|
required |
purpose
|
str | None
|
Optional purpose override for custom wrappers. |
None
|
extra
|
str | None
|
Optional |
None
|
package_name
|
str | None
|
Optional install package name override for custom wrappers. |
None
|
Source code in matgpr/optional_dependencies.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
is_optional_dependency_available(dependency)
¶
Return True when an optional dependency can be imported.
Source code in matgpr/optional_dependencies.py
135 136 137 138 139 140 141 142 | |
list_optional_dependencies()
¶
Return unique optional dependency metadata records.
Source code in matgpr/optional_dependencies.py
145 146 147 148 149 150 | |
Scikit-Learn GPR Helpers¶
matgpr.sklearn_gpr
¶
build_sklearn_gpr_kernel(name='matern', *, n_features=None, constant_value=1.0, constant_value_bounds=(0.001, 1000.0), length_scale=1.0, length_scale_bounds=(1e-05, 100000.0), noise_level=1e-06, noise_level_bounds=(1e-10, 0.1), nu=2.5, metric=None, normalize=True, feature_scales=None, validate_nonnegative=True)
¶
Create a common scikit-learn Gaussian-process kernel.
"ard_rbf" and "ard_matern" use one length scale per feature, so
n_features is required for those options.
Source code in matgpr/sklearn_gpr.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
build_sklearn_gpr_model(*, kernel='matern', n_features=None, alpha=1e-08, normalize_y=True, n_restarts_optimizer=5, random_state=42, **kernel_kwargs)
¶
Build a scikit-learn Gaussian Process Regressor.
This returns an unfitted model. Put it inside a scikit-learn Pipeline with
build_preprocessor when raw dataframe columns need preprocessing.
alpha may be a scalar or one variance per training row, which is useful
when appending soft virtual physics observations.
Source code in matgpr/sklearn_gpr.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |
build_sklearn_gpr_grid_search(*, n_features, cv=5, scoring='neg_root_mean_squared_error', random_state=42, n_jobs=1)
¶
Build a grid search over useful scikit-learn GPR kernels and settings.
Source code in matgpr/sklearn_gpr.py
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | |