Advanced User Guide¶
The tutorial shows how to build a study. This guide describes
how amos works, every setting, and how to add your own techniques. The
technique catalog lists every technique. Every example on this
page is run by the amos unit tests.
How the pieces fit together¶
settings ──create──▶ Idea ──draft──▶ workflow ──apply──▶ Dataset ──▶ report, export
(file or dict) (chrisjen (graph of workers, (your data and
settings) steps, techniques) all it taught)
amos is built on chrisjen, which
reads settings and builds a workflow from them. Everything that chrisjen
does works in amos, so its advanced
guide applies here too.
amos adds:
| Class | Description |
|---|---|
Project |
A chrisjen.Project that makes your data into a Dataset, applies the workflow to a copy of it, and can export the results. |
Dataset |
The item that flows through the workflow: the data, the label, the split, the model, and everything learned. |
Operation |
Base class for every amos technique (a chrisjen.Technique that works on a Dataset). |
Loader, Parser, Cleaner, Munger, Merger, Shaper, Saver, Describer, Splitter, Transformer, Sampler, Model, Validator, Evaluator, Inferer, Plot |
The genres of techniques. Transformer has the genres Imputer, Scaler, Encoder, Mixer, Selector, and Reducer, Parser has the genre PatternParser, and Inferer has a genre for each package of causal inference (Doubleml, Dowhy, Causalml, and Tigramite). |
Metric |
Base class for metrics, which score a model's predictions. A metric is a chrisjen.Criteria, not a technique, so it is not a step of a workflow: name it as a criterion, or in the metrics of a technique such as scorecard or a validator. GroupMetric is its genre of fairness metrics. |
Chooser |
The genre of the techniques that choose other techniques to suit the data (auto, auto_sampler, auto_model, and auto_plot). See Choosing techniques automatically. |
Experiment |
A design that compares every combination of techniques and keeps a table of how each did. |
Findings |
The default report. |
The library¶
Every technique is a class, stored in the chrisjen library (also available as
amos.library) under its snake case name as soon as it is defined. That is
how names in settings are found. The genres are nested layers of the library:
import dataclasses
import pathlib
from typing import Any, ClassVar
import numpy as np
import pandas as pd
import sklearn.datasets
import amos
print(sorted(amos.library["vertex"]["operation"]))
# ['audit', 'chooser', 'cleaner', 'describer', 'evaluator', 'inferer', 'loader', 'merger', 'model', 'munger', 'parser', 'plot', 'pretest', 'sampler', 'saver', 'shaper', 'splitter', 'transformer', 'validator']
print(amos.library.classify("smote"), amos.library.classify("one_hot"))
# sampler encoder
print(amos.library.all["random_forest"])
# <class 'amos.models.RandomForest'>
Names must be unique across the library, including the names of chrisjen
classes such as "none", "flow", and "summary". The technique
catalog lists every technique by genre.
Settings reference¶
A project's settings are sections of settings. amos reads three special
sections. Every other section is read by chrisjen.
The idea file page shows how to write settings in a file and describes the "general" section in detail.
| Section | Setting | Meaning |
|---|---|---|
general |
label |
The column that models predict. |
task |
"classify" or "regress", if it should not be inferred from the label. | |
seed |
Seed for every random process (passed as random_state). |
|
groups |
Columns that identify groups of rows (see "Groups and fairness" below). | |
use_gpu |
Whether to fit the models that can use a GPU (xgboost, catboost, lightgbm, and tabpfn) on an NVIDIA GPU. Defaults to false (see "Fitting models on a GPU" below). |
|
visualize_explorers |
Whether every explorer (describer) draws a figure of its table. If it is set, it replaces each explorer's visualize parameter; if not (the default), each explorer's own parameter (false unless set) decides (see "Figures of explorers and critics" below). |
|
visualize_critics |
Whether every critic (evaluator or inferer) draws a figure of its table. If it is set, it replaces each critic's visualize parameter; if not (the default), each critic's own parameter (false unless set) decides. |
|
order |
The column that puts the rows in order (such as a date). It is not a feature. audit_independence tests the errors of rows next to each other in this order. |
|
assumption_violations |
What amos does when the data does not meet an assumption of a technique: "warn" (the default), "raise" an error, "ignore" it, or "skip" the branch of an experiment. See Assumptions. | |
conserve_memory |
Whether every experiment keeps only the best combination's whole dataset, rather than every combination's, while it tries them. A worker's own conserve_memory setting wins. Defaults to false (see "Experiments" below). |
|
pipeline |
A named pipeline (such as classification or regression_inference) that fills in the settings of the analyst, critic, and artist. It can also be in the project's section, or in the section of one of those workers for that worker alone. Settings that you write win. See pipeline. |
|
files |
root_folder |
The workspace, which the other folders are in. Defaults to the folder that holds the "code" folder (see "Where data and results are kept" below). |
input_folder |
Folder (in the root folder) where data files named by a relative path are looked for, and where loaders save downloads. Defaults to "data". | |
data_subfolder |
The subfolder of the input folder that holds the project's data (such as "crime/nibrs"), which becomes the input folder. | |
interim_folder |
Folder (in the root folder) for intermediate files. Defaults to the input folder. | |
output_folder |
Folder (in the root folder) in which export makes a folder for each run. Defaults to "studies". |
|
export_results |
Whether to export the results after every run. Defaults to False. |
|
replication_format |
Format of the settings file of the winning paths that export saves: "json", "ini", "toml", "yaml" (or "yml"), or "py". Defaults to "json" (see "Reports and exports" below). |
|
feature_groups |
{group} |
The features (columns) in a group, which is then a technique that keeps only them (see "Selecting features" below). |
The chrisjen settings, in brief:
| Setting | Meaning |
|---|---|
A section named {name}_project |
The project. Its {name}_workers setting lists the workers, in order. |
| A section named for a worker | The worker's settings, below. |
steps or {name}_steps |
The steps of the worker (or of name). |
techniques or {name}_techniques |
The techniques of the worker (or of the step name). In an experiment, the techniques of a step are alternatives. |
design or {name}_design |
How the worker applies its nodes. Defaults to flow. |
criterion or {name}_criterion |
What an experiment or contest compares: a metric (such as roc_auc) or another chrisjen.Criteria. |
A section named {name}_parameters |
Parameters for the technique, step, or worker name. |
A section named {technique}_{step}_parameters |
Parameters for one technique in one step. |
plots, evaluators, inferers in a model's {model}_parameters section |
The techniques that replace the workflow's plots, evaluators, or inferers when that model is the dataset's model (an amos setting; see "Critics and artists for each model" below). |
The designs:
| Design | What it does |
|---|---|
flow |
Applies its nodes one after another. The default. |
experiment |
Tries every combination of one technique from each step, keeps the best, and adds a comparison table. |
contest |
Like experiment, without the table. |
survey |
Tries every combination and averages the results. The results must be numbers, so it is rarely used with a Dataset. |
benchmark |
Repeats its nodes until its criterion is met. |
Where data and results are kept¶
A project's clerk is an amos.Clerk (a nagata.FileManager), which keeps
the data and results outside the project's code, in the "workspace" that
holds the "code" folder:
projects/ (the workspace)
code/
my_study/ (the project's code, where it is run)
data/
crime/nibrs/ (a project's data, in its own subfolder)
studies/
my_study_2026-10-30_09-15-00/ (each run's results)
So data that many projects use is kept once, and neither data nor results
have to be left out of a repository by hand. The workspace is the folder
that holds the nearest folder named "code" at or above the current folder
(or the current folder, if there is none). The environment variable
AMOS_WORKSPACE names another, and so does amos.options._DEFAULT_ROOT
(for a package built on amos). The "files" section of the settings can
name the project's data subfolder and change any folder:
A Clerk can also be made and passed as the clerk of Project.create,
for example amos.Clerk(data_subfolder = "crime/nibrs"). Each folder is
made if it does not exist.
The dataset¶
A Dataset has these attributes:
| Attribute | Meaning |
|---|---|
data |
The data, a pandas.DataFrame. It stays one DataFrame after the data is split. |
label |
The name of the column that models predict. |
task |
"classify" or "regress". |
seed |
Seed for every random process. |
groups |
Columns that identify groups of rows. They stay in the data but are not features. |
use_gpu |
Whether the models that can use a GPU are fitted on one. |
visualize_explorers, visualize_critics |
Whether every explorer (or critic) draws a figure of its table, or None to leave it to each technique's visualize. |
order |
The column that puts the rows in order, or None. Like the groups, it stays in the data but is not a feature. |
assumption_violations |
What amos does when the data does not meet an assumption of a technique: "warn", "raise", "ignore", or "skip". |
train, test |
Index labels of the training and test rows. test is None until the data is split. |
synthetic |
Index labels of the training rows that a sampler made up (synthetic rows and extra copies of a row). |
model |
The fitted model. |
predictions |
Predictions for the test rows (or every row, if the data is not split). |
probabilities |
Predicted probabilities of each class, for the same rows. |
metrics |
Scores, by the name of each metric. |
tables, figures |
Tables and figures, by the name of the technique that made them. |
fitted |
Fitted tools (such as a scaler), by the name of the technique that fitted them. |
history |
A record of each technique applied, with its tool and parameters. |
branches |
A record of every branch of the most recent experiment (for the scorecard). |
kinds |
The kind that set_kinds gave each column (see "Kinds of columns" below). |
A label that is not yet a column is pending until a technique makes it (see "Settings named for columns" below).
Its properties select parts of the data: x and y (the features and the
label), x_train, y_train, x_test, and y_test, and the names of the
features of each kind:
data = pd.DataFrame({
"age": [31, 45, 52, 38],
"clinic": ["north", "south", "north", "north"],
"insured": [True, False, True, False],
"admitted": pd.to_datetime(["2020-01-02", "2021-03-04", "2022-05-06", "2023-07-08"]),
"readmitted": ["yes", "no", "no", "yes"],
})
dataset = amos.Dataset(data, label = "readmitted")
print(dataset.numerics, dataset.categoricals, dataset.booleans, dataset.dates)
# ['age'] ['clinic'] ['insured'] ['admitted']
print(dataset.task, dataset.classes)
# classify ['no', 'yes']
Models cannot use dates or text, so encode them (dates with date_parts, and
text with an encoder such as one_hot or tfidf) or remove them before the
model step.
Dataset.create makes a dataset from a DataFrame, a Polars DataFrame or
LazyFrame, a numpy array, a dict of columns, the path to a data file, or
a scikit-learn dataset loaded with as_frame = True. A Project does this for
you. A data file is read just as load_file reads it (see "Loading data"
below), so it may be in any format that nagata knows. A project reads it
with its clerk, so a relative path is looked for in the current folder and
then in the clerk's input folder.
Loading data¶
A loader makes the dataset from a source named in the settings, so a project
with a loader needs no item. Loaders are usually the first step of the
wrangler. They work through the project's clerk (an amos.Clerk): a
file named by a relative path is looked for in the current folder and then in
the clerk's input folder (the input_folder of the "files" section), and
downloads are saved in the input folder.
| Loader | Source | Other parameters |
|---|---|---|
load_file |
The path of a data file. | |
load_files |
A folder, a pattern of paths (such as "reports/*.txt"), or a list of paths. Files of tables add their rows, and files of text add a row each, with the text in a "text" column. Every row names its file in a "file" column. | pattern (of the names of a folder's files, such as "*.txt"), recursive (whether to look in subfolders), file_column, text_column, limit (most files), and workers (threads that read at once) |
download |
The URL of a file (http or https), or of a web page that links to it (with link), or the name (such as "credit-g") or id (such as 31) of an OpenML dataset. Both are saved in the input folder and only downloaded again if they are missing. An OpenML dataset's default target is the label unless "label" is set. |
For a URL, file_name (what to save it as), refresh (to download it again), timeout (in seconds), link (the words of the link on the page at the URL that leads to the file), required_member (a pattern that a file in a downloaded zip archive must match), resume (to continue a download that stopped), and session (such as a requests.Session). For OpenML, version, target_column, and the other parameters of sklearn.datasets.fetch_openml |
load_chunks |
The path or URL of a CSV file too large to load at once (which may be compressed, such as "opinions.csv.bz2"). A URL's file is downloaded to the input folder first, unless stream is true. |
columns, keep (the values to keep of some columns), where (an expression that rows must match), the dialect of the file (such as delimiter and escape_char), block_size, processes, limit (most rows), and the parameters of download for a URL (see "Reading huge CSV files" below) |
Every loader takes a source, and the label, task, and groups of the
data, which default to those in the "general" section. The dataset's history
records the source. This project loads a file from its input folder:
settings = {
"general": {"label": "canceled", "seed": 43},
"files": {"input_folder": "data"},
"customers_project": {"customers_workers": "wrangler, explorer"},
"wrangler": {
"steps": "load, clean",
"load_techniques": "load_file",
"clean_techniques": "drop_duplicates",
},
"load_file_parameters": {"source": "customers.csv"},
"explorer": {"techniques": "label_balance"},
}
project = amos.Project.create(settings, id = "loaded")
print(project.result)
# Dataset(rows=5, columns=3, label='canceled', task='classify')
print(project.result.history[0])
# {'technique': 'load_file', 'source': 'customers.csv', 'rows': 6, 'columns': 3}
load_file and download load a file in any format that the clerk knows
(such as csv, tsv, Excel, parquet, feather, json, json lines, fixed-width,
HDF, ORC, XML, Stata, SAS, and SPSS), which they find from the file's
extension. A path passed as a project's item, or to Dataset.create, is
read the same way. pandas opens a compressed file (such
as "customers.csv.gz") itself. Set file_format (such as "csv") for a file whose
name does not say what it is, and member to load one file from a zip
archive, which is extracted to a folder named for the archive. Other
parameters, such as sep, go to the pandas reader if it accepts them.
Unlike the clerk's own defaults (which suit quick tests), loaders read every
row and read text as UTF-8, as pandas does.
A file online is named the same way, and is downloaded the first time the project runs:
[wrangler]
steps = load, clean
load_techniques = download
clean_techniques = drop_duplicates
[download_parameters]
source = https://example.com/data/customers.csv.gz
To read another kind of file, add a format to nagata. Every subclass of
nagata.base.FileFormat that is not abstract adds itself to nagata's
formats when it is defined, named for the class in snake case without
"file_format_" (so FileFormatPsv is "psv"). It is then read by load_file,
download, the mergers, and a project's item alike:
import dataclasses
import nagata
@dataclasses.dataclass
class FileFormatPsv(nagata.FileFormatCSV):
"""Pipe-separated values."""
extensions = ("psv",)
def load(self, path, **kwargs):
kwargs.setdefault("sep", "|")
return super().load(path, **kwargs)
pd.DataFrame({"plan": ["basic", "premium"], "calls": [2, 1]}).to_csv(
"calls.psv", sep = "|", index = False)
print(amos.Dataset.create("calls.psv"))
# Dataset(rows=2, columns=2)
To write a loader for another source, see "Writing your own techniques" below.
Reading huge CSV files¶
Some data comes as CSV files far too large to load at once, such as the bulk
files of court records, which reach 55 GB compressed. load_chunks reads such
a file a block at a time with pyarrow, which parses each block on every core,
and keeps only the columns in columns and the rows whose values are in
keep. The rows that are not wanted are dropped before their text becomes
Python objects, so reading the file takes about as long as decompressing it.
A file compressed with bzip2 (".bz2") is decompressed on every core with
indexed_bzip2, and one compressed with gzip, xz, or Zstandard as it is read.
Every value is read as text, so that ids and dates keep their exact form, and
where (an expression for DataFrame.query) then chooses among the rows that
are kept. Each block (block_size bytes, 256 MB by default) must be longer
than the longest row.
id,court,filed,text
1,ca1,2009-05-01,"plain"
2,ca2,2011-02-03,"He said \"no\""
3,ca1,2012-07-08,"Reversed, in part"
4,ca9,2013-01-01,
settings = {
"files": {"input_folder": "data"},
"rulings_project": {"rulings_workers": "wrangler"},
"wrangler": {"techniques": "load_chunks"},
"load_chunks_parameters": {
"source": "rulings.csv",
"columns": ["id", "text"],
"keep": {"court": ["ca1", "ca2"]},
"where": "id != '1'",
# The file escapes quotes with a backslash, as PostgreSQL writes them.
"escape_char": "\\",
"double_quote": False,
},
}
project = amos.Project.create(settings, id = "rulings")
print(project.result.data.to_dict("list"))
# {'id': ['2', '3'], 'text': ['He said "no"', 'Reversed, in part']}
A file online is downloaded to the input folder the first time (and a
download that stops is resumed the next time), unless stream is true, in
which case it is read as it arrives and not saved. limit stops reading once
that many rows are kept, which is quick for trying out a workflow.
Outside of a project, amos.loaders.read_chunks yields the kept rows of each
block as a DataFrame, labeled by their places in the file, so a program can
work through a file of any size with little memory. where can also be a
function of a chunk:
chunks = amos.loaders.read_chunks(
"data/rulings.csv",
keep = {"court": "ca1"},
where = lambda chunk: chunk["filed"] >= "2010-01-01",
escape_char = "\\",
double_quote = False)
for chunk in chunks:
print(chunk[["id", "court"]].to_dict("index"))
# {2: {'id': '3', 'court': 'ca1'}}
Downloading files¶
download and load_chunks download with tools that work outside of a
project too, in amos.loaders. Each takes a session: anything with a get
method like a requests.Session (such as one that a package built on amos
sets up with its own headers, or a fake one in tests). Without one, they use
a requests.Session that names amos to the server.
| Function | Does |
|---|---|
download_file(url, path) |
Downloads a file unless path has it (or refresh is true), a piece at a time, so that a download that stops leaves no file behind (or, with resume, is continued the next time). required_member is a pattern (such as "*caseCentered*") that a file in a downloaded zip archive must match before the archive is saved. |
page_links(url) |
Returns the full address and the words of each link on a web page. |
find_links(url, words) |
Returns the addresses of the links on a page with those words (without regard to case or spacing). |
download_linked_file(url, link, folder) |
Downloads the file that the link with the words link leads to. If several links have those words, each is tried until one leads to an archive that has required_member. |
open_session(session) |
Returns session, or a new requests.Session that names amos. |
Some sites link to the newest release of their data from the same page, with
the same words but a new address each year. download finds such a file
with link:
[download_parameters]
source = https://scdb.la.psu.edu/data/2025-release-01/
link = CSV Organized by Supreme Court Citation
required_member = *caseCentered_Citation*
member = SCDB_2025_01_caseCentered_Citation.csv
Parsing documents¶
Loaders bring documents into a dataset as they are: load_files makes a row
for each file of text, with its path in a "file" column and its text in a
"text" column. Parsers then find information in that text and make columns
of it. Like mungers, they keep the rows and every column, and they come
before the data is split. Each parser searches text for a regular
expression and records what it
finds. A pattern is found anywhere in the text, so "deliver" is found in
"Delivered late", and "deliver|arriv" finds either word. Characters with
special meanings, such as "." and "(", need a backslash to stand for
themselves ("Ph.D."). Missing text matches nothing. Each search covers every
row at once, so hundreds of searches parse thousands of documents in seconds.
Each kind of search is a parser of its own, and the technique catalog lists them:
| Parser | Kind | Makes |
|---|---|---|
parse_flags |
flags |
True if the pattern appears, and otherwise false. |
parse_counts |
counts |
The number of times the pattern appears. |
parse_category |
category |
The value if the pattern appears. The first pattern (or rule) for a column that matches wins, so they can turn text into categories. |
parse_categories |
categories |
The value of every pattern (or rule) for the column that appears, once each. |
parse_match |
match |
The first match, or a column for each named group of the pattern (such as "(?P |
parse_matches |
matches |
Every match, or a column for each named group. |
parse_split |
split |
A column for each name: the text before the first match, between the first and second, and so on, with the rest in the last. |
parse_names |
names |
The names in the text, split wherever the pattern matches (the pattern matches what comes between names). The names are made upper-case without periods or apostrophes. |
parse_fields |
fields |
A column for each label that the pattern matches (such as "AUTHORS:"), with the text after it, up to the next label. The columns are named for the labels in snake case, after the name if there is one. |
parse_replace |
replace |
The text with every match replaced by the value ("\1" is the first group of the match). A blank value removes the matches. |
Every one of them takes the same parameters:
| Parameter | Meaning |
|---|---|
pattern |
The regular expression to search for, or a list of them, which are applied in order and combined (see below). For the parsers that write a value, it can map patterns to their values instead. |
column |
The columns of text to search, separated by commas. Defaults to "text". "*" searches every column of text that is not categorical. |
name |
The column to make. parse_split names two or more, separated by commas. parse_replace without a name changes the text it searches. parse_fields, and parse_match and parse_matches with named groups, need no name, and use one as the start of the names of their columns. |
value |
What parse_category, parse_categories, and parse_replace write, if pattern does not map patterns to values. |
flags |
Any of "ignorecase", "dotall" (so "." also matches line breaks), "multiline" (so "^" and "$" match at each line), and "verbose", separated by commas. |
separator |
What separates several values in one cell (for parse_categories, parse_matches, and parse_names). Defaults to a comma and a space. |
default |
Only for parse_category: the value of text that matches no pattern. |
In a toml settings file, text in single quotes keeps its backslashes as they are:
[shipping_project]
shipping_workers = "wrangler"
[wrangler]
techniques = "parse_split, parse_flags, parse_category, clean_numbers"
[parse_split_parameters]
column = "route"
pattern = '\s+to\s+'
name = "origin, destination"
[parse_flags_parameters]
column = "route"
name = "coastal"
pattern = '\bBoston\b|\bMiami\b'
[parse_category_parameters]
column = "status"
name = "outcome"
default = "other"
flags = "ignorecase"
[parse_category_parameters.pattern]
'deliver|arriv' = "delivered"
'return|refus' = "returned"
[clean_numbers_parameters]
columns = "cost"
orders = pd.DataFrame({
"route": ["Boston to Denver", "Austin to Reno", "Tulsa to Boise"],
"status": ["DELIVERED late", "Returned.", "Arrived."],
"cost": ["$1,200", "n/a", "$350.50"],
})
shipping = amos.Project.create("shipping.toml", item = orders)
shipped = shipping.result.data
print(shipped["origin"].tolist(), shipped["destination"].tolist())
# ['Boston', 'Austin', 'Tulsa'] ['Denver', 'Reno', 'Boise']
print(shipped["coastal"].tolist(), shipped["outcome"].tolist())
# [True, False, False] ['delivered', 'returned', 'delivered']
print(shipped["cost"].tolist())
# [1200.0, nan, 350.5]
print(shipping.result.history[0])
# {'technique': 'parse_split', 'changed': [], 'created': ['origin', 'destination']}
Like any technique, a parser can also be applied by hand. A pattern with named groups makes a column of each group:
sizes = amos.Dataset(
pd.DataFrame({"size": ["12 x 30 cm", "8 x 10 in", "unknown"]}))
amos.parsers.ParseMatch().apply(
sizes, column = "size", pattern = r"(?P<width>\d+) x (?P<height>\d+)")
amos.cleaners.CleanNumbers().apply(sizes, columns = ["width", "height"])
print(sizes.data["width"].tolist(), sizes.data["height"].tolist())
# [12.0, 8.0, nan] [30.0, 10.0, nan]
Rulebooks¶
The parse_all parser applies a rulebook: an ordered list of rules, each
of which is one of the searches above, named by its kind. Rules are usually
rows of CSV files, so they can be written and checked in a spreadsheet:
column,name,kind,pattern,value,flags,note
,title,match,^.*,,,The first line
title,"topic, subtitle",split,:\s,,,The title on either side of the colon
,,fields,^[A-Z]+:,,multiline,Sections such as AUTHORS: and ABSTRACT:
authors,team,names,"\bBY\b|\bAND\b|,",,,
abstract,finding,category,no effect|no difference,null,ignorecase,The first that matches wins
abstract,finding,category,increase|reduce,effect,ignorecase,
abstract,dois,matches,10\.\d{4}/\w+,,,
Sleep and Memory: A Field Study
AUTHORS: By LYNCH, O'BRIEN, and BARRON.
ABSTRACT: Sleep loss REDUCES recall. See 10.1037/abc123 and 10.1016/xyz9.
Tutoring at Scale: Evidence from Ohio
AUTHORS: By BOUDIN.
ABSTRACT: We find no effect. See 10.1080/q2.
settings = {
"general": {"seed": 43},
"papers_project": {"papers_workers": "wrangler"},
"wrangler": {
"steps": "load, parse",
"load_techniques": "load_files",
"parse_techniques": "parse_all",
},
"load_files_parameters": {"source": "papers", "pattern": "*.txt"},
"parse_all_parameters": {"rules": "rules/papers.csv"},
}
project = amos.Project.create(settings, id = "papers")
parsed = project.result.data
print(parsed[["file", "topic", "team", "finding"]].to_string(index = False))
# file topic team finding
# jones.txt Tutoring at Scale BOUDIN null
# smith.txt Sleep and Memory LYNCH, OBRIEN, BARRON effect
print(parsed["dois"].tolist())
# ['10.1080/q2', '10.1037/abc123, 10.1016/xyz9']
print(project.result.history[-1]["created"])
# ['title', 'topic', 'subtitle', 'authors', 'abstract', 'team', 'finding', 'dois']
The columns of a file of rules are:
| Column | Meaning |
|---|---|
column |
The columns of text to search, separated by commas. If it is blank, the rule searches the parser's column ("text" unless it is set). |
name |
The column that the rule makes (or adds to), as the parameter name above. |
kind |
What the rule does: one of the kinds above, or one you register (see below). |
pattern |
The regular expression to search for. |
value |
What a category, categories, or replace rule writes. Blank for the other kinds. |
flags |
Optional: as the parameter flags above. |
separator |
Optional: as the parameter separator above. |
note |
Optional: anything you want to say about the rule. |
Rules are applied from top to bottom, and every column that a rule makes can
be searched by the rules after it, as the rules above search the "authors"
and "abstract" columns that the fields rule made. Rules that make the same
column are combined: flags are true if any rule matches, counts are added,
the first category or match that matches is kept, and the results of
categories, matches, and names rules are joined. A parser given a list
of patterns combines them in the same way. Several values in one cell are
separated by commas; the shaper lists_to_rows can make rows of them.
The "rules" of parse_all can be a CSV file, a folder of them (read in
alphabetical order), a list of rules as dictionaries (with the columns above
as keys), the name of a rulebook, or a list of any of these. CSV files in an
older layout of rules (with "target", "variable", "ignorecase", and "dotall"
columns, and its kinds, such as "section" and "label") are read too.
A package can name its rulebooks by subclassing amos.parsers.ParseAll and
setting its rules, so that its users name them in settings without knowing
where the files are. The subclass is a technique of its own
(parse_surveys, which needs no parameters), and its name without "parse_"
is a rulebook that parse_all and other rulebooks can name (rules =
surveys):
@dataclasses.dataclass
class ParseSurveys(amos.parsers.ParseAll):
rules: ClassVar[Any] = pathlib.Path("rules", "surveys")
Writing your own parsers¶
A parser that does something other than search for a pattern subclasses
amos.Parser and writes parse (see Writing your own
techniques). A parser that searches for a
pattern subclasses amos.PatternParser and writes find, which takes a
Rule (with its pattern, the names of the columns to make, and its
value), the columns of text to search, and the columns made so far (to
add to). The parser takes the parameters above at once, and it is also a
kind of rule that rulebooks can name, after the class without "Parse"
(ParseLast is "last"). Set rule_aliases to give the kind other names:
@dataclasses.dataclass
class ParseLast(amos.PatternParser):
"""Keeps the last match of a pattern in text."""
def find(self, rule, texts, made, index):
text = next(iter(texts.values()))
found = text.str.findall(rule.pattern.pattern, flags = rule.flags)
made[rule.names[0]] = found.str[-1].astype("str")
paper = amos.Dataset(pd.DataFrame({"text": ["See 10.1037/abc123 and 10.1080/q2."]}))
amos.parsers.ParseAll().apply(paper, rules = [
{"kind": "last", "name": "last_doi", "pattern": r"10\.\d{4}/\w+"}])
print(paper.data["last_doi"].tolist())
# ['10.1080/q2']
Munging data¶
Cleaners remove rows and columns, and turn text into the numbers, dates, and
booleans it stands for (clean_numbers, clean_dates, and
clean_booleans). Mungers change what else is in the columns, or make new
columns from them, without adding or removing rows. Each one changes
a whole column at once with the vectorized methods of pandas, so they are
fast even with a lot of data. None of them learns from the data, so, like
cleaners, they belong in the wrangler, before the data is split. The
technique catalog describes each one:
| Kind | Mungers |
|---|---|
| Text | strip_text, normalize_text, html_to_text |
| Values and types | map_values, convert_types, auto_categorize, set_kinds |
| Combining columns | coalesce, combine_flags, derive_columns |
html_to_text converts web pages and other markup (HTML or XML) to plain
text: each paragraph and other block on a line of its own, with character
references (such as "&") as characters, and without the text of scripts,
styles, and the page numbers that publishers insert. Its skipped_tags,
skipped_classes, and block_tags change which elements are left out and
which start lines, and workers converts in that many processes. The same
conversion is amos.mungers.html_to_text for one piece of text:
print(amos.mungers.html_to_text(
'<p>Smith & Jones<span class="star-pagination">*12</span></p>'
'<p>Affirmed.</p>'))
# Smith & Jones
# Affirmed.
To search text for patterns, use the parsers (see Parsing
documents). Each munger records the columns whose
values or types it changed and the columns it made. Parameters that map
names to values, such as the "values" of map_values, need settings that
have mappings: a toml, json, or yaml file, or a Python dict (an ini file
has none), unless the technique takes settings named for columns (see
below).
Settings named for columns¶
Some cleaners and mungers take settings named for the columns they are about, so an ini file needs no mappings for them:
| Technique | A setting name = value means |
Other settings |
|---|---|---|
rename_columns |
Rename the column name to value. |
names |
filter_rows |
Keep the rows whose name meets the condition value. |
query |
derive_columns |
Make the column name from the expression value. |
expressions |
set_kinds |
Give the columns in value the kind name (see below). |
none |
A condition of filter_rows starts with a comparison ("", "!=", "<", "<=",
">", ">=", "in", or "not in"). "not" and a value (as in "not 1") means "!=", a
list means "in", and a value alone means "". The rows kept meet every
condition (and the query, if there is one). In the conditions and in the
expressions of derive_columns, a word that is not a column is a value, so
text needs no quotes: "offender_race == B" is "offender_race == 'B'". If a
word is both a column and a value of the column it is compared to, it raises
an error; put the value in quotes or the column in backticks.
The label can be a column that the wrangler makes. Until a technique makes it, the label is pending: the dataset keeps its name, and its task is inferred once the column is made.
[general]
label = repaid # made by derive_columns
[wrangle_project]
wrangle_workers = wrangler
[wrangler]
techniques = rename_columns, filter_rows, derive_columns,
set_kinds
[rename_columns_parameters]
loan_type = product
[filter_rows_parameters]
product = not in [payday, pawn]
amount = > 0
[derive_columns_parameters]
repaid = status in [paid, closed]
secured = product == mortgage
[set_kinds_parameters]
dummy = secured
categorical = product
loans = pd.DataFrame({
"loan_type": ["mortgage", "auto", "payday", "mortgage", "auto"],
"amount": [100.0, 2500.0, 40.0, 0.0, 75.5],
"status": ["paid", "late", "paid", "closed", "closed"],
})
wrangled = amos.Project.create("wrangle.ini", item = loans).result
print(wrangled.label, wrangled.task, wrangled.data["repaid"].tolist())
# repaid classify [1, 0, 1]
print(wrangled.data.dtypes.astype(str).to_dict())
# {'product': 'category', 'amount': 'float32', 'status': 'category', 'repaid': 'int8', 'secured': 'int8'}
Since every setting of these techniques other than those in the last column is a column, a parameter set for the whole wrangler (in a "wrangler_parameters" section) would be read as a column. Set their parameters in their own sections.
Kinds of columns¶
set_kinds gives each column a kind, "dummy", "categorical", or
"numerical", and stores it in the smallest type that holds its values
exactly. A dummy is int8 (0 and 1), and raises an error if it has missing
values or any other value. A categorical column is the pandas "category"
type. A numerical column is the smallest integer type if its values are
whole numbers with none missing, and otherwise float32 (or float64, for
numbers that float32 cannot hold to about 7 digits).
Columns that are not listed get the kind of their values: a boolean column
or a column of only 0s and 1s is a dummy, other numbers are numerical, and a
categorical column or text with few values is categorical. Dates, longer
text, and the groups are left as they are. A classified label of booleans (or
0s and 1s) becomes a dummy. The kinds are kept in Dataset.kinds, so a dummy
is one of the dataset's booleans even though it holds numbers, and
frequencies with columns = all counts the dummies with the categorical
columns:
print(wrangled.booleans, wrangled.categoricals, wrangled.numerics)
# ['secured'] ['product', 'status'] ['amount']
Arithmetic on small integer types can overflow (int8 holds only -128 to
127), so make new columns from numbers before setting their kinds.
Maps of values¶
map_values replaces values with others, as its "values" map says. Without
"values", it uses the map (or function) for each column in its
value_maps, which a subclass sets. A package built on amos can give the
meanings of its codes once, and its projects name the subclass as a
technique (map_race_codes), with "columns" to map only some of them:
@dataclasses.dataclass
class MapRaceCodes(amos.mungers.MapValues):
value_maps: ClassVar[dict[str, Any]] = {
"offender_race": {"W": "white", "B": "black"},
"victim_race": {"W": "white", "B": "black"},
}
crimes = amos.Dataset(pd.DataFrame({
"offender_race": ["W", "B", "B"],
"victim_race": ["B", "B", "W"],
"age": [19, 34, 52],
}))
MapRaceCodes().apply(crimes)
print(crimes.data["offender_race"].tolist())
# ['white', 'black', 'black']
A subclass of that subclass can add columns of its own with
value_maps = {**MapRaceCodes.value_maps, "weapon": ...}. The order of the
wrangler's techniques is up to you: a technique after a map sees the new
values, not the codes.
Merging data¶
Research often needs data from sources that are not organized the same way: one table has a row for each project, another has a row for each department, and another has a row for each department that each employee has worked in. A merger matches each row of the data to a row of another table and adds that row's columns. The mergers differ in how they match rows (the technique catalog lists them):
| Merger | A row of the data gets | Its parameters |
|---|---|---|
merge_keys |
The columns of the row with the same keys (such as its department). | on, other_on, ignorecase, and duplicates |
merge_nearest |
The columns of the row with the nearest date or number (such as the last price of its stock before it was traded). | column, other_column, direction, tolerance, and keys, if any |
merge_ranges |
The columns of the row whose range has its date or number in it (such as the president in office in its year). | column, start, end, duplicates, and keys, if any |
merge_summary |
Summaries of every row with the same keys (such as the number of employees in its department and the share of them who are women). | how, count, and the keys |
A merger never adds, removes, or reorders rows. The data keeps the unit that it studies, its label, its groups, and its index, so a merger cannot quietly multiply or lose your observations. A row without a match gets missing values. So start from the table whose rows are what you study (which is the table with the label), and merge the others into it. If the other table describes something else (employees, when the rows of the data are projects), reshape the data first (see reshaping data).
Every merger takes these parameters:
| Parameter | Meaning |
|---|---|
source |
The other table: the path of a data file, which is found and loaded as a loader would (a relative path is looked for in the current folder and then in the clerk's input folder). In Python, it can also be a DataFrame, a Dataset, or anything else that Dataset.create accepts. |
reader |
Parameters for loading the file, such as file_format, member, or sep. |
columns |
The columns of the other table to add. By default, they are every column whose name the data does not already have (other than the keys of the other table, which repeat those of the data). |
prefix |
Text to put before the names of the added columns, such as "store_". |
indicator |
The name of a column to make that says whether each row was matched. |
on names the key columns of the data, and other_on those of the other
table, if they have other names there. A key must be the same kind of data
(numbers, dates, or text) in both tables. Set ignorecase to match text
keys without regard to capital letters or the spaces around them. A missing
key matches nothing. A row can match only one row, so merge_keys and
merge_ranges stop if a row matches several, unless duplicates says to use
the "first" or "last" of them (merge_summary summarizes them instead).
The history records how many rows were matched, which is worth checking (and reporting) every time:
projects = pd.DataFrame({
"project": ["a1", "a2", "a3", "a4"],
"department": ["Research", "marketing", "Research", "Sales"],
"year": [2001, 2015, 2019, 2010],
"on_time": [True, False, True, False],
})
merging = {
"general": {"label": "on_time"},
"files": {"input_folder": "data"},
"projects_project": {"projects_workers": "wrangler"},
"wrangler": {"techniques": "merge_keys"},
"merge_keys_parameters": {
"source": "departments.csv",
"on": "department",
"ignorecase": True,
"indicator": "department_found",
},
}
merged = amos.Project.create(merging, item = projects).result
print(merged.data["floor"].tolist(), merged.data["department_found"].tolist())
# [1.0, 9.0, 1.0, nan] [True, True, True, False]
print(merged.history[0])
# {'technique': 'merge_keys', 'source': 'departments.csv', 'rows': 4, 'matched': 3, 'created': ['floor', 'budget', 'department_found']}
merge_ranges and merge_nearest match rows in time. A range has a start
and an end (both are in the range), and a missing one means that the range
has no limit on that side, as with a term that is still going on.
merge_nearest looks "before" a row's date or number unless direction says
"after" or "nearest", so that nothing is used that was not yet known, and no
farther than tolerance, if it is set:
terms = pd.DataFrame({
"president": ["Clinton", "Bush", "Obama", "Trump"],
"began": [1993, 2001, 2009, 2017],
"ended": [2000, 2008, 2016, 2020],
})
amos.mergers.MergeRanges().apply(
merged, source = terms, column = "year", start = "began", end = "ended",
columns = "president")
print(merged.data["president"].tolist())
# ['Bush', 'Obama', 'Trump', 'Obama']
merge_summary is for a table with several rows for each row of the data. It
summarizes them as group_rows does: by default, with the
mean of each column of numbers and booleans (the mean of a boolean is the
share that are true). count names a column for the number of rows:
name,department,began,ended,level,woman
Lee,Research,1995,,3,True
Silva,Research,1986,2021,2,False
Bose,Research,1992,2021,2,False
Baker,Research,2014,,1,False
Kim,Marketing,1985,2017,3,False
Reyes,Marketing,1980,2018,1,False
amos.mergers.MergeSummary().apply(
merged, source = "data/employees.csv", on = "department",
ignorecase = True, count = "employees", prefix = "staff_")
print(merged.data["staff_employees"].tolist(), merged.data["staff_woman"].tolist())
# [4.0, 2.0, 4.0, nan] [0.25, 0.0, 0.25, nan]
Reshaping data¶
Shapers change what a row is: they rearrange the same data so that each row stands for something else. Each has an opposite (the technique catalog lists them):
| Shaper | What it does | Its parameters |
|---|---|---|
wide_to_long |
Stacks columns into rows: a row for each state, with a column for each year, becomes a row for each state in each year. | columns (with name and value), or stubs (with name and separator) |
long_to_wide |
Spreads the rows of each group into columns, which is the opposite. | names, values or stubs, ids, and separator |
lists_to_rows |
Makes a row for each item of a list: a row for each project becomes a row for each member of its team. | column, separator, name, and position |
group_rows |
Makes one row for each group of rows, with summaries of its columns, which is the opposite. | by, how, and count |
The rows of reshaped data are not the rows that it began with, so:
- The rows get new index labels (0, 1, 2, and so on). When rows are repeated, an index with a name is kept as a column of that name.
- A shaper must come before the data is split, so shapers belong in the wrangler.
- The label and groups must still be columns afterward. If they are not, set the shaper's "label" and "groups" (and "task") parameters to those of the reshaped data, as for a loader.
wide_to_long stacks the columns that it is given into a value column,
with a name column that says which column each value came from. With
stubs, it stacks sets of columns that begin with the same names, as panel
data often has: each stub becomes a column, and name has the rest of each
name. long_to_wide does the opposite, with one column of values (whose
new columns are named for the names alone) or one or more stubs:
states = pd.DataFrame({
"state": ["Kansas", "Missouri"],
"income_2019": [51, 48],
"income_2020": [52, 49],
"tax_2019": [0.05, 0.04],
"tax_2020": [0.05, 0.05],
})
long = amos.shapers.WideToLong().apply(
states, stubs = ["income", "tax"], name = "year")
print(long.data.to_dict("list"))
# {'state': ['Kansas', 'Kansas', 'Missouri', 'Missouri'], 'year': [2019, 2020, 2019, 2020], 'income': [51, 52, 48, 49], 'tax': [0.05, 0.05, 0.04, 0.05]}
amos.shapers.LongToWide().apply(long, names = "year", stubs = ["income", "tax"])
print(list(long.data.columns))
# ['state', 'income_2019', 'income_2020', 'tax_2019', 'tax_2020']
group_rows summarizes the columns of each group with the summaries in its
"how": "mean", "median", "sum", "min", "max", "std", "count", "nunique",
"first", "last", "any", "all", or "list". Without one, a column that is the
same throughout each group keeps its value (so a project's year stays its year),
the mean is taken of other numbers and booleans, and the first value is
taken of anything else. A dict gives columns their own summaries.
Together, shapers and mergers join tables whose rows are different things. Each project lists the members of its team in one cell, and the table of employees above has a row for each department that each employee has worked in. To study the teams, this project makes a row for each member of each team, adds what is known about the employee of that name who was working in the department that year, and groups the rows into projects again:
[general]
label = "on_time"
[files]
input_folder = "data"
[teams_project]
teams_workers = "wrangler"
[wrangler]
techniques = "lists_to_rows, merge_ranges, group_rows"
[lists_to_rows_parameters]
column = "team"
separator = ";"
name = "member"
[merge_ranges_parameters]
source = "employees.csv"
column = "year"
start = "began"
end = "ended"
on = ["member", "department"]
other_on = ["name", "department"]
ignorecase = true
columns = ["level", "woman"]
prefix = "team_"
indicator = "found"
[group_rows_parameters]
by = "project"
count = "members"
[group_rows_parameters.how]
member = "list"
found = "sum"
staffed = pd.DataFrame({
"project": ["a1", "a2", "a3"],
"department": ["Research", "Marketing", "Research"],
"year": [2001, 2015, 2019],
"team": ["LEE; SILVA; BOSE", "KIM; REYES", "LEE; BAKER; STONE"],
"on_time": [True, False, True],
})
teams = amos.Project.create("teams.toml", item = staffed).result
print(teams.data["members"].tolist(), teams.data["found"].tolist())
# [3, 2, 3] [3, 2, 2]
print(teams.data["team_level"].round(2).tolist(), teams.data["team_woman"].tolist())
# [2.33, 2.0, 2.0] [0.3333333333333333, 0.0, 0.5]
print(teams.data["on_time"].tolist(), teams.label, teams.task)
# [True, False, True] on_time classify
print(teams.history[1])
# {'technique': 'merge_ranges', 'source': 'employees.csv', 'rows': 8, 'matched': 7, 'created': ['team_level', 'team_woman', 'found']}
Stone was a contractor from another company, so no row of the table of
employees matches Stone, and the means of the third team leave Stone out.
The "found" column says so, which is why an indicator is worth keeping.
Saving and going on later¶
A workflow whose first steps are slow (such as loading and parsing huge
files) can save its dataset once they are done, so that a later run can go
on from there rather than start again. Savers save the dataset at their
point in the workflow and pass it on unchanged. save_data saves the whole
Dataset (its data, label, task, seed, groups, split, fitted tools, model,
metrics, tables, figures, and history) in a joblib file, and its data as a
table that other tools can read. Savers are a step of the wrangler, but
they can come anywhere in a workflow, such as after a model is fitted.
| Parameter | What it does | Default |
|---|---|---|
folder |
The folder of the files: one of the clerk's folders ("input", "interim", or "output"), a folder in the workspace, or an absolute path. | The clerk's interim folder (the data folder, unless the "files" section names another). |
file_name |
The name of the files, without an extension. | The names of the project and the saver, such as "cancer_save_data". |
table_format |
The format of the table of the data: any format that the clerk knows, such as "parquet", "csv", or "excel". Set it to false to save only the dataset. | "parquet" |
compress |
How much joblib compresses the dataset, from 0 (fastest) to 9. | 0 |
Each run saves over the files of the one before. This project saves its dataset after the wrangler:
[general]
label = target
seed = 43
[cancer_project]
cancer_workers = wrangler, analyst
[wrangler]
techniques = drop_duplicates, save_data
[analyst]
steps = split, scale, model
split_techniques = stratified
scale_techniques = standard
model_techniques = logit
cancer = sklearn.datasets.load_breast_cancer(as_frame = True).frame
project = amos.Project.create("checkpoint.ini", item = cancer)
saved = project.result.history[1]
print(saved["file_name"], [pathlib.Path(f).name for f in saved["files"]])
# cancer_save_data ['cancer_save_data.joblib', 'cancer_save_data.parquet']
To go on from it, pass the saved file as the item of a project whose
workflow starts after that point. A relative path is looked for in the
current folder and then in the clerk's input folder, as a data file is. The
dataset is what it was when it was saved: it keeps its label, seed, and
everything else, and the settings of the "general" section fill in only
what it lacks. Its history goes on from where it stopped, so the history of
the later run (and its export) lists every technique from the start:
[cancer_project]
cancer_workers = analyst
[analyst]
steps = split, scale, model
split_techniques = stratified
scale_techniques = standard
model_techniques = logit
later = amos.Project.create("resume.ini", item = "cancer_save_data.joblib")
print([entry["technique"] for entry in later.result.history])
# ['drop_duplicates', 'save_data', 'stratified', 'standard', 'logit']
print(later.result.seed, later.result.metrics == project.result.metrics)
# 43 True
A loader (such as load_file, with the file as its "source") and
Dataset.create load a saved dataset the same way. In a branch of an
experiment, which applies the saver once for each combination of
techniques, the label of the branch is added to the file name (such as
"cancer_save_data_stratified_split-standard_scale"), so that every branch
is saved.
Loading a joblib file runs code that it holds, so load only files that you, or someone you trust, saved. A saved dataset is also tied to the versions of the packages that saved it, so go on from it with the same environment.
How techniques work¶
Parameters¶
A technique receives its parameters from the settings and from the workers
that contain it, as in chrisjen: a technique's own parameters are overridden
by those of its step, then by those of its workers, and then by any passed to
Project.apply. A technique that wraps a tool passes the tool only the
parameters it accepts, so a parameter set for a whole worker does not break
the techniques that do not use it.
If the dataset has a seed and a tool accepts a random_state that was not
set, the seed is used. Every random process in a project is reproducible.
Columns¶
Each genre of transformer changes the features of some kinds by default:
imputers change the numeric features with missing values (mode_impute
changes features of every kind), scalers and mixers change the numeric
features, encoders change the categorical and text features, and selectors
and reducers change the numeric and boolean features. Pass columns to
choose others:
cancer = sklearn.datasets.load_breast_cancer(as_frame = True)
dataset = amos.Dataset.create(cancer, seed = 43)
amos.scalers.MinMax().apply(dataset, columns = ["mean radius"])
print(dataset.history[-1]["columns"])
# ['mean radius']
print(dataset.data["mean radius"].max())
# 1.0
The columns that a transformer makes take the place of the columns it
changed, so the order of the other columns does not change. Transformers are
fitted to the training rows (all rows, before the data is split) and then
change every row. The fitted tool is stored in fitted:
Interactions¶
interactions adds the product of each pair of numeric features. Give it
formulas instead, each named for the interaction it makes (as in "race =
offender_race * victim_race" in its settings), and it adds only those, and
keeps the columns they are made from. Categorical columns make one
categorical column of their combinations, each value followed by the part of
its column's name that differs from the others', which an encoder can then
encode. Numbers make their product, and numbers with categorical columns make
the product for each combination, as a column of its own. It learns nothing
from the data, so it can come before the split:
amos.mixers.Interactions().apply(
crimes, race = "offender_race * victim_race", age_by_race = "age * victim_race")
print(crimes.data["race"].tolist())
# ['white_offender_black_victim', 'black_offender_black_victim', 'black_offender_white_victim']
print(list(crimes.data.columns))
# ['offender_race', 'victim_race', 'age', 'race', 'age_by_race_black_victim_race', 'age_by_race_white_victim_race']
Labels and the positive class¶
Metrics, encoders, and models handle labels of any type. For a binary label,
the positive class is the last of Dataset.classes (such as 1, True, or
"yes"), and metrics such as precision and roc_auc are about that class.
For more than two classes, precision, recall, and f1 are averaged over
the classes ("macro") and roc_auc compares each class with the rest. Pass
average, pos_label, or the other parameters of the scikit-learn metric to
change this. Encoders that learn from the label (such as target) are given
the position of each class when the classes are text.
Hyperparameter search¶
Every model accepts these parameters:
| Parameter | Meaning |
|---|---|
search |
"grid", "random", or "optuna". Without it, lists are passed to the model as they are. |
cv |
Number of cross-validation folds. Defaults to 5. If the dataset has groups, each fold keeps the rows of every group of its first group column together. |
n_iter |
Number of combinations to try in a random or Optuna search. Defaults to 10. |
scoring |
The scikit-learn scorer to compare with, such as "roc_auc". Defaults to "matthews_corrcoef" (the Matthews correlation coefficient) for a classifier and "r2" for a regression. |
With a search, every parameter given as a list is searched. In a random or
Optuna search, a list of two numbers is a range (whole numbers are drawn from
it, inclusive; other numbers are drawn from between them). An Optuna search
chooses each combination to try from the results of the ones before, so it
usually finds good values in fewer tries, and it searches a range that spans
two or more orders of magnitude (such as a learning rate from 0.001 to 0.1) on
a log scale. The search uses the training rows only, and the results of every
combination are stored in tables as "{name}_search".
Why classifiers are compared by the Matthews correlation coefficient¶
Wherever amos compares classifiers without being told how, it uses the
Matthews correlation coefficient (MCC): the scorer of a model's search, the
pipelines' searches and the classification pipeline's criterion,
auto_model's cross-validation, the model-based selectors, permutation
importance, and the learning and validation curves. Name another scorer
("scoring") or criterion ("criterion", or "metric" for auto_model) to
change it.
The MCC is the correlation between the predicted and the true classes, from
-1 (always wrong) through 0 (no better than chance) to 1 (always right). As
Chicco and Jurman (2023) show,
a high MCC means that all four of the basic rates of a confusion matrix
(sensitivity, specificity, precision, and negative predictive value) are high.
A high balanced accuracy guarantees three of them, a high accuracy or F1
score two, and a high area under the ROC curve only one, so a model can score
well on those while doing poorly on one class, which is common when the
classes are imbalanced. Their argument is for two classes; for more,
scikit-learn's MCC is Gorodkin's generalization of it, which keeps its scale.
matthews is also the metric of that name, for a scorecard or an
experiment's criterion.
Chicco, D., & Jurman, G. (2023). The Matthews correlation coefficient (MCC) should replace the ROC AUC as the standard metric for assessing binary classification. BioData Mining, 16, 4. https://doi.org/10.1186/s13040-023-00322-4
When rows are not independent, such as the ratings of one product by several reviewers,
give the dataset groups. A search then folds whole groups (with
StratifiedGroupKFold for a classifier and GroupKFold for a regression),
just as the group validators do, so that no group has rows on both sides of
a fold and the search never scores a model on rows that are nearly copies of
ones it learned from.
amos.splitters.Stratified().apply(dataset)
amos.models.RandomForest().apply(
dataset, search = "random", n_estimators = [20, 60], max_depth = [2, 8],
n_iter = 3, cv = 3)
search = dataset.tables["random_forest_search"]
print(len(search), search["param_n_estimators"].between(20, 60).all())
# 3 True
amos.models.RandomForest().apply(
dataset, search = "optuna", n_estimators = [20, 60], max_depth = [2, 8],
n_iter = 3, cv = 3)
print(list(dataset.tables["random_forest_search"].columns[:2]))
# ['param_max_depth', 'param_n_estimators']
Selecting features¶
Selectors keep some of the features and remove the rest. They are usually
the techniques of a step of their own (such as "select"), so an experiment
can compare them. Most wrap scikit-learn's feature_selection module and,
like other transformers, learn which features to keep from the training rows
only:
| Selector | Keeps |
|---|---|
variance_threshold |
The features whose variance is above a threshold (0). |
k_best, select_percentile |
The k features (or the percentile of them) most related to the label, by an F test or another "score_func". |
select_fpr, select_fdr, select_fwe |
The features whose p-values pass a test at "alpha" (0.05), controlling the false positive rate, the false discovery rate, or the family-wise error rate. |
generic_univariate |
The features most related to the label, by a "mode" (one of the above) and its "param". |
select_from_model |
The features that a model finds most important. |
recursive_elimination |
The features left after removing a model's least important feature again and again. |
recursive_elimination_cv |
The number of features left by recursive_elimination that scores best in cross-validation. |
sequential_selection_sk |
The features chosen by adding (or removing) one at a time, in cross-validation. |
sequential_selection, exhaustive_selection |
The set of features that scores best in mlxtend's sequential or exhaustive search. |
feature_group |
The features that the settings list. |
A selector that would keep none of the features (such as select_fwe with
a small "alpha") raises an error instead.
Searching with a model¶
The selectors that fit a model take:
| Parameter | Meaning |
|---|---|
estimator |
The model: the name of a model in the library (such as random_forest), which is built for the task, or an estimator, its class, or its import path. Defaults to a logistic regression (to classify) or a linear regression. select_from_model and the recursive selectors need a model that reports the importance of each feature (as coef_ or feature_importances_). |
scoring |
For the selectors that cross-validate: the scikit-learn scorer to compare with. Defaults to accuracy or R². |
cv |
For the selectors that cross-validate: the number of folds. Defaults to 5. As in a hyperparameter search, a fold keeps the rows of every group of the first group column together. |
sequential_selection adds the feature that most improves the score, one at
a time (or, with forward = false, removes them), and keeps k_features
features, or by default the number of features that scored best.
exhaustive_selection tries every set of min_features to max_features
features (1 to 3 by default), which is slow when there are many. Both need
mlxtend. They, and recursive_elimination_cv, store the score of every set
(or number of features) that they tried in tables as "{name}_search",
best first.
features = amos.Dataset.create(cancer, seed = 43)
amos.splitters.Stratified().apply(features)
amos.selectors.SequentialSelection().apply(
features, k_features = 3, cv = 3,
estimator = "sklearn.tree.DecisionTreeClassifier")
print(len(features.features))
# 3
print(sorted(features.tables["sequential_selection_search"]["size"]))
# [1, 2, 3]
ranked = amos.Dataset.create(cancer, seed = 43)
amos.splitters.Stratified().apply(ranked)
amos.selectors.RecursiveElimination().apply(
ranked, estimator = "random_forest", n_features_to_select = 4)
print(len(ranked.features))
# 4
Groups of features¶
To compare groups of features that you choose, name each group in a "feature_groups" section of the settings, and then name the groups as techniques. Each group keeps only the features listed for it (the label and groups are always kept), so an experiment compares them like any other techniques:
[general]
label = target
seed = 43
[cancer_project]
design = experiment
criterion = roc_auc
steps = split, scale, select, model
split_techniques = stratified
scale_techniques = standard
select_techniques = size, texture, k_best
model_techniques = logit
[feature_groups]
size = mean radius, mean perimeter, mean area
texture = mean texture, worst texture
[k_best_parameters]
k = 3
data = cancer.frame
project = amos.Project.create("groups.ini", item = data)
print(sorted(b.steps["select"] for b in project.result.branches))
# ['k_best', 'size', 'texture']
print(project.result.features)
# ['worst radius', 'worst perimeter', 'worst concave points']
A listed name that is not a feature keeps the features made from it, whose
names start with it and an underscore, so a group can name a column before
it is encoded ("region" keeps "region_north" and "region_south" after
one_hot). A group's name must not be the name of another technique.
To keep some features in every group, list them as always_use in the
section. always_use is not a group of its own (it cannot be named as a
technique): each group, including a numbered feature_group, keeps its own
features and those. Other selectors, such as k_best, are not affected.
[feature_groups]
always_use = mean radius
size = mean perimeter, mean area
texture = mean texture, worst texture
To
use a group without the section, pass its features as columns to
feature_group (or to a numbered copy, such as feature_group2, with its
own parameters section).
The groups can also be the parameters of feature_group. Then a step that
names feature_group names each of its groups in its place, so an experiment
compares them as branches, and always_use in those parameters is kept by
each of them:
[analyst]
select_techniques = feature_group
[feature_group_parameters]
always_use = mean radius
size = mean perimeter, mean area
texture = mean texture, worst texture
Fitting models on a GPU¶
Four models can be fitted on an NVIDIA GPU, which can be much faster for
large data. To use one, set use_gpu in the "general" section of the
settings:
use_gpu is false unless the settings set it to true, so a project is
fitted on the CPU unless it asks for a GPU. (Without settings, pass
use_gpu = True to Dataset or Dataset.create.) With it:
| Model | On the GPU | Notes |
|---|---|---|
xgboost |
device = "cuda" |
xgboost's packages for Linux and Windows include GPU support. |
catboost |
task_type = "GPU" |
catboost's packages for Linux and Windows include GPU support. Its results on a GPU can vary slightly from one run to the next. |
lightgbm |
device_type = "gpu" |
lightgbm uses OpenCL, which its packages for Linux include (NVIDIA's driver provides the OpenCL runtime). Its packages for Windows and macOS do not, so it is fitted on the CPU there. |
tabpfn |
device = "cuda" |
Needs a build of PyTorch for your GPU (see below). TabPFN is only practical on a CPU for about 1,000 rows or fewer. |
The same goes for the models that DoubleML's and causalml's inferers fit
(named by outcome_model and treatment_model, see "Causal inference"
below). Every other model (and every other technique) runs on the CPU, as it
does without use_gpu. When use_gpu is true:
amosasks NVIDIA's driver which GPUs there are, so no other package is needed. If there is none, it warns and fits every model on the CPU, so the same settings work on a computer without a GPU.- A model is fitted on the first GPU. To use another, set the
CUDA_VISIBLE_DEVICESenvironment variable (such asCUDA_VISIBLE_DEVICES=1) before starting Python. - If a model cannot be fitted on the GPU (because its package was built without GPU support, the GPU is too old for it, or the GPU runs out of memory, for example), it warns and is fitted on the CPU instead.
- An inferer's models are fitted by DoubleML or causalml, which cannot
switch to the CPU partway through. So before the inferer starts, each one
that can use the GPU is fitted to a few made-up rows on it, and if that
fails, it warns and the inferer fits that model on the CPU. This catches a
package without GPU support or a GPU too old for it, but not a GPU that
runs out of memory on the full data, which raises an error (set
use_gputo false to fit them on the CPU). - A model's own parameters take precedence. To keep one model on the CPU,
set its device in its section, such as
device = cpuin[xgboost_parameters]. (An inferer builds its models with their default parameters, so to keep them on the CPU, name a model that does not use a GPU or setuse_gputo false.) - The history records the device of each model with its parameters (but
not of an inferer's models, which warn if they are fitted on the CPU
instead), and
exportrecords the GPUs (their names, compute capabilities, memory, and CUDA version) in "environment.json".
A model fitted on a GPU can give slightly different results from the same model fitted on a CPU, because the GPU adds numbers in a different order. A result is reproducible on the same kind of device, which is why the device and the GPU are recorded.
Older GPUs need care. CUDA 13 does not support GPUs older than NVIDIA's
Turing generation (compute capability 7.5), such as the GeForce 10 series
and the TITAN Xp (compute capability 6.1). For those, use the regular
xgboost package (not xgboost-cu13), which supports compute capability
5.0 and later, and, for TabPFN, a build of PyTorch for CUDA 12.6: PyTorch's
builds for CUDA 12.8 and later leave out these GPUs (and PyTorch plans to
stop making builds for CUDA 12.6 after version 2.14).
Statistical inference¶
Machine learning models predict. Research usually also needs inference: which
features matter, by how much, and how surely. ols and glm wrap statsmodels
and store a table of coefficients with their standard errors, test
statistics, p-values, and 95% confidence intervals:
diabetes = sklearn.datasets.load_diabetes(as_frame = True)
dataset = amos.Dataset.create(diabetes, seed = 43)
amos.models.OLS().apply(dataset)
table = dataset.tables["ols_coefficients"]
print(list(table.columns))
# ['coefficient', 'standard_error', 'statistic', 'p_value', 'ci_lower', 'ci_upper']
print(table.loc["bmi", "p_value"] < 0.001)
# True
glm is a logistic regression (without a penalty) for classification and a
linear regression for regression. Set its "family" parameter for other
generalized linear models, such as "poisson" for counts. Every model that wraps
statsmodels stores the same table:
| Model | statsmodels | Use it for |
|---|---|---|
ols |
OLS |
Least squares regression. |
wls |
WLS |
Least squares with a weight for each row (the "weights" column). |
glm |
GLM |
Generalized linear models of any "family". |
quantile_regression |
QuantReg |
A "quantile" of the label (the median by default), which outliers sway less. |
robust_regression |
RLM |
Regression that gives outliers less weight, by "norm" (Huber's by default). |
mixedlm |
MixedLM |
Regression with a random intercept for each of "groups" (such as each hospital). |
gee |
GEE |
A glm for rows correlated within "groups", with "covariance" "independence" or "exchangeable". |
poisson, negative_binomial, generalized_poisson, zero_inflated_poisson |
Poisson, NegativeBinomial, GeneralizedPoisson, ZeroInflatedPoisson |
Counts: whole numbers of 0 or more, which may vary more than a Poisson's or have extra zeros. |
logit_sm, probit |
Logit, Probit |
Two classes. Unlike logit (scikit-learn's logistic regression), logit_sm has no penalty. |
binomial_bayes_mixedglm |
BinomialBayesMixedGLM |
Two classes, with a random intercept for each of "groups", fitted by variational Bayes. Its table has the mean and standard deviation of each coefficient's posterior and its 95% credible interval, and no p-values. |
mnlogit |
MNLogit |
Any number of classes. Each class other than the reference class (set by "reference"; the first class, sorted, by default) has its own coefficients, named "{feature} ({class})". |
ordinal_regression |
OrderedModel |
Ordered classes, as an ordered logit (or probit, with "distribution"). Its classes are ordered as the categories of an ordered categorical label, and otherwise sorted. |
mixedlm, gee, and binomial_bayes_mixedglm use the dataset's first group
unless "groups" names a column, and the groups and weights are not features.
mnlogit compares each class with the first class (sorted) unless
"reference" names another, as in
amos.models.Mnlogit().apply(dataset, reference = "granted"). A class
matches if it equals "reference" or has the same text, so "2" in a settings
file matches the class 2.
The predictions of mixedlm and binomial_bayes_mixedglm use the fixed
effects only, so they suit groups that the model has not seen. A feature that is a
combination of others (collinear) has no coefficient of its own. ols, wls,
glm, quantile_regression, and robust_regression share the effect among
such features, and the other models leave them out: the model's dropped_
lists them, and their rows in the table of coefficients are empty. amos classifies whole
numbers with few values, so set "task" to "regress" in the "general" section
for a label of counts. The rest of statsmodels' models either do not predict a
label from features (such as MANOVA; PCA and Factor are below), or
condition the effects of groups away so that they cannot predict new rows
(such as ConditionalLogit; use fixest for fixed effects).
Two of the critic's evaluators describe the features that the model learned
from (the real training rows), rather than the model, with statsmodels'
PCA and Factor. pca reports the eigenvalue of each principal
component and the share of the variance it explains (and stores the loadings
as "pca_loadings"), which shows how many dimensions the features really have.
Unlike the pca_reduce reducer, it does not change the data. factor_analysis reports the loading of each feature on a
few hidden factors (by default, one for each eigenvalue of the correlations
above 1, rotated by varimax), with each feature's communality and
uniqueness:
features = amos.Dataset.create(cancer, seed = 43)
amos.splitters.Stratified().apply(features)
amos.evaluators.PCA().apply(features)
print(round(features.tables["pca"].loc["component_6", "cumulative"], 2))
# 0.89
amos.evaluators.FactorAnalysis().apply(features)
print(list(features.tables["factor_analysis"].columns[-3:]))
# ['factor_6', 'communality', 'uniqueness']
fixest wraps pyfixest for regressions with fixed effects (an intercept for
each level of a column, such as each firm or year) and standard errors
clustered by a column. The columns named by its "fixed_effects" and "cluster"
parameters are usually the dataset's groups, and they are not used as
features. It is a least squares regression, or a logit model for
classification; set "family" to "poisson" for counts or "probit":
clinics = diabetes.frame.copy()
clinics["clinic"] = [f"c{i % 10}" for i in range(len(clinics))]
dataset = amos.Dataset(clinics, label = "target", seed = 43, groups = ["clinic"])
amos.models.Fixest().apply(dataset, fixed_effects = "clinic", cluster = "clinic")
print(list(dataset.tables["fixest_coefficients"].index[:3]))
# ['age', 'sex', 'bmi']
Bayesian models¶
Two models sample a posterior with PyMC (install them with
pip install amos[bayesian], on Python 3.12 or later). Each predicts the
posterior mean, and "draws", "tune", and "chains" set its sampler (1000,
1000, and 2 by default; "cores" samples chains at once, and is 1 by default
so that amos's parallel runs do not start processes of their own).
bambiis a Bayesian regression written by Bambi from a formula, with a random intercept for each of "groups" (the dataset's first group, by default). Set "formula" to write it yourself, with the names of the columns, and "family" for the label ("bernoulli" for two classes and "gaussian" for a number by default). Its table of coefficients has the mean and standard deviation of each coefficient's posterior and its 95% credible interval, and no p-values.pymcis Bayesian additive regression trees (BART, from pymc-bart): a sum of "m" small trees (50 by default) that need no scaling and find curves and interactions themselves. Its importances are the share of its splits on each feature. "likelihood" is "bernoulli" for two classes and "normal" for a number by default (or "poisson" for counts).
# skip
dataset = amos.Dataset(clinics, label = "target", seed = 43, groups = ["clinic"])
amos.splitters.GroupSplit().apply(dataset)
amos.models.Bambi().apply(dataset, formula = "target ~ age + bmi + (1|clinic)")
print(dataset.tables["bambi_coefficients"][["coefficient", "ci_lower", "ci_upper"]])
Choosing techniques automatically¶
Name "auto" in place of a step's techniques, and amos chooses techniques
that suit the data when the workflow reaches that step. "auto" works in a
step that fills missing values, encodes, samples, models, evaluates, or
plots. The kind of step is found from its name ("impute", "encode",
"sample", "model", "evaluate", or "plot", and a few others such as "fill",
"resample", "fit", and "draw") or, for a worker without steps, from the
worker's name (such as "critic" or "artist"). In a step with another name,
name the chooser yourself: auto_imputer, auto_encoder, auto_sampler,
auto_model, auto_evaluator, or auto_plot. The named
pipelines are built on them.
| Chooser | What it chooses |
|---|---|
auto_imputer |
Nothing if no feature has missing values. Otherwise iterative_impute for the numeric features if one misses more than 5% of its values (with at least two numeric features and no more than 10,000 rows), and median_impute if not; and mode_impute for categorical and boolean features. |
auto_encoder |
For each categorical feature: one_hot if it has 15 levels or fewer ("levels"), tfidf if it is free text, target if it has more levels and the label has two classes or is regressed, count if the label has more classes, and one_hot with at most 15 columns if category_encoders is not installed. date_parts for dates. Its parameters (such as "drop") go to the encoders. |
auto_evaluator |
scorecard; classification_report and confusion for classes; regression_table for a model with coefficients and standard errors (not after an experiment); audit_assumptions for a regression whose model makes assumptions that only its errors can test; feature_importance for a model with its own importances; permutation_importance for a scikit-learn model without a regression table; shap_importance for a model of trees; and fairness for two classes with groups. |
auto_sampler |
Nothing for a regressed label or classes that are balanced (the rarest class has at least half the rows of the most common). Otherwise random_under if the rarest class has 10,000 rows or more, smote_tomek if the classes overlap, smote if the features are numeric, and random_over if they are not (or have missing values, are mostly binary, or the rarest class has fewer than 6 rows). |
auto_model |
Rules out the models that cannot do the task or use the features, and those whose assumptions the data does not meet (such as linear when the errors are not normal or the features are collinear, poisson for overdispersed counts, or naive_bayes when the features are not normal), cross-validates the first 4 of the rest ("candidates"), and fits the simplest model whose score is within one standard error of the best. It also knows the needs of ols, logit_sm, probit (two classes), and mnlogit (three or more), which it considers only when they are in "choices". |
auto_plot |
Plots of the data before a model is fitted. After, plots of the model that suit the task and the model, such as a precision-recall curve for imbalanced classes, a Q-Q plot for a model that assumes normal errors, or partial dependence for a model that is not linear. |
Each chooser adds a table to the dataset's tables, named for it, with a row
for each technique it considered: whether it was chosen and why (or why
not). For models, it also has each model's cross-validated score. The
dataset's history records the choice and the profile of the training rows
that it was based on, so a paper can report how each technique was chosen.
tumors = sklearn.datasets.load_breast_cancer(as_frame = True).frame
auto_settings = {
"general": {"label": "target", "seed": 43},
"cancer_project": {"cancer_workers": ["analyst", "artist"]},
"analyst": {
"steps": ["split", "scale", "sample", "model"],
"split_techniques": "stratified",
"scale_techniques": "standard",
"sample_techniques": "auto",
"model_techniques": "auto",
},
"auto_model_parameters": {
"choices": ["naive_bayes", "logit", "random_forest", "gradient_boosting"],
},
"artist": {"techniques": "auto"},
}
auto_project = amos.Project.create(auto_settings, item = tumors)
auto_result = auto_project.result
print(auto_result.tables["auto_sampler"].loc["none", "reason"])
# the classes are balanced: the rarest has 60% of the rows of the most common
model_choices = auto_result.tables["auto_model"]
print(model_choices.loc["naive_bayes", "reason"])
# assumes normal features, but 73% of them are not
print(model_choices["score"].round(3).dropna().to_dict())
# {'logit': 0.941, 'random_forest': 0.915, 'gradient_boosting': 0.935}
print(model_choices.index[model_choices["chosen"]].tolist())
# ['logit']
print(list(auto_result.figures))
# ['confusion_heatmap', 'roc_curve', 'calibration_curve', 'importance_plot']
gradient_boosting scored a little better than logit, but by less than
one standard error, so the simpler logit was chosen. Set "simplest" to
false to choose the best score instead. The "auto_model_parameters" section
holds the parameters of the "model" step's "auto" (as for any technique of a
step). "choices" limits the techniques that a chooser considers (in the
order to prefer them). Its other parameters ("candidates", "folds", and
"metric" for auto_model, "levels" for auto_encoder, and "data" for
auto_plot) are described in the
API reference, and any others are passed to the
techniques it chooses.
The choosers can also be applied directly, and amos.auto.profile returns
what they found about the data. Here, the label is counts that vary more
than a Poisson model assumes:
generator = np.random.default_rng(0)
stores = pd.DataFrame({
"staff": generator.integers(1, 10, 500),
"hours": generator.normal(30, 8, 500),
})
mean = np.exp(0.2 + 0.15 * stores["staff"] + 0.01 * stores["hours"])
stores["complaints"] = generator.negative_binomial(2, 2 / (2 + mean))
complaint_data = amos.Dataset(stores, label = "complaints", task = "regress", seed = 43)
complaint_data = amos.splitters.TrainTest().apply(complaint_data)
amos.auto.AutoModel().apply(
complaint_data, choices = ["poisson", "negative_binomial", "linear", "random_forest"])
model_table = complaint_data.tables["auto_model"]
print(model_table.index[model_table["chosen"]].tolist())
# ['negative_binomial']
print(model_table.loc["poisson", "reason"])
# assumes that the variance of the counts equals their mean, but they are overdispersed (dispersion 3.31)
print(model_table.loc["linear", "reason"])
# assumes normal errors, but they are not (skewness 1.95, excess kurtosis 5.34)
found = amos.auto.profile(complaint_data)
print(found.counts, found.overdispersed, found.normal)
# True True False
Groups and fairness¶
Research about people often needs to know whether a model treats groups
differently. Name the columns that identify groups (such as race, school, or
region) as the dataset's groups, or in the "groups" setting of the "general"
section. Groups stay in the data but are not features, so transformers and
models do not use them. Then:
- The fairness metrics (
demographic_parity,equalized_odds, andequal_opportunity, with a "_ratio" version of each) compare the model's predictions across the dataset's first group, or the column named by their "group" parameter. They wrap fairlearn and need a label with two classes. fairnessmakes a table of the count, selection rate, accuracy, and true and false positive rates of each group, with the largest difference and smallest ratio between groups.- The
scorecardaddsdemographic_parityandequalized_oddsfor every branch if the first group has at most 20 values (Scorecard.fairness_limit) and fairlearn is installed. A group with more values (such as the person of each row) is not compared unless the fairness metrics are named in the scorecard's "metrics". fixestcan use groups as fixed effects and clusters, andgroup_splitkeeps each row of the dataset's first group in the same set.mixedlm,gee, andbinomial_bayes_mixedglmmodel the correlation of the rows of each group (see above).gpboostdoes the same for gradient boosting: GPBoost fits trees of the features together with a random intercept for each level of "groups" (the dataset's first group by default), and can add a Gaussian process over "coordinates" (such as a latitude and a longitude). Rows of groups that it has not seen are predicted by the trees alone, and the variances of its random effects are stored intablesas "gpboost_random_effects".bambifits a Bayesian regression with Bambi, by default with a random intercept for each level of "groups" (the dataset's first group), or any model that "formula" writes in Bambi's syntax (such as"outcome ~ age + (age|hospital)"). PyMC samples its posterior ("draws", "tune", and "chains" set the sampler). The posterior mean, standard deviation, and 95% credible interval of each coefficient are stored intablesas "bambi_coefficients" (with no p-values), and those of the standard deviation of each group's random effects as "bambi_random_effects". A row of a group that it has not seen is predicted over the random effects that a new group could have.
data = cancer.frame.copy()
data["clinic"] = np.where(np.arange(len(data)) % 3 == 0, "north", "south")
dataset = amos.Dataset(data, label = "target", seed = 43, groups = ["clinic"])
print("clinic" in dataset.features)
# False
amos.splitters.Stratified().apply(dataset)
amos.scalers.Standard().apply(dataset)
amos.models.Logit().apply(dataset)
amos.evaluators.Fairness().apply(dataset)
print(list(dataset.tables["fairness"].index))
# ['north', 'south', 'difference', 'ratio']
print(0 <= amos.metrics.EqualizedOdds().measure(dataset) <= 1)
# True
Rows that a sampler copies keep their groups. Synthetic rows (made by
smote, for example) have no groups.
Uncertainty¶
conformal turns any model's predictions into intervals (for regression) or
sets of classes (for classification) that contain the true value for at least
a chosen share of rows, with MAPIE's cross-conformal methods. The share of
test rows covered and the width of the intervals (or the size of the sets)
are stored in metrics:
dataset = amos.Dataset.create(diabetes, seed = 43)
amos.splitters.TrainTest().apply(dataset)
amos.models.Linear().apply(dataset)
amos.evaluators.Conformal().apply(dataset, confidence = 0.9)
print(list(dataset.tables["conformal"].columns))
# ['actual', 'prediction', 'lower', 'upper', 'covered']
print(dataset.metrics["coverage"] > 0.8)
# True
Causal inference¶
A model predicts the label. An inferer measures how much a treatment (such
as a program or a ruling) changes the label, after accounting for the other
features, or, for a time series, which variables cause which others and when.
The inferers in amos.inferers belong to the critic, since they judge
what the data can say about causes, and they come from four packages. Each
package's inferers are a genre of Inferer:
| Genre | Inferers | Python |
|---|---|---|
doubleml |
partially_linear, partially_linear_iv, partially_logistic, partially_linear_panel, interactive_regression, interactive_iv, potential_outcomes, quantile_effects, difference_in_differences, regression_discontinuity, sample_selection |
every version |
dowhy |
regression_adjustment, glm_adjustment, doubly_robust, propensity_matching, propensity_stratification, propensity_weighting, distance_matching, instrumental_variable |
3.13 and later |
causalml |
s_learner, t_learner, x_learner, dr_learner, tmle |
3.11 and 3.12 |
tigramite |
pcmci, pcmci_plus, lpcmci, time_series_effect |
every version |
causalml has no version for Python 3.13 and later, and on Python 3.11 and
3.12 the versions of DoWhy that work with pandas 3 cannot be installed with
causalml. So the causal extra installs DoubleML (with rdrobust, for
regression_discontinuity) and tigramite everywhere, causalml on Python 3.11
and 3.12, and DoWhy on Python 3.13 and later. (On
Python 3.11 and 3.12, pip install dowhy installs DoWhy if causalml is not
installed.) The technique catalog describes
each one. Which to use depends on the design of the study:
| Design | Inferers |
|---|---|
| A treatment that changes the label by the same amount for every row | partially_linear, regression_adjustment |
| A treatment with two values, whose effect may differ from row to row | interactive_regression, doubly_robust, propensity_matching, propensity_stratification, propensity_weighting, distance_matching, s_learner, t_learner, x_learner, dr_learner, tmle |
| A label with two classes | partially_logistic, glm_adjustment (and the treatments of two values above, whose effects are changes in the chance of the second class) |
| Causes of the treatment that are not among the features, and an "instrument" | partially_linear_iv, interactive_iv, instrumental_variable, quantile_effects (with "local_quantile") |
| A treatment given to the rows at or above a cutoff of a score ("running") | regression_discontinuity |
| A treatment with several levels | potential_outcomes, and causalml's learners (with "control") |
| Effects on the spread of the label, not only its mean | quantile_effects |
| Units (or groups) seen before and after a treatment that some of them got, perhaps in different periods | difference_in_differences |
| Units seen over several periods (a panel) | partially_linear_panel |
| A label seen only for some rows | sample_selection |
| A time series | pcmci, pcmci_plus, lpcmci, time_series_effect |
An inferer uses every row, so it needs no split. It stores a table under
its name with a row for each effect (of each treatment, group, quantile, or
level of the treatment): its estimate ("coefficient"), standard error, test
statistic, p-value, and 95% confidence interval, which coefficient_plot
can draw. The parameters of most inferers are:
| Parameter | Meaning |
|---|---|
treatment |
The column with the treatment. Required, except by pcmci, pcmci_plus, and lpcmci. |
outcome_model, treatment_model |
amos models of the label and of the treatment (and of any instrument), for DoubleML and causalml. By default, random_forest. |
n_folds |
The number of folds for cross-fitting the models (5 by default). |
instrument, time, unit, selected, running |
Columns with other roles in the design, for the inferers that need them. |
simulations, refuters |
DoWhy's bootstrap samples (100 by default) and refuters (placebo_treatment_refuter, random_common_cause, and data_subset_refuter), whose results are stored as "{name}_refutations". |
control |
causalml's value of the treatment that the others are compared to. Each row's effect is stored as "{name}_effects". |
max_lag, alpha, test |
tigramite's longest lag (5 by default), level of significance (0.05 by default), and test of conditional independence ("parcorr", "robust_parcorr", or "cmiknn"). |
rng = np.random.default_rng(1)
age = rng.normal(40, 10, 500)
program = (rng.random(500) < 1 / (1 + np.exp(-(age - 40) / 5))).astype(int)
outcome = 2 * program + 0.1 * age + rng.normal(0, 1, 500)
treated = pd.DataFrame({"age": age, "program": program, "outcome": outcome})
dataset = amos.Dataset(treated, label = "outcome", seed = 43)
amos.inferers.PartiallyLinear().apply(
dataset, treatment = "program", outcome_model = "linear",
treatment_model = "logit")
effect = dataset.tables["partially_linear"].loc["program"]
print(effect["ci_lower"] < 2 < effect["ci_upper"])
# True
amos.inferers.QuantileEffects().apply(
dataset, treatment = "program", outcome_model = "logit",
treatment_model = "logit")
print(list(dataset.tables["quantile_effects"].index))
# [0.25, 0.5, 0.75]
For a time series, the rows must be in order. tigramite's methods find which variables cause which others, and at what lag. Here, ads raise visits to a website a week later, which raise sales two weeks after that:
rng = np.random.default_rng(2)
weeks = np.zeros((300, 3))
for week in range(2, 300):
weeks[week, 0] = 0.7 * weeks[week - 1, 0] + rng.normal()
weeks[week, 1] = (
0.5 * weeks[week - 1, 1] + 0.6 * weeks[week - 1, 0] + rng.normal())
weeks[week, 2] = (
0.4 * weeks[week - 1, 2] + 0.8 * weeks[week - 2, 1] + rng.normal())
traffic = pd.DataFrame(weeks, columns = ["ads", "visits", "sales"])
series = amos.Dataset(traffic, label = "sales", seed = 43)
amos.inferers.PCMCI().apply(series, max_lag = 3, alpha = 0.01)
print(series.tables["pcmci"][["cause", "effect", "lag"]].values.tolist())
# [['ads', 'ads', 1], ['ads', 'visits', 1], ['visits', 'visits', 1], ['visits', 'sales', 2], ['sales', 'sales', 1]]
amos.inferers.TimeSeriesEffect().apply(
series, treatment = "ads", lag = 3, max_lag = 3, alpha = 0.01)
effect = series.tables["time_series_effect"].iloc[0]
print(effect.name, effect["ci_lower"] < 0.6 * 0.8 < effect["ci_upper"])
# ads (lag 3) True
The estimates are causal only if the assumptions of their designs hold: most need every feature that affects both the treatment and the label to be among the features, and an instrument must affect the label only through the treatment. DoWhy's refuters test some of these assumptions.
Survival analysis¶
For the time until an event (such as a patient's relapse or a customer's cancellation), the
label is the time, and a column says whether the event happened (1) or the
row stopped being observed first (0, censored). kaplan_meier and
survival_curves describe and draw the share of rows without the event over
time, overall or by group (with a table of the number of rows at risk, if
"at_risk" is set). cox is a Cox proportional hazards regression,
with hazard ratios in its coefficients table, and concordance scores its
predictions. They wrap statsmodels:
rng = np.random.default_rng(2)
complaints = rng.poisson(2, 400).astype(float)
times = pd.DataFrame({
"complaints": complaints,
"canceled": (rng.random(400) < 0.7).astype(int),
"days": rng.exponential(400 / (1 + complaints)).round() + 1,
})
dataset = amos.Dataset(times, label = "days", seed = 43, groups = ["canceled"])
amos.describers.KaplanMeier().apply(dataset, event = "canceled")
amos.splitters.TrainTest().apply(dataset)
amos.models.Cox().apply(dataset, event = "canceled")
print(dataset.tables["cox_coefficients"].loc["complaints", "hazard_ratio"] > 1)
# True
print(amos.metrics.Concordance().measure(dataset) > 0.5)
# True
Figures¶
The artist's plots draw matplotlib figures, which are stored in the
dataset's figures and saved by Project.export. Every plot takes a "width"
and "height" (in inches), a "title", and the style parameters below. They fall
into a few families:
| Family | Plots |
|---|---|
| The data | histograms, box_plots, count_plots, distribution_plots, frequency_plots, pair_plot, correlation_heatmap, missing_heatmap, missing_bars, label_plot, association_rules_plot, scree_plot, loadings_heatmap |
| Classifiers | roc_curve, precision_recall_curve, det_curve, calibration_curve, confusion_heatmap, classification_report_heatmap |
| Regressions | actual_vs_predicted, residual_plot, qq_plot, influence_plot, coefficient_plot, estimates_plot |
| Models | importance_plot, weights_plot, partial_dependence, decision_regions, learning_curve, validation_curve, search_plot, prediction_intervals, bias_variance_plot, scorecard_plot, shape_functions |
| Trees | tree_plot, tree_leaf_sizes, tree_leaf_distributions, tree_leaf_purity, tree_feature_space, tree_prediction_path |
| SHAP values | shap_bar, shap_beeswarm, shap_violin, shap_heatmap, shap_decision, shap_embedding, shap_waterfall, shap_force, shap_scatter, shap_partial_dependence, shap_group_difference |
| Groups and time | fairness_plot, survival_curves, causal_graph |
Plots of the data are split or colored by the label's classes (or by the
dataset's first group, or by the column "by"). Plots of a table, such as
coefficient_plot (of the coefficients of ols, glm, fixest, or cox,
or of an inferer), search_plot, fairness_plot, and prediction_intervals,
draw the table that another technique made. Most of them make the table if
it is missing (coefficient_plot, search_plot, and causal_graph cannot),
and each takes a "source", the name of the table to draw, for a technique
that was given a name of its own. learning_curve and validation_curve fit
copies of a scikit-learn model again, in cross-validation on the training
rows.
In the workflow of a Project or an Experiment, a plot or evaluator that
does not suit the model (such as a tree_plot of a logit, or a
coefficient_plot of a model without a table of coefficients and no "source")
is skipped rather than ending the run, since one path of an experiment may need
it and another may not. A warning is logged, and the technique's entry in the
dataset's history (and "history.json") has "skipped" and the "reason". An
experiment's own entry also has "skipped_techniques", with what each path
skipped, since the datasets of the other paths may not be kept. A technique of
your own can do the same by raising amos.IncompatibleTechniqueError. Other
errors, such as a wrong parameter or a plot of a model that has not been
applied yet, are still raised, and so is this one if you call apply directly.
The SHAP plots draw the SHAP values that shap_importance found (or find
them) for the class "category", with shap's own plotting functions. shap
draws with matplotlib.pyplot, so amos lends it each figure while it
draws, without opening a window, and seeds the random numbers that shap uses
to jitter dots, so that a figure is the same every time.
dataset = amos.Dataset.create(diabetes, seed = 43)
amos.splitters.TrainTest().apply(dataset)
amos.models.OLS().apply(dataset)
for plot in (amos.plots.CoefficientPlot(), amos.plots.QqPlot()):
plot.apply(dataset)
amos.plots.InfluencePlot().apply(dataset, title = "Influence of each row")
print(sorted(dataset.figures))
# ['coefficient_plot', 'influence_plot', 'qq_plot']
The tree plots draw a decision_tree, or one tree (numbered tree) of a
random_forest, extra_trees, or adaboost model. tree_plot is
scikit-learn's drawing of the splits; the others are dtreeviz's, which also
draw the training rows in each part of the tree: how many are in each leaf
(tree_leaf_sizes), their classes or labels (tree_leaf_distributions), how
mixed each leaf is (tree_leaf_purity), how the splits divide one or two
features (tree_feature_space), and how much each feature decides one row's
path to its leaf (tree_prediction_path). tree_leaf_sizes and
tree_leaf_distributions also draw a tree of an xgboost or lightgbm
model. decision_regions is mlxtend's plot of the class that any classifier
predicts across two features (the two most important, by default), with the
other features held at their medians.
trees = amos.Dataset.create(cancer, seed = 43)
amos.splitters.Stratified().apply(trees)
amos.models.DecisionTree().apply(trees, max_depth = 3)
for plot in (amos.plots.TreeLeafSizes(), amos.plots.DecisionRegions()):
plot.apply(trees)
print(sorted(trees.figures))
# ['decision_regions', 'tree_leaf_sizes']
Figures of explorers and critics¶
The explorers and critics make tables, and each can also draw its table, in
the same style as every plot. Pass visualize = True to apply (or set
visualize = true in the technique's parameters), and the figure is stored
in the dataset's figures under the technique's name, and the technique's
entry in history has "figure". visualize is false unless it is set, so
nothing is drawn by default.
explored = amos.Dataset.create(cancer, seed = 43)
amos.describers.Correlations().apply(explored, visualize = True)
amos.describers.Summarize().apply(explored)
print(sorted(explored.figures), explored.history[0]["figure"])
# ['correlations'] correlations
To draw every figure of a stage, set "visualize_explorers" or
"visualize_critics" in the "general" section of the settings (or pass them
to Dataset or Dataset.create). If either is set, it replaces the
visualize of every technique of its stage: true draws every figure, and
false draws none, even if a technique's parameters ask for it. If it is not
set (the default), each technique's own visualize decides.
explored.visualize_explorers = True
amos.describers.Summarize().apply(explored)
explored.visualize_explorers = False
amos.describers.MissingValues().apply(explored, visualize = True)
print(sorted(explored.figures))
# ['correlations', 'summarize']
Each technique draws its table with the plot that suits it:
| Technique | Figure |
|---|---|
association_rules |
association_rules_plot: each rule's support against its confidence, colored by its lift. |
correlations |
correlation_heatmap of the table. |
describe |
distribution_plots: a histogram of each column of numbers or dates, and bars of the most common values of each other column. |
frequencies |
frequency_plots: the share of the rows with each value, a panel for each column. |
kaplan_meier |
survival_curves, with the same "event" and "group". |
label_balance |
label_plot. |
missing_values |
missing_bars: the share of each column's values that are missing. |
summarize |
box_plots of the numeric columns, not split by class. |
bias_variance |
bias_variance_plot: the expected loss, the bias, and the variance. |
classification_report |
classification_report_heatmap: the precision, recall, and f1 of each class. |
confusion |
confusion_heatmap of the table. |
conformal |
prediction_intervals. |
explain_weights |
weights_plot: the weight of each feature. |
factor_analysis |
loadings_heatmap: the loadings of each feature on each factor. |
fairness |
fairness_plot. |
feature_importance, permutation_importance, shap_importance |
importance_plot of the table. |
pca |
scree_plot: each component's share of the variance, and their cumulative share. |
regression_table |
estimates_plot: every model's estimates with their confidence intervals. |
scorecard |
scorecard_plot: each branch's score on each metric. |
| An inferer that estimates effects | coefficient_plot of the effects. |
pcmci, pcmci_plus, lpcmci |
causal_graph: tigramite's graph of the causal links. |
These plots are ordinary plots too, so the artist can draw them, and each
makes the table it draws if it is missing (except causal_graph, which
needs a table of links). A figure that cannot be drawn (because the plots
extra is not installed, or the plot does not suit the table) does not stop
the technique: a warning is logged, the table is kept, and its entry in
history has the reason as "figure_error". Every plot's make_figure
returns its figure without adding it to the dataset, which is how the
explorers and critics draw theirs.
Axes¶
The axes of a figure start at 0, so that the heights and lengths of what it draws can be compared, unless the axis shows something with no natural zero:
- the values of the features (in
histograms,box_plots,pair_plot,partial_dependence,decision_regions,tree_feature_space,shape_functions,shap_scatter, andshap_partial_dependence); - the model's output in shap's
shap_decision,shap_waterfall,shap_force, andshap_embedding; - the label of a regression, or the model's predictions of it (in
label_plot,actual_vs_predicted,residual_plot,prediction_intervals,partial_dependence,shap_partial_dependence, andtree_leaf_distributions); - the parameters of the model (in
search_plotandvalidation_curve).
An axis of negative numbers ends at 0, and one that already holds 0 is left as it is, as are axes of names, dates, a logarithmic scale, or a heatmap. "start_at_zero" picks the axes: "x", "y", "xy", or "" for neither.
The panels of a plot that measure the same thing share their ranges: the
counts of histograms and count_plots, the scores of search_plot and
fairness_plot, and the contributions of shape_functions. In a
pair_plot, each feature has one range, on the x axes of its column and the
y axes of its row.
amos.plots.LearningCurve().apply(trees, start_at_zero = "x")
axes = trees.figures["learning_curve"].axes[0]
print(axes.get_xlim()[0] == 0, axes.get_ylim()[0] == 0)
# True False
Styles¶
Every figure has the same style, so that a paper's figures match. By default, it is the "science" style of SciencePlots with its "nature" style, which gives figures the size and fonts of a figure in Nature: one column (3.3 inches) wide, with 7-point text. The colors are SciencePlots' "bright" cycle (Paul Tol's), which people with color blindness can tell apart. Each plot takes:
| Parameter | Meaning |
|---|---|
style |
Names of matplotlib or SciencePlots styles (such as "science", "nature", "ieee", "ggplot", or "default"), applied in order, or "xkcd", for figures that look drawn by hand. "none" uses the current settings of matplotlib. |
colors |
A color cycle, such as "bright", "vibrant", "muted", or "high-contrast", applied after the style (so "xkcd" keeps it), or "none" for the colors of the style. |
latex |
Whether to set the text with LaTeX, which must be installed. By default, matplotlib sets the text and math itself, whatever the style says. |
Set them for every plot in the "{worker}_parameters" section of the artist,
or for one plot in its own section. The defaults are options._PLOT_STYLE
and options._PLOT_COLORS:
Unless a plot is given a "width" or "height", its usual size is scaled to the
width of the style, and Project.export saves figures at 300 dots per inch
(options._FIGURE_DPI), so that they are sharp in print. "xkcd" uses the
"xkcd Script", "Comic Neue", or "Comic Sans MS" font if one is installed,
and the usual font if not.
amos.plots.QqPlot().apply(dataset)
print(dataset.figures["qq_plot"].get_size_inches())
# [3.3 2.475]
amos.plots.QqPlot().apply(dataset, style = "xkcd")
print(dataset.figures["qq_plot"].get_size_inches())
# [6.4 4.8]
Plots drawn by other packages follow the style as far as those packages
allow. shap draws with matplotlib, so the SHAP plots take the style's
fonts, lines, and ticks. shap_bar and shap_waterfall also take the first
two colors of the style's cycle (in "bright", blue for features that lower
the prediction and red for those that raise it), but the other SHAP plots
keep shap's own red and blue scale. shap also fixes the sizes of its text,
so the SHAP plots (and statsmodels' influence_plot, which does too) keep
their usual sizes (6.4 by 4.8 inches for most), so that their text fits.
Writing your own techniques¶
Subclass the genre that fits and write the method it requires. The class is in the library under its snake case name as soon as it is defined, so it can be named in settings right away.
| Genre | Write | Returns |
|---|---|---|
Loader |
load(self, source, **kwargs) |
The data: a DataFrame or anything that Dataset.create accepts. self.read(path, **kwargs) loads a file with the clerk. |
Parser |
parse(self, data, **kwargs) |
The DataFrame with the information found in its text in changed or new columns, and the same rows. |
Cleaner |
clean(self, data, **kwargs) |
The cleaned DataFrame. |
Munger |
munge(self, data, **kwargs) |
The DataFrame with changed or new columns, and the same rows. |
Merger |
match(self, data, other, **kwargs) |
For each row of the data, the position of the row of the other table that matches it, or -1 for none. The merger adds the columns of those rows. prepare(self, other, **kwargs) can change the other table first. |
Shaper |
shape(self, data, **kwargs) |
The reshaped DataFrame. |
Saver |
save(self, item, folder, file_name, **kwargs) |
The paths of the files that it saved in folder, named file_name (without an extension). It must not change item. self._get_clerk() returns the clerk that saves files. |
Describer |
describe(self, item, **kwargs) |
A table, stored in tables. |
Splitter |
divide(self, item, test_size, **kwargs) |
The training and test index labels. |
Evaluator |
evaluate(self, item, **kwargs) |
A table, stored in tables. |
Inferer |
infer(self, item, **kwargs) |
An amos.Inference: the table of estimates (with a "coefficient" column), stored in tables, the fitted estimator, stored in fitted, and any other tables and details to record. |
Plot |
draw(self, item, figure, **kwargs) |
Nothing: it draws on figure. |
Transformer, Sampler, Model, Validator, Metric |
Set contents to a tool. A Model can also name its assumptions and needs (see Assumptions), and set its package and complexity, so that auto_model can choose it. |
|
Pretest |
Nothing: name the pretest in the pretested_by of an amos.Assumption or amos.Need (see Assumptions). |
|
Audit |
Nothing: name the audit in the audited_by of an amos.Assumption. |
|
Chooser |
apply(self, item, **kwargs), and set chooses to a genre and step_names to the names of the steps that "auto" stands in for it in. |
The changed Dataset. |
Operation |
apply(self, item, **kwargs) |
The changed Dataset. |
An apply that a subclass writes always gets a Dataset and the technique's
parameters, whatever its caller passed, and the technique is recorded in the
dataset's history unless apply records it itself. A call to
super().apply(...) passes its arguments on exactly as they are.
Keyword parameters of these methods are filled from the settings. For example, a cleaner that limits extreme values (winsorizes):
@dataclasses.dataclass
class Winsorize(amos.Cleaner):
"""Limits each numeric column to its 1st and 99th percentiles."""
def clean(self, data, lower = 0.01, upper = 0.99, **kwargs):
numbers = data.select_dtypes("number")
limits = numbers.quantile([lower, upper])
data[numbers.columns] = numbers.clip(
limits.iloc[0], limits.iloc[1], axis = 1)
return data
dataset = amos.Dataset.create(cancer, seed = 43)
Winsorize().apply(dataset, upper = 0.95)
entry = dataset.history[-1]
print(entry["rows"], entry["columns"], len(entry["changed"]))
# [569, 569] [31, 31] 30
That cleaner looks at every row, so it belongs before the split. A technique
that learns from the data should be a Transformer, so that it learns only
from the training rows. Most transformers, samplers, models, and metrics need
no code at all: set contents to the import path of a scikit-learn-style
tool. Its parameters (and columns, for a transformer) come from the settings:
@dataclasses.dataclass
class Spline(amos.Mixer):
contents: str = "sklearn.preprocessing.SplineTransformer"
@dataclasses.dataclass
class BayesRidge(amos.Model):
contents: str = "sklearn.linear_model.BayesianRidge"
@dataclasses.dataclass
class MedianError(amos.Metric):
contents: str = "sklearn.metrics.median_absolute_error"
greater_is_better = False
tasks = ("regress",)
settings = {
"general": {"label": "target", "seed": 43},
"diabetes_project": {"techniques": "train_test, spline, bayes_ridge"},
"spline_parameters": {"columns": ["bmi"], "n_knots": 4},
}
project = amos.Project.create(settings, item = diabetes)
print(type(project.result.model).__name__, MedianError().measure(project.result) > 0)
# BayesianRidge True
print(project.result.features[2:5])
# ['bmi_sp_0', 'bmi_sp_1', 'bmi_sp_2']
A model whose tool differs by task sets tools (a dict mapping "classify"
and "regress" to tools) instead of contents. A metric sets
greater_is_better, tasks, and uses_probabilities as class attributes,
and measure returns its score of a dataset. A metric is not a step of a
workflow, but because every metric is a chrisjen.Criteria, a new metric can
be the criterion of an experiment or one of the metrics of a scorecard or
validator.
Experiments¶
An experiment is a chrisjen contest that also records how every
combination did. You can build one in code, as any chrisjen worker. Its
populate method takes the nodes in order. A list of nodes is a set of
alternatives:
dataset = amos.Dataset.create(cancer, seed = 43)
amos.splitters.Stratified().apply(dataset)
experiment = amos.Experiment(name = "models", criteria = amos.metrics.F1())
experiment.populate([
[amos.scalers.Standard(), amos.scalers.Robust()],
[amos.models.Baseline(), amos.models.Logit()],
])
result = experiment.apply(dataset)
print(experiment.winner.endswith("logit"))
# True
print(result.tables["models_comparison"].shape)
# (4, 3)
scores has the score of each combination, results the dataset that each
made, and winner the label of the best. The criterion of an experiment can be
a metric for which lower is better (such as log_loss). It is negated to rank
the combinations, but the table shows its real value. The winning dataset also
keeps a Branch for every combination in its branches: the technique used at
each step, its score, and its predictions, which is what a scorecard compares.
Keeping every combination's whole dataset (its features and fitted model) lets
a regression_table show each combination's model, but with many
combinations, or a large dataset, they may not all fit in memory. If
conserve_memory is true, an experiment keeps only the best dataset so far
while it tries the combinations, so no more than two are in memory at once.
Set it for one experiment in its section of the settings, or for every
experiment (and contest or survey) in the "general" section:
The comparison table, the scores, and the branches are the same, but only the
winner's dataset is in results, so a regression_table has only the
winner's model:
lean = amos.Experiment(
name = "models", criteria = amos.metrics.F1(), conserve_memory = True)
lean.populate([
[amos.scalers.Standard(), amos.scalers.Robust()],
[amos.models.Baseline(), amos.models.Logit()],
])
winner = lean.apply(dataset)
print(list(lean.results) == [lean.winner], len(winner.branches))
# True 4
Critics and artists for each model¶
Some evaluators, inferers, and plots suit only some models: an importance
plot suits a random forest, and a ROC curve suits any classifier. A model's
parameters section can name the "plots", "evaluators", and "inferers" to
use when it is the dataset's model, such as the winner of a contest. They
replace the techniques of those genres (and auto_plot and
auto_evaluator, or an auto that chooses them) that the workflow applies
after the model is fitted. A model that names none keeps the workflow's:
settings = {
"general": {"label": "target", "seed": 43},
"cancer_project": {"cancer_workers": ["analyst", "critic", "artist"]},
"analyst": {
"design": "contest",
"criterion": "f1",
"steps": ["split", "scale", "model"],
"split_techniques": ["stratified"],
"scale_techniques": ["standard"],
"model_techniques": ["logit", "random_forest"],
},
"critic": {"techniques": ["scorecard"]},
"artist": {"techniques": ["confusion_heatmap"]},
"logit_parameters": {"plots": ["roc_curve", "precision_recall_curve"]},
"random_forest_parameters": {
"plots": ["importance_plot"],
"evaluators": ["permutation_importance"],
},
}
project = amos.Project.create(settings, item = cancer)
print([entry["technique"] for entry in project.result.history])
# ['stratified', 'standard', 'logit', 'scorecard', 'confusion_heatmap', 'roc_curve', 'precision_recall_curve']
print(sorted(project.result.figures), "scorecard" in project.result.tables)
# ['precision_recall_curve', 'roc_curve'] True
settings["analyst"]["model_techniques"] = ["random_forest"]
forest = amos.Project.create(settings, item = cancer)
print(sorted(forest.result.figures), sorted(forest.result.tables))
# ['importance_plot'] ['assumptions', 'permutation_importance']
The first technique of a genre that the workflow applies after the model is
fitted applies the model's techniques instead, and the later ones of that
genre are left out. Each records the "model" and the techniques it was
"replaced_by" in history. The model's techniques are built like any other,
with their own parameters sections, and they may be workers. They are not
parameters of the model (so a list of them is never searched), and they are
kept in the winning settings that export_replication saves. Write them in
the model's own "{model}_parameters" section (such as "xgboost_parameters",
or "xgboost2_parameters" for "xgboost2"), not a step's. They apply only in a
project: a technique applied by itself is never replaced.
Cross-validation¶
A validator measures how well the model does on rows that it did not learn
from, without using the test rows. It is the last step of the analyst, after
the model. It divides the training rows into folds with one of
scikit-learn's cross-validation splitters (k_fold, stratified_k_fold,
group_k_fold, time_series_split, and the others in the technique
catalog), fits a new copy of the model to the
rest of the training rows for each fold, and scores the copy on the fold. The
scores of each fold are a table, stored under the validator's name, and their
means are stored in metrics as "cv_{metric}". A scorecard and an
experiment's comparison table show them beside the scores on the test rows:
[analyst]
design = experiment
criterion = roc_auc
steps = split, scale, sample, model, validate
split_techniques = stratified
scale_techniques = standard
sample_techniques = none, smote
model_techniques = logit, random_forest
validate_techniques = stratified_k_fold
A validator takes the parameters of its splitter (such as n_splits, the
number of folds, and n_repeats for repeated_k_fold), and:
| Parameter | Meaning |
|---|---|
metrics |
The metrics to score each fold with. Defaults to the metrics of a scorecard for the task. |
groups |
For group_k_fold and the other validators of groups, the column that identifies each row's group. Defaults to the dataset's first group. |
order |
A column (such as a date) to order the rows by before they are divided, for time_series_split. |
shuffle |
Whether to shuffle the rows (with the dataset's seed) before dividing them, for a splitter that can. Defaults to True. |
dataset = amos.Dataset.create(cancer, seed = 43)
amos.splitters.Stratified().apply(dataset)
amos.scalers.Standard().apply(dataset)
amos.samplers.Smote().apply(dataset)
amos.models.Logit().apply(dataset)
amos.validators.StratifiedKFold().apply(dataset, metrics = ["roc_auc", "f1"])
print(dataset.tables["stratified_k_fold"].columns.tolist())
# ['train', 'validation', 'roc_auc', 'f1']
print(sorted(name for name in dataset.metrics if name.startswith("cv_")))
# ['cv_f1', 'cv_roc_auc']
Rows that a sampler made up (the dataset's synthetic rows) are never
scored, since they are not real observations. Instead, each sampler is
applied again to the rows that each copy of the model learns from, as it was
to all of the training rows. Transformers are not fitted again, so a validator
scores the model given the features that the transformers made from all of
the training rows, and a model whose parameters were searched for keeps the
values found with all of the training rows.
leave_one_row_out predicts each row with a copy of the model fitted to every
other row. A fold of one row cannot be scored alone, so its predictions are
scored together, and its table has the prediction of each row.
Scorecards¶
The scorecard is the critic's summary of an analysis. It has one row for
each branch of the most recent experiment (each combination of techniques),
ranked by the experiment's criterion:
| Column | Meaning |
|---|---|
rank |
1 for the best branch. |
| One for each step | The technique used at that step. Steps are named as in the settings (such as "scale"), or by their genre (such as "scaler") in an experiment built in code. |
| One for each metric | The branch's score, computed from its own predictions on the test rows: the criterion first, then the other standard metrics for the task, then any other metrics the branches computed. |
A dataset that did not come from an experiment gets one row for its final
model, with the techniques that made it. As a technique in the critic,
scorecard stores its table in the dataset's tables and the final model's
scores in its metrics. Its "metrics" parameter chooses the metrics, and the
scorecard_digits and scorecard_title settings (in the critic's section) set
the digits shown and the title.
In Python, use Project.scorecard (which returns the critic's scorecard, or
makes one) or Scorecard.create with a dataset or a project:
scorecard = amos.evaluators.Scorecard.create(result)
print(scorecard.heading)
# 4 branches ranked by f1
print(list(scorecard.table.columns[:4]))
# ['rank', 'scaler', 'model', 'f1']
print(scorecard.to_markdown().splitlines()[1])
# | ---: | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
A scorecard can be saved in several formats:
| Method | Saves | Needs |
|---|---|---|
to_csv(path) |
A csv file, with scores at full precision. It also returns the text. | |
to_markdown(path) |
A Markdown table, with numbers aligned to the right. It also returns the text. | |
to_latex(path) |
A LaTeX table (with the booktabs package). It also returns the text. | |
to_html(path) |
An HTML table. It also returns the HTML. | great_tables (amos[tables]) |
to_word(path) |
A Word document with a heading and a table. | python-docx (amos[word]) |
to_image(path) |
An image of the table, in the format of the file's extension (such as png, svg, or pdf). to_figure returns the matplotlib figure instead. |
matplotlib (amos[plots]) |
export(folder, formats) |
Several formats, named "scorecard" (csv, md, docx, and png by default; also tex, html, svg, and pdf). |
Scores in the Markdown table, Word document, and image are rounded to digits
(3 by default). The title of the Word document and image is title, or a
description of the branches if there is no title.
Regression tables¶
A regression_table puts the estimates of every model side by side, like the
regression tables of Stata, R, and statsmodels. It has a column for each branch
of the most recent experiment (named by the steps that differ between
branches), or one column for the final model. Each feature has two rows: its
estimate, with stars for its p-value, and below it, its standard error in
parentheses. Below the estimates are the kind of estimates, the number of
observations that the model learned from, and the model's cross-validated
metrics.
Only some models have coefficients with standard errors, so a model gets one of two kinds of estimates:
| Model | Estimates | Standard errors and p-values |
|---|---|---|
A model that reports its coefficients: ols, logit_sm, glm, fixest, cox, and the other statsmodels and pyfixest models |
Its coefficients | The model's own |
Any other model, such as random_forest, xgboost, knn, and the scikit-learn linear models (linear, logit, ridge, and others, whose coefficients have no standard errors) |
Average marginal effects | Refitting the model to bootstrap samples of the training rows |
An average marginal effect (AME) is the average change in the prediction for a one-unit increase in a feature, with the other features held where they are. For a classifier, it is the change in the predicted probability of the positive class (or of each class, named "{feature} ({class})"). Every model has one, and the AME of a linear regression is its coefficient. Each feature is moved up and down by a small step for every training row. A boolean feature, or one with only two values, moves from its lower value to its higher one.
| Parameter | Meaning |
|---|---|
marginal |
Whether to show marginal effects for every model, even one with coefficients. This puts every column on the same scale (the coefficients of logit_sm, for example, are log odds). Defaults to false. |
simulations |
Number of bootstrap samples for the standard errors of marginal effects. Defaults to 100. |
step |
Standard deviations that each feature is moved up and down. Defaults to 0.1. |
validator |
The validator that cross-validates each model, if the analysis did not. Defaults to stratified_k_fold to classify and k_fold to regress. |
metrics |
The cross-validated metrics. Defaults to accuracy, ROC AUC, and log loss to classify, and R², RMSE, and MAE to regress. |
The regression_table_title, regression_table_digits,
regression_table_stars, and regression_table_style settings (in the
critic's section) set the title, the digits shown, the p-values below which an
estimate gets one, two, and three stars (0.1, 0.05, and 0.01 by default), and
the layout of Word documents and images ("stata" by default, or
"columns"). In Python, use RegressionTable.create
with a dataset, an applied project, or several datasets with fitted models (a
dict names their columns):
table = amos.evaluators.RegressionTable.create(result, simulations = 10)
print(list(table.statistics.columns))
# ['standard / baseline', 'standard / logit', 'robust / baseline', 'robust / logit']
print(list(table.statistics.index))
# ['estimates', 'observations', 'cv_accuracy', 'cv_roc_auc', 'cv_log_loss']
print(table.table.loc[0, "standard / logit"], table.table.loc[1, "standard / logit"])
# -0.012*** (0.002)
As a technique in the critic, regression_table stores the estimates in the
dataset's tables under its name, with one row for each model and feature
(their "estimate", "standard_error", "statistic", "p_value", "ci_lower", and
"ci_upper"), and the rows below them as "regression_table_statistics". Like a
scorecard, it can be saved with to_csv, to_markdown, to_latex,
to_html, to_word, to_image, and export. csv, Markdown, LaTeX, and HTML
put the models side by side, with stars, like Stata's esttab. Notes below
the table explain the parentheses and stars. to_csv saves the table as
text, as it is published. The numbers at full precision are in estimates
and statistics.
Word documents, images, and to_text look like Stata's output of regress.
Each model is a block. At its top are its name, its kind of estimates, and
(for marginal effects) what they are changes in. Beside them are the number
of observations, the number of bootstrap samples ("Replications"), and the
cross-validated metrics. Below is a table of its terms ("Coef." or "dy/dx",
"Std. Err.", "t" or "z", its p-value, and its 95% confidence interval), with
numbers written as Stata writes them (such as "-.0115626"), between rules,
with a bar after the terms. Coefficients get a t statistic if the model's
results use the t distribution (as least squares and fixest do), and a z
statistic otherwise. Set the regression_table_style setting (or style) to
"columns" to put the models side by side in Word documents and images too:
print(table.to_text().splitlines()[0].split())
# ['standard', '/', 'baseline', 'Number', 'of', 'obs', '=', '426']
Some statistics of a regression table have no meaning for most machine learning models, so these take their place:
- R², log-likelihood, and pseudo-R². A flexible model can fit the rows that it learned from almost perfectly, so its metrics are cross-validated instead. They are the "cv_{metric}" metrics of a validator, if the analysis has one.
- Adjusted R², AIC, BIC, and the F-test. These need a count of the model's parameters, which a forest or a boosted model does not have. Cross-validated metrics do the same job: they penalize a model that overfits.
- Coefficients, standard errors, and p-values. Average marginal effects with bootstrapped standard errors.
A marginal effect describes the model, not the world. It is causal only if the features are, so use an inferer to estimate the effect of a treatment. An AME can mislead when features are correlated, since moving one while holding the others fixed makes rows unlike any real one. The bootstrap treats rows as independent, so its standard errors are too small for rows that are correlated within groups or over time.
Reports and exports¶
Findings, the default report, describes the data, the split, the workflow,
the winner of each experiment or contest, the model, the metrics, and the
tables and figures. To use another report, pass a chrisjen.Report as
report to Project.create.
Project.export saves these files with the project's clerk (an
amos.Clerk), in a folder named for the run in the output folder (the
"studies" folder of the workspace, unless the settings name another):
| File | Contents |
|---|---|
| report.txt | The text of the report. |
| settings.json | The settings of the project. |
| {project}_replication.json | The settings of only the winning path, if the workflow has an experiment or contest (see below). |
| environment.json | The versions of Python and of the packages used, and the GPUs, if use_gpu is true. |
| history.json | Each technique applied, with its tool and parameters. |
| metrics.csv | The model's metrics. |
| predictions.csv | The labels, predictions, and probabilities of the predicted rows. |
| tables/{name}.csv | Each table. |
| figures/{name}.png | Each figure. |
| scorecard.csv, .md, .docx, .png | The scorecard in each format. The Word document and image are saved if python-docx and matplotlib are installed. |
| regression_table.csv, .md, .docx, .png | Each regression_table in the workflow (named for the technique), in the same formats as the scorecard. |
| data.csv | The data after the workflow, if export(data = True). |
"{project}_replication.json" (such as "cancer_replication.json") holds the
settings that Project.winning_settings returns, so that another researcher
can pass the file to Project.create to fit the winning path alone. Each
experiment or contest becomes a flow:
- Each step that it compared (or, without steps, the worker itself) keeps only the technique of the winning path, and its "design", "criterion", and "conserve_memory" settings are dropped.
- The parameters sections of the techniques that lost are dropped, unless another worker still names the technique, and so are their own worker sections and feature groups.
- A model that searched for its hyperparameters is given the values that the search chose, without its "search", "cv", "n_iter", and "scoring".
- Each "pipeline" setting is dropped, since the settings of the pipeline are already filled in.
The winner of an experiment inside another worker that compares paths is
found in the history. A plain contest does not record its winner there, so
one inside another keeps every alternative.
bobbie writes the file, in any format that a settings file can have: set
replication_format in the "files" section, or pass replication_format to
export. "toml" and "yaml" need the settings extra
(pip install amos[settings]). Project.export_replication saves the file
alone, and takes a folder, a file_name (without its extension), and a
file_format.
Errors you may see¶
| Error | Cause |
|---|---|
ValueError: there is no data |
The project has no item and no loader. Pass the data as item, or add a loader (such as load_file) to the wrangler. |
ValueError: '...' has nothing to load |
A loader has no "source". Set it in the {loader}_parameters section. |
ValueError: the pattern '...' is not valid: ... |
A munger's pattern is not a valid regular expression. A character with a special meaning (such as "(") needs a backslash to stand for itself. |
TypeError: '...' uses text, but '...' is not text |
A munger that searches text was given a column of numbers, dates, or booleans. |
ValueError: '...' has nothing to merge |
A merger has no "source". Set it in the {merger}_parameters section. |
ValueError: ... rows of the other table have the same [...] as another of its rows |
A row of the data can match only one row of the other table. Set "duplicates" to "first" or "last" to use one of them, or summarize them with merge_summary. |
TypeError: '...' cannot match '...', which is numbers in the data, with '...', which is text in the other table |
A key is not the same kind of data in both tables. Change the column of the data with a cleaner (such as clean_numbers or clean_dates) or a munger (such as convert_types). |
ValueError: '...' would add columns named [...], which the data already has |
A merger was told to add a column whose name is taken. Set its "prefix". |
ValueError: '...' changes the rows of the data, so it must come before the data is split |
A shaper came after a splitter. Reshape the data in the wrangler. |
KeyError: the reshaped data has no columns [...], which are the label or groups |
A shaper left the data without its label or a group. Set the shaper's "label" or "groups" to those of the reshaped data. |
ValueError: the dataset has no label |
A technique needs a label. Set "label" in the "general" section or pass it to Dataset. |
ValueError: the data has not been split |
A technique asked for the test rows before a splitter was applied. |
ValueError: '...' cannot use the dates or text in [...] |
A model was given text or dates. Encode them (with an encoder such as one_hot) or remove them (with drop_columns) first. |
ValueError: '...' can classify, but the label is set to regress |
The model does only one task. Choose another model or set "task". |
ValueError: '...' needs predictions: apply a model first |
An evaluator or plot came before the model, or a metric scored a dataset without one. |
ValueError: '...' needs predicted probabilities, which the model does not make |
The metric (such as roc_auc) needs probabilities. |
ImportError: ... install it with "pip install amos[...]" |
The technique wraps an optional package that is not installed. |
ValueError: '...' needs a group |
A fairness metric or fairness was used without groups. Set "groups" in the "general" section or pass "group". |
KeyError: the fixed_effects column ... is not in the data |
A column named by a model's parameter (such as "fixed_effects", "cluster", or "event") is missing. |
ValueError: '...' needs the name of a "treatment" column |
An inferer was used without a "treatment" parameter. |
ImportError: causalml has no version for Python 3.13 and later ... |
causalml's inferers (such as x_learner) need Python 3.11 or 3.12. Use another package's inferer, such as DoubleML's interactive_regression. |
ImportError: ... The causal extra ... installs DoWhy on Python 3.13 and later ... |
DoWhy's inferers (such as propensity_matching) need DoWhy, which the causal extra installs on Python 3.13 and later. |
TypeError: '...' is a metric, not a technique, so it cannot be a step of a workflow |
A metric (such as roc_auc) was listed in a worker's techniques. Name it as the worker's criterion, or in the metrics of a scorecard or validator. |
KeyError: no class named ... is in the library |
A name in the settings is not a technique. Check the spelling against the technique catalog. |
ValueError: '...' needs the name of a "groups" column |
A splitter or validator of groups (such as group_k_fold) was used without groups. Set "groups" in the "general" section or pass "groups". |
ValueError: a copy of the model could not predict ... |
A validator's copy of the model could not predict the rows of a fold. A model that cannot predict a group it did not learn from needs a validator that does not keep groups apart (such as k_fold). (fixest predicts a group it did not learn from with the average of its fixed effects.) |
ValueError: ... needs criteria to compare results |
An experiment or contest has no "criterion" setting. |