Skip to content

Keras

Let's go through a simple example of integrating the Aporia SDK with a Keras model.

STEP 1: Add Model

Click the Add Model button in the Models page.

Add Model

Enter the model name and optionally a description. Click Next.

STEP 2: Initialize the Aporia SDK

First, we should initialize aporia and load a dataset to train the model.

import uuid

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.utils import to_categorical

import aporia
aporia.init(token='123', environment='example')

data = pd.read_csv("./path_to_real_file_with_data.csv")
features = data.drop(["will_buy_insurance"], axis=1)
labels = data[["will_buy_insurance"]]

STEP 3: Create Model Version

Next, we'll define a version for the new model:

aporia.create_model_version(
  model_id="my-model",
  model_version="v1",
  model_type="binary",
  features=aporia.pandas.infer_schema_from_dataframe(features),
  predictions=aporia.pandas.infer_schema_from_dataframe(labels)
)

STEP 4: Train Model

Now, let's train an Keras model, and log the training data:

model = tf.keras.Sequential([
    tf.keras.layers.Input(12),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Dense(30, activation='relu'),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Dropout(0.3),
    tf.keras.layers.Dense(2, activation='softmax')
])

model.compile(
    loss=tf.keras.losses.binary_crossentropy, 
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
)

y_nn_train = to_categorical(labels["will_buy_insurance"])
model.fit(X_train, y_nn_train, validation_split=0.1, epochs=23, batch_size=256, verbose=2)

apr_model = aporia.Model(model_id="my-model", model_version="v1")
apr_model.log_training_set(features=features, labels=labels)

STEP 5: Predict

The last step is to log the predictions performed by the model.

# pred_features is a DataFrame containing the features for the predictions
prediction = model.predict(pred_features)

apr_model = aporia.Model(model_id="my-model", model_version="v1")
apr_model.log_prediction(
  id=str(uuid.uuid4()),
  features=pandas_to_dict(pred_features),
  predictions={
    "will_buy_insurance": bool(np.argmax(prediction))
  }
)