API reference¶
The public API is importable from amesml. Modules are documented below in
pipeline order.
amesml.config ¶
Training configuration.
A :class:TrainConfig records every choice that changes a trained model. It is
saved inside each model's metadata.json, so any model can be retrained
exactly from its own metadata.
The defaults reproduce the original notebook: an unregularised linear model (or a logistic regression for classification) on the raw Ames columns, with an 80/20 split seeded with 42.
TrainConfig
dataclass
¶
Everything that determines how a model is trained.
Attributes:
| Name | Type | Description |
|---|---|---|
task |
TaskType
|
|
model |
ModelType
|
Estimator family. |
target |
str
|
Name of the sale-price column. |
id_column |
str | None
|
Identifier column that is never used as a feature. |
test_size |
float
|
Fraction of rows held out for evaluation. |
random_state |
int
|
Seed for the train/test split and every seeded estimator. |
threshold |
Threshold
|
Price separating the two classes, or |
stratify |
bool
|
Keep the class balance equal across the split. Only valid for classification. |
engineer_features |
bool
|
Add the derived features from
:mod: |
numeric_features |
tuple[str, ...] | None
|
Use exactly these numeric columns instead of inferring them from the data. |
categorical_features |
tuple[str, ...] | None
|
Use exactly these categorical columns instead of inferring them from the data. |
categorical_codes |
tuple[str, ...]
|
Columns stored as numbers that are really category
codes, such as the dwelling-type code |
zero_fill_features |
tuple[str, ...]
|
Numeric columns where a missing value means "none of this", so they are filled with 0 instead of the median. |
drop_first |
bool
|
Drop the first level of each one-hot encoded column, as the notebook did. This avoids the dummy-variable trap for the unregularised models. |
alpha |
float | None
|
Regularisation strength for |
max_iter |
int
|
Iteration limit for the iterative solvers. |
resolved_alpha
property
¶
The regularisation strength actually used, after applying defaults.
replace ¶
Return a copy with changes applied; the copy is validated too.
from_dict
classmethod
¶
Build a config from a mapping, rejecting unknown keys.
from_file
classmethod
¶
Load a config from a .yaml, .yml or .json file.
amesml.data ¶
Loading, validating and splitting the Ames Housing dataset.
The dataset is the Kaggle "House Prices: Advanced Regression Techniques"
train.csv: 1,460 sales from Ames, Iowa, with 79 candidate features, an
Id and the target SalePrice (De Cock, 2011).
In this file the string "NA" is a value, not an accident: it means the
house has no pool, no alley access, no basement, and so on. Elsewhere the
literal word "None" is a real category (MasVnrType == "None"), so pandas'
default list of missing-value markers - which includes "None" - would
silently destroy information. :func:read_ames_csv therefore treats only
"NA" and empty fields as missing, exactly as the original notebook did.
read_ames_csv ¶
Read an Ames-format CSV with the dataset's missing-value conventions.
No validation happens here, so this also reads prediction inputs that lack
the target column. Use :func:load_ames for the training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
CSV file to read. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
The parsed data. |
validate_ames ¶
Check that frame has the Ames columns with usable types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Data to check. |
required |
require_target
|
bool
|
Also require a numeric, positive, complete |
True
|
Raises:
| Type | Description |
|---|---|
AmesSchemaError
|
Describing every problem found, so they can all be fixed in one pass. |
load_ames ¶
load_ames(path: PathLike | None = None, *, download: bool = True, validate: bool = True) -> pd.DataFrame
Load the Ames Housing training data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike | None
|
CSV file to read. When omitted, |
None
|
download
|
bool
|
Allow the download when the default file is missing. |
True
|
validate
|
bool
|
Check the columns and types with :func: |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per sale, including |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
|
DatasetDownloadError
|
The default file had to be downloaded and could not be. |
AmesSchemaError
|
The data failed validation. |
download_ames ¶
download_ames(destination: PathLike | None = None, *, url: str = DATASET_URL, sha256: str | None = DATASET_SHA256, timeout: float = 60.0, force: bool = False) -> Path
Download the training CSV and verify its checksum.
The file is written to a temporary name and renamed only after the checksum matches, so an interrupted or tampered download never replaces good data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
destination
|
PathLike | None
|
Where to save the file; defaults to |
None
|
url
|
str
|
Source URL. |
DATASET_URL
|
sha256
|
str | None
|
Expected SHA-256 hex digest, or |
DATASET_SHA256
|
timeout
|
float
|
Network timeout in seconds. |
60.0
|
force
|
bool
|
Download even if |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
The path of the downloaded file. |
Raises:
| Type | Description |
|---|---|
DatasetDownloadError
|
The request failed or the checksum did not match. |
train_test_split_df ¶
train_test_split_df(frame: DataFrame, *, test_size: float = 0.2, random_state: int = 42, stratify: Sequence[Any] | Series | str | None = None) -> tuple[pd.DataFrame, pd.DataFrame]
Split whole rows into training and test frames.
With the defaults this selects the same rows as the notebook's
train_test_split(X, y, test_size=0.2, random_state=42).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Data to split. |
required |
test_size
|
float
|
Fraction of rows in the test frame. |
0.2
|
random_state
|
int
|
Seed for the shuffle. |
42
|
stratify
|
Sequence[Any] | Series | str | None
|
Labels to stratify on (use this for classification so both
classes keep their proportions), or the name of a column in
|
None
|
Returns:
| Type | Description |
|---|---|
tuple[DataFrame, DataFrame]
|
|
dataset_fingerprint ¶
Return a SHA-256 of the frame's contents, independent of platform.
Used in model metadata to record exactly which data a model was trained on.
The frame is serialised as CSV with \n line endings so the same data
hashes identically on every operating system.
amesml.features ¶
Derived features for the Ames data.
Each function takes a frame with the raw Ames columns and returns one new
column as a Series, without modifying its input. :func:add_engineered_features
applies all of them at once and is what the training pipeline uses when
TrainConfig.engineer_features is enabled, so a saved model recomputes these
columns from raw inputs at prediction time.
The original notebook did not engineer features; these are the standard Ames
derivations. They are opt-in so that the default models reproduce the notebook's
published results. See docs/benchmarks.md for their effect.
total_square_footage ¶
Basement plus first- and second-floor area, in square feet.
A missing basement area means there is no basement, so it counts as 0.
house_age ¶
Years between construction and sale, never negative.
remodel_age ¶
Years between the last remodel (or construction) and sale.
One record in the Kaggle data lists a remodel after the sale year; a negative age is meaningless, so it is clipped to 0.
total_bathrooms ¶
Full bathrooms plus half of the half-baths, above ground and in the basement.
total_porch_area ¶
Combined open, enclosed, three-season and screened porch area.
add_engineered_features ¶
Return a copy of frame with every engineered column appended.
Existing columns with the same names are overwritten, so applying the function twice gives the same result as applying it once.
Raises:
| Type | Description |
|---|---|
AmesSchemaError
|
A raw column needed by one of the features is missing. |
amesml.preprocess ¶
Column typing and the scikit-learn preprocessing transformer.
The transformer reproduces the notebook's choices, which follow from what a missing value means in this dataset:
- Numeric gaps are filled with the training median - except columns listed in
zero_fill_cols(MasVnrArea,GarageYrBlt), where a gap means the feature is absent rather than unknown. - Categorical gaps become the explicit level
"Missing".NAin Ames means "no pool", "no basement" and so on; filling it with the most frequent level would claim that houses without a pool have the most common pool quality. - Category codes stored as numbers (
MSSubClass,MoSold) get their own branch, filled with the most frequent code, because a column cannot mix the string"Missing"with integers and still be encoded.
FeatureTypes
dataclass
¶
The model's input columns, split by how they are preprocessed.
infer_feature_types ¶
infer_feature_types(frame: DataFrame, *, exclude: Iterable[str] = ('Id', 'SalePrice'), categorical_codes: Iterable[str] = ('MSSubClass', 'MoSold')) -> FeatureTypes
Classify the columns of frame as numeric or categorical features.
Columns with a numeric dtype are numeric features, except the category
codes in categorical_codes. Every other dtype - object, pandas'
str and category - is categorical. Checking "not numeric" rather
than "object" matters: under pandas 3 text columns use the str dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Data whose columns to classify. |
required |
exclude
|
Iterable[str]
|
Columns that are not features (the identifier and target). |
('Id', 'SalePrice')
|
categorical_codes
|
Iterable[str]
|
Numeric columns that encode categories. |
('MSSubClass', 'MoSold')
|
Returns:
| Type | Description |
|---|---|
FeatureTypes
|
The feature columns in their original order, with the category codes |
FeatureTypes
|
placed after the text columns. |
build_preprocessor ¶
build_preprocessor(numeric_cols: Sequence[str], categorical_cols: Sequence[str], scale: bool = True, *, zero_fill_cols: Sequence[str] = (), code_cols: Sequence[str] = (), drop_first: bool = False, dense: bool = False) -> Any
Build the (unfitted) column transformer for the given feature columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
numeric_cols
|
Sequence[str]
|
Numeric features; missing values become the median. |
required |
categorical_cols
|
Sequence[str]
|
Categorical features; one-hot encoded. |
required |
scale
|
bool
|
Standardise numeric features. Needed by the regularised and logistic models; unnecessary for trees and plain least squares. |
True
|
zero_fill_cols
|
Sequence[str]
|
Members of |
()
|
code_cols
|
Sequence[str]
|
Members of |
()
|
drop_first
|
bool
|
Drop each column's first category after encoding. Unknown categories at prediction time are then encoded like that first category; scikit-learn reports them with a warning. |
False
|
dense
|
bool
|
Always return a dense matrix. Required by the gradient-boosting models. Otherwise scikit-learn's default applies: the output is sparse when fewer than 30% of its entries are non-zero, which is the case for the Ames columns. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
An unfitted |
Raises:
| Type | Description |
|---|---|
ValueError
|
No columns were given, or a |
normalise_missing ¶
Return values as an object array with every missing marker as NaN.
SimpleImputer only recognises NaN. In an object column - what pandas 2
builds from Python objects - None and pd.NA would otherwise survive
imputation and become a category of their own.
amesml.models ¶
Training, saving, loading and prediction.
A trained model is an ordinary scikit-learn Pipeline with a few extra
fitted attributes that make it self-describing:
task_
"regression" or "classification".
input_features_
The raw columns the pipeline expects, in order.
input_kinds_
"number" or "text" for each input column, used to coerce inputs.
feature_defaults_
The most common training value of each input (the median for numeric
measurements), used for any column an input leaves out.
threshold_
Classification only: the price separating the two classes.
training_data_sha256_
Fingerprint of the rows the pipeline was fitted on.
amesml_config_
The :class:~amesml.config.TrainConfig used, as a dictionary.
On disk a model is a directory holding model.joblib and metadata.json
(and metrics.json when it came from :func:train).
FeaturePlan
dataclass
¶
Which columns a pipeline consumes and how each is preprocessed.
Attributes:
| Name | Type | Description |
|---|---|---|
input_columns |
tuple[str, ...]
|
Raw columns the pipeline reads, in data order. |
numeric |
tuple[str, ...]
|
Numeric model features, including engineered ones. |
categorical |
tuple[str, ...]
|
Categorical model features. |
codes |
tuple[str, ...]
|
Members of |
zero_fill |
tuple[str, ...]
|
Members of |
TrainResult
dataclass
¶
Outcome of :func:train: the fitted model and its held-out evaluation.
Attributes:
| Name | Type | Description |
|---|---|---|
pipeline |
Pipeline
|
The fitted pipeline. |
config |
TrainConfig
|
Configuration used. |
metrics |
Metrics
|
Scores on the held-out test rows. |
train_rows |
int
|
Number of rows used for fitting. |
test_rows |
int
|
Number of held-out rows scored. |
dataset_sha256 |
str
|
Fingerprint of the full dataset before splitting. |
unseen_categories |
dict[str, list[str]]
|
Test-set categories absent from the training rows. |
save ¶
Write model.joblib, metadata.json and metrics.json.
Returns:
| Type | Description |
|---|---|
Path
|
The model directory. |
Predictions
dataclass
¶
Predictions for a batch of houses.
Attributes:
| Name | Type | Description |
|---|---|---|
task |
str
|
|
values |
NDArray[Any]
|
Predicted prices, or predicted labels (1 = at or above the threshold). |
probabilities |
NDArray[float64] | None
|
Classification only: probability of label 1. |
unseen_categories |
dict[str, list[str]]
|
Column -> category values the model never saw in training. Such values are encoded like the column's reference level. |
to_frame ¶
Return the predictions as a DataFrame with descriptive column names.
make_estimator ¶
make_estimator(task: str, model: str, *, alpha: float | None, random_state: int, max_iter: int) -> Any
Create the unfitted scikit-learn estimator for a task and model family.
For classification, alpha is an inverse regularisation strength:
C = 1 / alpha, matching the regression models where a larger alpha
always means a simpler model.
l1_logistic_regression ¶
L1-penalised logistic regression across scikit-learn versions.
scikit-learn 1.8 deprecated penalty= (removal in 1.10) in favour of
l1_ratio, but before 1.8 l1_ratio was ignored unless
penalty="elasticnet". liblinear supports L1 everywhere and is far
faster than saga on data of this size, with identical results.
plan_features ¶
Work out the feature columns for frame under config.
Raises:
| Type | Description |
|---|---|
AmesSchemaError
|
A configured column is missing or has the wrong type. |
build_pipeline ¶
Assemble the unfitted pipeline for a feature plan.
resolve_threshold ¶
Turn "median" into the median of prices; pass numbers through.
price_labels ¶
Label each price 1 if it is at or above threshold, otherwise 0.
train_regressor ¶
Fit a sale-price regression pipeline on every row of frame.
Use :func:~amesml.data.train_test_split_df first to keep a test set, or
:func:train to split, fit and evaluate in one call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Training rows, including the target column. |
required |
config
|
TrainConfig | None
|
Training options; |
None
|
Returns:
| Type | Description |
|---|---|
Pipeline
|
The fitted pipeline. |
train_classifier ¶
Fit an above/below-threshold price classifier on every row of frame.
The threshold is resolved from frame itself (its median sale price by
default) and stored on the pipeline as threshold_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
Training rows, including the target column. |
required |
config
|
TrainConfig | None
|
Training options; |
None
|
Returns:
| Type | Description |
|---|---|
Pipeline
|
The fitted pipeline. |
train ¶
Split, fit and evaluate in one step.
The rows are split with config.test_size and config.random_state;
the model is fitted on the training rows and scored on the rest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
The full dataset, including the target column. |
required |
config
|
TrainConfig | None
|
Training options; defaults reproduce the notebook. |
None
|
Returns:
| Type | Description |
|---|---|
TrainResult
|
The fitted pipeline together with its test-set metrics. |
split_for_training ¶
Recreate the train/test split that :func:train uses for config.
Returns:
| Type | Description |
|---|---|
tuple[DataFrame, DataFrame]
|
|
save_model ¶
save_model(pipeline: Pipeline, path: PathLike, *, metrics: Mapping[str, Any] | None = None, extra: Mapping[str, Any] | None = None) -> Path
Save a trained pipeline with a metadata.json sidecar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
Pipeline
|
A pipeline returned by :func: |
required |
path
|
PathLike
|
A directory to create ( |
required |
metrics
|
Mapping[str, Any] | None
|
Evaluation results to record. |
None
|
extra
|
Mapping[str, Any] | None
|
Further top-level metadata entries. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
The path of the written model file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
build_metadata ¶
Describe a trained pipeline as a JSON-serialisable dictionary.
load_model ¶
Load a pipeline saved by :func:save_model.
If metadata.json is present, the model file's SHA-256 is checked
against it first. This catches corrupted or swapped files; it is not a
security boundary, because unpickling runs code. Only load models you trust.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The model directory, or the |
required |
Raises:
| Type | Description |
|---|---|
ModelLoadError
|
The file is missing, fails its checksum, or is not an amesml model. |
load_metadata ¶
Read the metadata.json belonging to a saved model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
PathLike
|
The model directory, or the |
required |
Raises:
| Type | Description |
|---|---|
ModelLoadError
|
There is no metadata next to the model. |
records_to_frame ¶
records_to_frame(pipeline: Pipeline, records: Sequence[Mapping[str, Any]], *, strict: bool = True) -> pd.DataFrame
Turn JSON-style records into a model-ready frame.
A field left out of a record takes the model's training default (see
feature_defaults_); a field sent as None is missing for that house
and handled like a gap in the training data. For example, omit PoolQC
to get the typical house, or send "PoolQC": None to say there is no pool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
Pipeline
|
A trained amesml pipeline. |
required |
records
|
Sequence[Mapping[str, Any]]
|
One mapping of column name to value per house. |
required |
strict
|
bool
|
Reject field names the model does not use, so a typo cannot silently fall back to a default. |
True
|
Raises:
| Type | Description |
|---|---|
AmesSchemaError
|
|
prepare_input ¶
Align and type-check a frame of raw Ames columns for pipeline.
Columns the model does not use are dropped (so a full Kaggle file with
Id and SalePrice works). Columns the model needs but the frame lacks
are filled with training defaults.
Raises:
| Type | Description |
|---|---|
AmesSchemaError
|
A numeric column contains a value that is not a number. |
predict ¶
Predict for every row of frame, which holds raw Ames columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
Pipeline
|
A trained amesml pipeline. |
required |
frame
|
DataFrame
|
Houses to score; see :func: |
required |
Returns:
| Type | Description |
|---|---|
Predictions
|
Prices for a regression model; labels and probabilities for a classifier. |
unseen_categories ¶
Find categorical values in inputs that the model never saw in training.
suppress_unknown_category_warnings ¶
Silence scikit-learn's per-call warning about unknown categories.
With drop_first the encoder warns on every call that meets a category
absent from training, naming columns only by position. amesml reports those
values itself, by column name, through :func:unseen_categories.
amesml.evaluate ¶
Evaluation metrics for the regression and classification tasks.
Both functions take true and predicted values (array-likes or Series) rather than a model, so they work for any predictions - including ones loaded from a file - and are easy to check by hand.
RegressionMetrics
dataclass
¶
Error of predicted sale prices against the true prices.
Attributes:
| Name | Type | Description |
|---|---|---|
mae |
float
|
Mean absolute error, in dollars. |
rmse |
float
|
Root mean squared error, in dollars. Penalises large misses. |
r2 |
float
|
Coefficient of determination; 1.0 is a perfect fit. |
mape |
float
|
Mean absolute percentage error as a fraction (0.12 means 12%). |
n_samples |
int
|
Number of predictions evaluated. |
ClassificationMetrics
dataclass
¶
Quality of above/below-threshold predictions.
Class 1 means "sells at or above the threshold".
Attributes:
| Name | Type | Description |
|---|---|---|
accuracy |
float
|
Fraction of houses classified correctly. |
precision |
float
|
Of houses predicted above the threshold, the fraction that were. |
recall |
float
|
Of houses above the threshold, the fraction predicted so. |
f1 |
float
|
Harmonic mean of precision and recall. |
roc_auc |
float | None
|
Area under the ROC curve, or |
confusion_matrix |
tuple[tuple[int, int], tuple[int, int]]
|
|
n_samples |
int
|
Number of predictions evaluated. |
evaluate_regressor ¶
Compute regression metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ArrayLike
|
Actual sale prices. |
required |
y_pred
|
ArrayLike
|
Predicted sale prices. |
required |
Returns:
| Type | Description |
|---|---|
RegressionMetrics
|
MAE, RMSE, R² and MAPE. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The inputs are empty or of different lengths. |
evaluate_classifier ¶
evaluate_classifier(y_true: ArrayLike, y_pred: ArrayLike, y_score: ArrayLike | None = None) -> ClassificationMetrics
Compute binary classification metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
ArrayLike
|
Actual labels (1 = at or above the threshold, 0 = below). |
required |
y_pred
|
ArrayLike
|
Predicted labels. |
required |
y_score
|
ArrayLike | None
|
Predicted probability of class 1, used for ROC-AUC. |
None
|
Returns:
| Type | Description |
|---|---|
ClassificationMetrics
|
Accuracy, precision, recall, F1, ROC-AUC and the confusion matrix. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The inputs are empty, of different lengths, or contain labels other than 0 and 1. |
amesml.plots ¶
Figures for the README and documentation.
Needs matplotlib: pip install "amesml[plots]". Figures are drawn with
matplotlib's object-oriented API and never touch pyplot, so these functions
keep no global state and work on headless servers without choosing a backend.
Every function writes a PNG and returns its path. :func:generate_all rebuilds
the full set from the raw data, training whatever models the figures need.
plot_target_distribution ¶
Histogram of sale prices with the mean and median marked.
plot_missing_values ¶
Horizontal bar chart of the columns with the most missing values.
plot_residuals ¶
Residuals against predicted price, next to the residual distribution.
plot_confusion_matrix ¶
plot_confusion_matrix(matrix: Sequence[Sequence[int]], path: PathLike, *, labels: tuple[str, str] = ('Below threshold', 'At/above threshold')) -> Path
Annotated 2x2 confusion matrix, laid out as [[TN, FP], [FN, TP]].
plot_feature_importance ¶
plot_feature_importance(pipeline: Pipeline, frame: DataFrame, path: PathLike, *, target: str = 'SalePrice', top_n: int = 15, n_repeats: int = 5, random_state: int = 42) -> Path
Permutation importance of the raw input columns.
Each column of frame is shuffled in turn and the drop in the model's
score (R² for regression) is measured. Importances are reported per raw
Ames column rather than per one-hot level, which keeps them readable, and
the method works for every model family - histogram gradient boosting has
no built-in feature_importances_.
generate_all ¶
generate_all(frame: DataFrame, out_dir: PathLike, *, random_state: int = 42, importance_repeats: int = 5) -> dict[str, Path]
Rebuild every figure from the raw data.
Trains the notebook's linear regression (residuals), its logistic regression (confusion matrix) and a gradient-boosting model (importance) on the standard 80/20 split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
DataFrame
|
The full dataset, including |
required |
out_dir
|
PathLike
|
Directory to write the PNG files into; created if needed. |
required |
random_state
|
int
|
Seed for the split, models and permutations. |
42
|
importance_repeats
|
int
|
Shuffles per column for the importance plot. |
5
|
Returns:
| Type | Description |
|---|---|
dict[str, Path]
|
Figure name -> written file. |
amesml.api ¶
REST inference service.
Install with pip install "amesml[api]" and start it with amesml serve,
or run uvicorn amesml.api:app with AMESML_MODEL_PATH set.
Models are loaded once, when the application starts. AMESML_MODEL_PATH (or
create_app(model_paths=...)) may list one regression and one classification
model, separated by commas, so a single process can serve both endpoints.
Pydantic and FastAPI evaluate annotations at runtime, and Python 3.9 cannot
evaluate X | None; this module therefore spells unions with Optional
and Union and does not use from __future__ import annotations.
PredictRequest ¶
Bases: BaseModel
A batch of houses to score.
Each record maps Ames column names to values. A field you leave out takes
the model's typical training value; a field sent as null means the
feature is absent - "PoolQC": null says the house has no pool.
PricePredictionResponse ¶
Bases: BaseModel
Predicted sale prices, in request order.
ClassPredictionResponse ¶
Bases: BaseModel
Predicted price classes, in request order.
ClassPrediction ¶
Bases: BaseModel
One house's price class.
HealthResponse ¶
Bases: BaseModel
Service status.
ModelSummary ¶
Bases: BaseModel
Which model produced a response.
create_app ¶
Build the FastAPI application.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_paths
|
Optional[Sequence[Union[str, Path]]]
|
Models to serve - at most one per task. When omitted, the
comma-separated paths in |
None
|
Returns:
| Type | Description |
|---|---|
FastAPI
|
The application. Models are loaded when it starts, so a missing or |
FastAPI
|
invalid model stops startup with a clear error instead of failing on the |
FastAPI
|
first request. |
amesml.errors ¶
Exception types raised deliberately by amesml.
Every error derives from :class:AmesMLError, so callers can catch the whole
family in one place. Each also derives from the closest built-in exception, so
code that already handles ValueError or RuntimeError keeps working.
AmesMLError ¶
Bases: Exception
Base class for all errors raised by amesml.
AmesSchemaError ¶
Bases: AmesMLError, ValueError
Data does not match the columns or types the pipeline expects.
ConfigError ¶
Bases: AmesMLError, ValueError
A training configuration is invalid.
DatasetDownloadError ¶
Bases: AmesMLError, RuntimeError
The dataset could not be downloaded, or it failed its integrity check.
ModelLoadError ¶
Bases: AmesMLError, RuntimeError
A saved model is missing, incomplete, or does not match its metadata.