Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Risklist module for production #631

Merged
merged 55 commits into from
Aug 27, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
55 commits
Select commit Hold shift + click to select a range
a563694
listmaking WIP
thcrock Feb 20, 2019
9750c3e
forgot migraton
thcrock Feb 20, 2019
360f8f9
WIP
tweddielin Feb 21, 2019
999a46f
alembic add label_value to list_predictions table
tweddielin Feb 26, 2019
372d9c8
add docstrings
tweddielin Feb 28, 2019
16645bc
move risklist a layer above
tweddielin Mar 13, 2019
914ad76
create risklist module
tweddielin Mar 13, 2019
c92bd8b
__init__lpy
tweddielin Mar 13, 2019
d3c3ba9
fix alembic reversion and replace metta.generate_uuid with filename_f…
tweddielin Mar 13, 2019
0e92fb0
Fix down revision of production schema migration
thcrock Apr 12, 2019
dbd4578
Fix alembic revisions
thcrock Jan 6, 2021
f7d49e5
Enable github checks on this branch too
thcrock Jan 6, 2021
dee930f
Closer to getting tests to run
thcrock Jan 6, 2021
1769b00
Add CLI for risklist
thcrock Jan 8, 2021
52c9ff0
Risklist docs stub
thcrock Jan 8, 2021
173167a
Break up data gathering into experiment and matrix, use pytest fixtur…
thcrock Jan 9, 2021
f6b2d02
Modify schema for list prediction metadata
thcrock Jan 9, 2021
acffa67
fix conflicts and add helper functions for getting imputed features
tweddielin Jan 9, 2021
43c1919
Handle other imputation flag cases, fix tracking indentation error
thcrock Jan 10, 2021
7dfb7e1
Add more tests, fill out doc page
thcrock Jan 11, 2021
cc9fe4a
Fix exception name typo
thcrock Jan 11, 2021
5951565
use timechop and planner to create matrix_metadata for production
tweddielin Jan 15, 2021
537f6c8
retrain and predict forward
tweddielin Apr 15, 2021
b429540
rename to retrain_definition
tweddielin Apr 15, 2021
0045aa5
reusing random seeds from existing models
shaycrk May 8, 2021
9dc3697
fix tests (write experiment to test db)
shaycrk May 10, 2021
da870d5
unit test for reusing model random seeds
shaycrk May 10, 2021
6768ee5
add docstring
shaycrk May 10, 2021
7d6a420
only store random seed in experiment runs
shaycrk May 20, 2021
b8fe6d8
DB migration to remove random seed from experiments table
shaycrk May 20, 2021
8207fcd
debugging
shaycrk May 20, 2021
45c9d68
debug model trainer tests
shaycrk May 21, 2021
a665e7e
debug catwalk utils tests
shaycrk May 21, 2021
ead882b
debug catwalk integration test
shaycrk May 21, 2021
de85f10
use public method
tweddielin May 30, 2021
ad860cd
Merge remote-tracking branch 'origin/kit_rand_seed' into list_making
tweddielin May 31, 2021
40466d5
alembic merge
tweddielin May 31, 2021
83c7385
reuse random seed
tweddielin May 31, 2021
f97089b
use timechop for getting retrain information
tweddielin Jun 30, 2021
6f0af1c
create retrain model hash in retrain level instead of model_trainer l…
tweddielin Jun 30, 2021
42bccaa
move util functions to utils
tweddielin Jun 30, 2021
3ec377f
fix cli and docs
tweddielin Jul 1, 2021
1c4da24
update docs
tweddielin Jul 1, 2021
35bd978
use reconstructed feature dict
tweddielin Jul 1, 2021
9f5a099
add RetrainModel and Retrain
tweddielin Jul 29, 2021
ba84822
remove break point
tweddielin Jul 29, 2021
83e0f66
change experiment_runs to triage_runs
tweddielin Aug 21, 2021
d6f14f5
get retrain_config
tweddielin Aug 22, 2021
d76359b
explicitly include run_type in joins to triage_runs
shaycrk Aug 26, 2021
9698500
DB migration updates
shaycrk Aug 26, 2021
a8a29f1
update argument name in docs
shaycrk Aug 26, 2021
694edcc
ensure correct temporal config is used for predicting forward
shaycrk Aug 27, 2021
583e9bd
debug
shaycrk Aug 27, 2021
815a258
debug
shaycrk Aug 27, 2021
5e183fe
Merge branch 'master' into list_making
shaycrk Aug 27, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,85 +1,87 @@
# Predictlist
If you would like to generate a list of predictions on already-trained Triage model with new data, you can use the 'Predictlist' module.

