<jupyter_start><jupyter_text>Train a ModelIn this notebook, which can be run in your favorite Python notebook environment such as on your local machine, SageMaker, or Databricks, we will be training an XGBoost classifier to predict whether a transaction is fraudulent or not, using the training dataframe we constructed from stored Tecton features on our users layered in with the transactional information we added from our `fraud_transactions_pq` table.We use pure Python here, so no need to run this in a Spark interface.We'll assume you've already downloaded the training dataframe you generated in step 1 to a suitable location on your local machine, but you can just as easily load it from S3 using the `s3fs` library.<jupyter_code>import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
from scikitplot.metrics import plot_precision_recall, plot_confusion_matrix, plot_roc
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt

import mlflow
import pyarrow.parquet as pq
# Silence deprecation warnings from numpy and informational messages from mlflow
import warnings
import logging

warnings.filterwarnings("ignore", category=DeprecationWarning)
logger = logging.getLogger("mlflow")
logger.setLevel(logging.ERROR)<jupyter_output><empty_output><jupyter_text>We'll load the training dataframe we created from Tecton above<jupyter_code>df = pq.read_table('./data/fraud_dataset.parquet/').to_pandas()<jupyter_output><empty_output><jupyter_text>We'll log our model to mlflow (bundled with Databricks) to make it easier to deploy our model to production, but you can use any model registry you'd like.<jupyter_code># Track this experiment and save model in the Databricks-managed mlflow instance
import os
os.environ['MLFLOW_TRACKING_URI']='databricks'
mlflow.start_run(experiment_id='1299164929996601')
mlflow.autolog()
# We're going to drop the user_id and timestamp fields from our training dataframe since those aren't relevant to our model training
X = df.drop(['isfraud', 'user_id', 'timestamp'], axis=1)
y = df.isfraud
# Split our training dataframe into train and test dataframes
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
  ('imputer', SimpleImputer(fill_value=0)),
  ('scaler', StandardScaler()),
  ('clf', XGBClassifier(random_state=42, use_label_encoder=False))
])
# Here you can run your pipeline through a hyperparameter optimizer like hyperopt or GridSearchCV
pipe.fit(X_train, y_train)<jupyter_output>[15:06:59] WARNING: /Users/runner/miniforge3/conda-bld/xgboost-split_1614844528294/work/src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.<jupyter_text>ScoringWe'll score our model to see how well it predicts against the test set: data it hasn't seen but for which we still have the right answer. No surprises here: we do very well in correctly predicting ok transactions but not fraudulent ones. This might be due to a few reasons: ok transactions may look more similar to each other than fraudulent transactions and there are comparatively fewer fraudulent transactions in the training dataset (aka a *class imbalance* problem).<jupyter_code># y_test_hat are the true/false predictions for whether a transaction is fraudulent. y_test_hat_proba is the numerical probability
# which is used in some of the metrics below. (You can also use the predict_proba results to create your own true/false threshold)
y_test_hat = pipe.predict(X_test.to_numpy())
y_test_hat_proba = pipe.predict_proba(X_test.to_numpy())
print(classification_report(y_test, y_test_hat))
plot_precision_recall(y_test, y_test_hat_proba)
plt.savefig('./output/precision_recall.png')
mlflow.log_artifact('./output/precision_recall.png')
plot_roc(y_test, y_test_hat_proba)
plt.savefig('./output/roc.png')
mlflow.log_artifact('./output/roc.png')
mlflow.end_run()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07129277566539924, 'fraction_numerical': 0.012357414448669201, 'mean_word_length': 6.516071428571428, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '650069', 'license': 'MIT', 'n_tokens_mistral': 1291, 'n_tokens_neox': 1218, 'n_words': 460, 'path': 'fraud_model_end_to_end/3 - training.ipynb', 'repo_name': 'tecton-ai-ext/tecton-examples', 'size': '4208'}