-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorchestrate.py
170 lines (130 loc) · 5 KB
/
orchestrate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import pathlib
import pickle
import pandas as pd
import numpy as np
import scipy
import sklearn
from sklearn.feature_extraction import DictVectorizer
from sklearn.metrics import mean_squared_error
import mlflow
import xgboost as xgb
from prefect import flow, task
from prefect.artifacts import create_markdown_artifact
from datetime import date
from prefect_email import EmailServerCredentials, email_send_message
@flow
def example_email_send_message_flow(email_addresses):
email_server_credentials = EmailServerCredentials.load("email-creds")
for email_address in email_addresses:
subject = email_send_message.with_options(name=f"email {email_address}").submit(
email_server_credentials=email_server_credentials,
subject="Example Flow Notification using Gmail",
msg="This proves email_send_message works!",
email_to=email_address,
)
example_email_send_message_flow(["EMAIL-ADDRESS-PLACEHOLDER"])
@task(retries=3, retry_delay_seconds=2, name="Read taxi data")
def read_data(filename: str) -> pd.DataFrame:
"""Read data into DataFrame"""
df = pd.read_parquet(filename)
df.lpep_dropoff_datetime = pd.to_datetime(df.lpep_dropoff_datetime)
df.lpep_pickup_datetime = pd.to_datetime(df.lpep_pickup_datetime)
df["duration"] = df.lpep_dropoff_datetime - df.lpep_pickup_datetime
df.duration = df.duration.apply(lambda td: td.total_seconds() / 60)
df = df[(df.duration >= 1) & (df.duration <= 60)]
categorical = ["PULocationID", "DOLocationID"]
df[categorical] = df[categorical].astype(str)
return df
@task
def add_features(
df_train: pd.DataFrame, df_val: pd.DataFrame
) -> tuple(
[
scipy.sparse._csr.csr_matrix,
scipy.sparse._csr.csr_matrix,
np.ndarray,
np.ndarray,
sklearn.feature_extraction.DictVectorizer,
]
):
"""Add features to the model"""
df_train["PU_DO"] = df_train["PULocationID"] + "_" + df_train["DOLocationID"]
df_val["PU_DO"] = df_val["PULocationID"] + "_" + df_val["DOLocationID"]
categorical = ["PU_DO"] #'PULocationID', 'DOLocationID']
numerical = ["trip_distance"]
dv = DictVectorizer()
train_dicts = df_train[categorical + numerical].to_dict(orient="records")
X_train = dv.fit_transform(train_dicts)
val_dicts = df_val[categorical + numerical].to_dict(orient="records")
X_val = dv.transform(val_dicts)
y_train = df_train["duration"].values
y_val = df_val["duration"].values
return X_train, X_val, y_train, y_val, dv
@task(log_prints=True, name="Train best model")
def train_best_model(
X_train: scipy.sparse._csr.csr_matrix,
X_val: scipy.sparse._csr.csr_matrix,
y_train: np.ndarray,
y_val: np.ndarray,
dv: sklearn.feature_extraction.DictVectorizer,
) -> None:
"""train a model with best hyperparams and write everything out"""
with mlflow.start_run():
train = xgb.DMatrix(X_train, label=y_train)
valid = xgb.DMatrix(X_val, label=y_val)
best_params = {
"learning_rate": 0.09585355369315604,
"max_depth": 30,
"min_child_weight": 1.060597050922164,
"objective": "reg:linear",
"reg_alpha": 0.018060244040060163,
"reg_lambda": 0.011658731377413597,
"seed": 42,
}
mlflow.log_params(best_params)
booster = xgb.train(
params=best_params,
dtrain=train,
num_boost_round=100,
evals=[(valid, "validation")],
early_stopping_rounds=20,
)
y_pred = booster.predict(valid)
rmse = mean_squared_error(y_val, y_pred, squared=False)
mlflow.log_metric("rmse", rmse)
pathlib.Path("models").mkdir(exist_ok=True)
with open("models/preprocessor.b", "wb") as f_out:
pickle.dump(dv, f_out)
mlflow.log_artifact("models/preprocessor.b", artifact_path="preprocessor")
mlflow.xgboost.log_model(booster, artifact_path="models_mlflow")
markdown__rmse_report = f"""# RMSE Report
## Summary
Duration Prediction
## RMSE XGBoost Model
| Region | RMSE |
|:----------|-------:|
| {date.today()} | {rmse:.2f} |
"""
create_markdown_artifact(
key="duration-model-report", markdown=markdown__rmse_report
)
return None
@flow(log_prints=True)
def main_flow(
train_path: str = "./data/green_tripdata_2021-01.parquet",
val_path: str = "./data/green_tripdata_2021-02.parquet",
) -> None:
"""The main training pipeline"""
# MLflow settings
mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("nyc-taxi-experiment")
# Load
df_train = read_data(train_path)
df_val = read_data(val_path)
# Transform
X_train, X_val, y_train, y_val, dv = add_features(df_train, df_val)
# Train
train_best_model(X_train, X_val, y_train, y_val, dv)
example_email_send_message_flow(["[email protected]"])
if __name__ == "__main__":
main_flow()