# Predict Foward with Existed Model
Use an existing model object to generate predictions on new data.
# Retrain and Predict
Use an existing model group to retrain a new model on all the data up to the current date and then predict forward into the future.

## Examples
Both examples assume you have already run a Triage Experiment in the past, and know these two pieces of information:
1. A `model_id` from a Triage model that you want to use to generate predictions
2. An `as_of_date` to generate your predictions on.
1. A `model_group_id` from a Triage model group that you want to use to retrain a model and generate prediction
2. A `today` to generate your predictions on.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we changed the argument to prediction_date rather than today, didn't we?


### CLI
`triage predictlist <model_id> <as_of_date>`
`triage retrainpredict <model_group_id> <today>`

Example:
`triage predictlist 46 2019-05-06`
`triage retrainpredict 30 2021-04-04`

The predictlist will assume the current path to be the 'project path' to find models and write matrices, but this can be overridden by sending the `--project-path` option.
The `retrainpredict` will assume the current path to be the 'project path' to train models and write matrices, but this can be overridden by sending the `--project-path` option

### Python
The `Retrainer` class from `triage.predictlist` module can be used to retrain a model and predict forward.

The `predict_forward_with_existed_model` function from the `triage.predictlist` module can be used similarly to the CLI, with the addition of the database engine and project storage as inputs.
```
from triage.predictlist import generate predict_forward_with_existed_model
```python
from triage.predictlist import Retrainer
from triage import create_engine

predict_forward_with_existed_model(
retrainer = Retrainer(
db_engine=create_engine(<your-db-info>),
project_path='/home/you/triage/project2'
model_id=46,
as_of_date='2019-05-06'
model_group_id=36,
)
retrainer.retrain(today='2021-04-04')
retrainer.predict(today='2021-04-04')

```

## Output
The Predictlist is stored similarly to the matrices created during an Experiment:
The retrained model is sotred similariy to the matrices created during an Experiment:
- Raw Matrix saved to the matrices directory in project storage
- Raw Model saved to the trained_model directory in project storage
- Retrained Model info saved in a table (triage_metadata.models) where model_comment = 'retrain_2021-04-04 21:19:09.975112'
- Predictions saved in a table (triage_production.predictions)
- Prediction metadata (tiebreaking, random seed) saved in a table (triage_production.prediction_metadata)
- Prediction metadata (tiebreaking, random seed) saved in a table (triage_produciton.prediction_metadata)

## Notes
- The cohort and features for the Predictlist are all inferred from the Experiment that trained the given model_id (as defined by the experiment_models table).
- The feature list ensures that imputation flag columns are present for any columns that either needed to be imputed in the training process, or that needed to be imputed in the predictlist dataset.

# Retrain and Predict
Use an existing model group to retrain a new model on all the data up to the current date and then predict forward into the future.
# Predictlist
If you would like to generate a list of predictions on already-trained Triage model with new data, you can use the 'Predictlist' module.

# Predict Foward with Existed Model
Use an existing model object to generate predictions on new data.

## Examples
Both examples assume you have already run a Triage Experiment in the past, and know these two pieces of information:
1. A `model_group_id` from a Triage model group that you want to use to retrain a model and generate prediction
2. A `today` to generate your predictions on.
1. A `model_id` from a Triage model that you want to use to generate predictions
2. An `as_of_date` to generate your predictions on.

### CLI
`triage retrainpredict <model_group_id> <today>`
`triage predictlist <model_id> <as_of_date>`

Example:
`triage retrainpredict 30 2021-04-04`
`triage predictlist 46 2019-05-06`

The `retrainpredict` will assume the current path to be the 'project path' to train models and write matrices, but this can be overridden by sending the `--project-path` option
The predictlist will assume the current path to be the 'project path' to find models and write matrices, but this can be overridden by sending the `--project-path` option.

### Python
The `Retrainer` class from `triage.predictlist` module can be used to retrain a model and predict forward.

```python
from triage.predictlist import Retrainer
The `predict_forward_with_existed_model` function from the `triage.predictlist` module can be used similarly to the CLI, with the addition of the database engine and project storage as inputs.
```
from triage.predictlist import generate predict_forward_with_existed_model
from triage import create_engine

retrainer = Retrainer(
predict_forward_with_existed_model(
db_engine=create_engine(<your-db-info>),
project_path='/home/you/triage/project2'
model_group_id=36,
model_id=46,
as_of_date='2019-05-06'
)
retrainer.retrain(today='2021-04-04')
retrainer.predict(today='2021-04-04')
```

## Output
The retrained model is sotred similariy to the matrices created during an Experiment:
The Predictlist is stored similarly to the matrices created during an Experiment:
- Raw Matrix saved to the matrices directory in project storage
- Raw Model saved to the trained_model directory in project storage
- Retrained Model info saved in a table (triage_metadata.models) where model_comment = 'retrain_2021-04-04'
- Predictions saved in a table (triage_production.predictions)
- Prediction metadata (tiebreaking, random seed) saved in a table (triage_produciton.prediction_metadata)
- Prediction metadata (tiebreaking, random seed) saved in a table (triage_production.prediction_metadata)

## Notes
- The cohort and features for the Predictlist are all inferred from the Experiment that trained the given model_id (as defined by the experiment_models table).
- The feature list ensures that imputation flag columns are present for any columns that either needed to be imputed in the training process, or that needed to be imputed in the predictlist dataset.


2 changes: 1 addition & 1 deletion src/tests/test_predictlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def test_retrain_should_write_model(finished_experiment):
model_group_id=model_group_id,
)
retrain_info = retrainer.retrain(prediction_date)
model_comment = retrain_info['retrain_model_comment']
model_comment = retrain_info['retrained_model_comment']

records = [
row
Expand Down
6 changes: 3 additions & 3 deletions src/triage/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ def __init__(self, parser):
)

parser.add_argument(
"today",
"prediction_date",
type=valid_date,
help="The date as of which to run features. Format YYYY-MM-DD",
)
Expand All @@ -428,8 +428,8 @@ def __call__(self, args):
args.project_path,
args.model_group_id,
)
retrainer.retrain(args.today)
retrainer.predict(args.today)
retrainer.retrain(args.prediction_date)
retrainer.predict(args.prediction_date)


@Triage.register
Expand Down
17 changes: 9 additions & 8 deletions src/triage/component/catwalk/model_trainers.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,14 @@ def _write_model_to_db(
return model_id
else:
if retrain:
logger.debug("Retrain model...")
model = Model(
model_group_id=model_group_id,
model_hash=model_hash,
model_type=class_path,
hyperparameters=parameters,
built_by_retrain=self.experiment_hash,
built_in_triage_run=self.run_id,
model_size=model_size,
**misc_db_parameters,
)
Expand All @@ -234,7 +237,7 @@ def _write_model_to_db(
hyperparameters=parameters,
model_group_id=model_group_id,
built_by_experiment=self.experiment_hash,
built_in_experiment_run=self.run_id,
built_in_triage_run=self.run_id,
model_size=model_size,
**misc_db_parameters,
)
Expand Down Expand Up @@ -283,13 +286,11 @@ def _train_and_store_model(
unique_parameters = self.unique_parameters(parameters)


if model_hash is None and retrain and model_group_id:
model_hash = self._model_hash(
matrix_store.metadata,
class_path,
parameters,
random_seed,
)
if retrain:
# if retrain, use the provided model_group_id
if not model_group_id:
raise ValueError("model_group_id should be provided when retrain")

else:
model_group_id = self.model_grouper.get_model_group_id(
class_path, unique_parameters, matrix_store.metadata, self.db_engine
Expand Down
4 changes: 4 additions & 0 deletions src/triage/component/results_schema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@
from .schema import (
Base,
Experiment,
Retrain,
FeatureImportance,
IndividualImportance,
ListPrediction,
ExperimentMatrix,
Matrix,
ExperimentModel,
RetrainModel,
ExperimentRun,
ExperimentRunStatus,
Model,
Expand All @@ -39,11 +41,13 @@
__all__ = (
"Base",
"Experiment",
"Retrain",
"FeatureImportance",
"IndividualImportance",
"ListPrediction",
"ExperimentMatrix",
"Matrix",
"RetrainModel",
"ExperimentModel",
"ExperimentRun",
"ExperimentRunStatus",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""add run_type

Revision ID: 5dd2ba8222b1
Revises: 079a74c15e8b
Create Date: 2021-07-22 23:53:04.043651

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '5dd2ba8222b1'
down_revision = '079a74c15e8b'
branch_labels = None
depends_on = None


def upgrade():
op.create_table('retrain',
sa.Column('retrain_hash', sa.Text(), nullable=False),
sa.Column('config', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('prediction_date', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('retrain_hash'),
schema='triage_metadata',
)
op.add_column('experiment_runs', sa.Column('run_type', sa.Text(), nullable=True), schema='triage_metadata')
op.add_column('experiment_runs', sa.Column('retrain_hash', sa.Text(), nullable=True), schema='triage_metadata')
op.alter_column('models', 'built_in_experiment_run', nullable=False, new_column_name='built_in_triage_run', schema='triage_metadata')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe add here (to avoid any potential for data loss):

op.execute("CREATE TABLE triage_metadata.deprecated_models_built_by_experiment AS SELECT model_id, model_hash, built_by_experiment FROM triage_metadata.models")

op.add_column('models', sa.Column('built_by_retrain', sa.Text(), nullable=True), schema='triage_metadata')

op.create_table('retrain_models',
sa.Column('retrain_hash', sa.String(), nullable=False),
sa.Column('model_hash', sa.String(), nullable=False),
sa.ForeignKeyConstraint(['retrain_hash'], ['triage_metadata.retrain.retrain_hash'], ),
sa.PrimaryKeyConstraint('retrain_hash', 'model_hash'),
schema='triage_metadata'
)


def downgrade():
op.drop_column('experiment_runs', 'run_type', schema='triage_metadata')
op.drop_column('experiment_runs', 'retrain_hash', schema='triage_metadata')
op.drop_table('retrain_models', schema='triage_metadata')
op.drop_table('retrain', schema='triage_metadata')
op.drop_column('models', 'built_by_retrain', schema='triage_metadata')
op.alter_column('models', 'built_in_triage_run', nullable=False, new_column_name='built_in_experiment_run', schema='triage_metadata')

42 changes: 40 additions & 2 deletions src/triage/component/results_schema/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from sqlalchemy.orm import relationship
from sqlalchemy.types import ARRAY, Enum
from sqlalchemy.sql import func
from sqlalchemy.ext.hybrid import hybrid_property

# One declarative_base object for each schema created
Base = declarative_base()
Expand Down Expand Up @@ -71,13 +72,23 @@ class Experiment(Base):
models_needed = Column(Integer)


class Retrain(Base):
__tablename__ = "retrain"
__table_args__ = {"schema": "triage_metadata"}

retrain_hash = Column(String, primary_key=True)
config = Column(JSONB)
prediction_date = Column(DateTime)


class ExperimentRunStatus(enum.Enum):
started = 1
completed = 2
failed = 3


class ExperimentRun(Base):
# class TriageRun(Base):

__tablename__ = "experiment_runs"
__table_args__ = {"schema": "triage_metadata"}
Expand All @@ -88,10 +99,15 @@ class ExperimentRun(Base):
git_hash = Column(String)
triage_version = Column(String)
python_version = Column(String)
run_type = Column(String)
experiment_hash = Column(
String,
ForeignKey("triage_metadata.experiments.experiment_hash")
)
retrain_hash = Column(
String,
ForeignKey("triage_metadata.retrain.retrain_hash")
)
platform = Column(Text)
os_user = Column(Text)
working_directory = Column(Text)
Expand All @@ -113,6 +129,11 @@ class ExperimentRun(Base):
stacktrace = Column(Text)
random_seed = Column(Integer)
experiment_rel = relationship("Experiment")
retrain_rel = relationship("Retrain")

@hybrid_property
def external_hash(self):
return self.experiment_hash or self.retrain_hash


class Subset(Base):
Expand Down Expand Up @@ -225,8 +246,11 @@ class Model(Base):
built_by_experiment = Column(
String, ForeignKey("triage_metadata.experiments.experiment_hash")
)
built_in_experiment_run = Column(
Integer, ForeignKey("triage_metadata.experiment_runs.id")
built_by_retrain = Column(
String, ForeignKey("triage_metadata.retrain.retrain_hash")
)
built_in_triage_run = Column(
Integer, ForeignKey("triage_metadata.experiment_runs.id"), nullable=True
)
train_end_time = Column(DateTime)
test = Column(Boolean)
Expand Down Expand Up @@ -261,6 +285,20 @@ class ExperimentModel(Base):
experiment_rel = relationship("Experiment")


class RetrainModel(Base):
__tablename__ = "retrain_models"
__table_args__ = {"schema": "triage_metadata"}

retrain_hash = Column(
String,
ForeignKey("triage_metadata.retrain.retrain_hash"),
primary_key=True
)
model_hash = Column(String, primary_key=True)
model_rel = relationship("Model", primaryjoin=(Model.model_hash == model_hash), foreign_keys=model_hash)
retrain_rel = relationship("Retrain")


class FeatureImportance(Base):

__tablename__ = "feature_importances"
Expand Down
Loading