The objective that we want to achieve is to establish the right playbooks that would help us in

Imports

import sys
import sagemaker
import boto3
import json
import pandas as pd
import numpy as np
import logging
import random
import argparse
import time
import os
import io

from sagemaker.session import Session
from sagemaker.feature_store.feature_group import FeatureGroup
from datetime import datetime
from sagemaker import get_execution_role
from sagemaker.spark.processing import PySparkProcessor
from argparse import Namespace, ArgumentParser


# to get the latest sagemaker python sdk
#!pip install -U sagemaker

Constants

NOTE: Before running this notebook, be sure to set the stack name in the first code cell to match the name of the CloudFormation stack you used to create this notebook instance. If you used the default stack name, you should not need to make any updates.

STACK_NAME = 'heidelberg-mlops-stack-3' # if you're not using the default stack name, replace this
%store STACK_NAME

STREAM_NAME='heidelberg-mlops-stream'
%store STREAM_NAME

APPLICATION_NAME='heidelberg-mlops-app'
%store APPLICATION_NAME

LOCAL_DIR='data'
%store LOCAL_DIR
Stored 'STACK_NAME' (str)
Stored 'STREAM_NAME' (str)
Stored 'APPLICATION_NAME' (str)
Stored 'LOCAL_DIR' (str)

Clients

role = get_execution_role()
sm = boto3.Session().client(service_name='sagemaker')
smfs_runtime = boto3.Session().client(service_name='sagemaker-featurestore-runtime')

boto_session = boto3.Session(region_name="us-east-1")
s3_client = boto3.Session().client('s3')
cf_client = boto3.client('cloudformation')
kinesis_client = boto3.client('kinesis')
lambda_client = boto3.client('lambda')
kda_client = boto3.client('kinesisanalytics')

Data

  1. Specify the Transformed data s3 location
  2. If you have run the data_preparation_notebook then do not change this othewise specify your s3_data location
s3_bucket = sagemaker.Session().default_bucket()
s3_prefix = 'heidelberg/data'

s3_transformed_data_filename = "transformed.csv"

s3_transformed_data_path="s3://{}/{}/{}".format(s3_bucket,s3_prefix,s3_transformed_data_filename)
print("Make sure trasformed data is present at : " ,s3_transformed_data_path)
Make sure trasformed data is present at :  s3://sagemaker-us-east-1-082830052325/heidelberg/data/transformed.csv

Setup

  1. Create feature groups
  2. Create an Amazon Kinesis data stream
  3. Create an Amazon Kinesis Data Applications (KDA) application

Get ARN's of Lambda functions from CloudFormation stack outputs

  1. InvokeFraudEndpointLambdaARN
  2. StreamingAggLambdaARN
try:
    outputs = cf_client.describe_stacks(StackName=STACK_NAME)['Stacks'][0]['Outputs']
    for o in outputs:
        if o['OutputKey'] == 'IngestLambdaFunctionARN':
            lambda_to_fs_arn = o['OutputValue']
        if o['OutputKey'] == 'PredictLambdaFunctionARN':
            lambda_to_model_arn = o['OutputValue']
        if o['OutputKey'] == 'PredictLambdaFunctionName':
            predict_lambda_name = o['OutputValue']

except:
    msg = f'CloudFormation stack {STACK_NAME} was not found. Please set the STACK_NAME properly and re-run this cell'
    sys.exit(ValueError(msg))
print(f'lambda_to_model_arn: {lambda_to_model_arn}')
print(f'lambda_to_fs_arn: {lambda_to_fs_arn}')
print(f'predict_lambda_name: {predict_lambda_name}')
lambda_to_model_arn: arn:aws:lambda:us-east-1:082830052325:function:HeidelbergInvokeFraudEndpointLambda3
lambda_to_fs_arn: arn:aws:lambda:us-east-1:082830052325:function:HeidelbergStreamingIngestAggFeatures3
predict_lambda_name: HeidelbergInvokeFraudEndpointLambda3
%store lambda_to_model_arn
%store predict_lambda_name
Stored 'lambda_to_model_arn' (str)
Stored 'predict_lambda_name' (str)

Create feature groups

When using Amazon SageMaker Feature Store, a core design decision is the definition of feature groups.

import datetime as dt
import dateutil.parser as parser


def create_feature_group_from_s3_input(s3_bucket, s3_prefix, s3_filename, fg_name, record_identifier_name, event_time_feature_name,role_arn=None, s3_uri=None):
    s3 = boto3.resource('s3')
    obj = s3.Object(s3_bucket, s3_prefix+'/'+s3_filename)
    body = obj.get()['Body'].read()
    data=pd.read_csv(io.BytesIO(body))
    del data['target']
    data = data.round(5)
    data=data.fillna(0)
    
    feature_store_session = Session(
    boto_session=boto_session,
    sagemaker_client=sm,
    sagemaker_featurestore_runtime_client=smfs_runtime
    )
    
    feature_group_name = fg_name
    feature_group = FeatureGroup(name=feature_group_name, sagemaker_session=feature_store_session)
    l=len(data)
    feature_group.load_feature_definitions(data_frame=data);
    
    s3_uri="s3://{}".format(s3_bucket)

    # specify record_identifier_name and event_time_feature_name
    feature_group.create(
        s3_uri=s3_uri,
        record_identifier_name=record_identifier_name,
        event_time_feature_name=event_time_feature_name,
        role_arn=role,
        enable_online_store=True
    )
fg_name = 'heidelberg-mlops-fg'
%store fg_name
Stored 'fg_name' (str)

Create feature groups(if not already Created)

create_feature_group_from_s3_input(s3_bucket,s3_prefix,s3_transformed_data_filename,fg_name,'id','event_time',role) 

Show that the feature store is aware of the new feature groups

sm.list_feature_groups()
{'FeatureGroupSummaries': [{'FeatureGroupName': 'transaction-feature-group-15-05-22-59',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/transaction-feature-group-15-05-22-59',
   'CreationTime': datetime.datetime(2020, 12, 15, 5, 23, 10, 113000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created',
   'OfflineStoreStatus': {'Status': 'Active'}},
  {'FeatureGroupName': 'ml-ops-2',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/ml-ops-2',
   'CreationTime': datetime.datetime(2020, 12, 19, 6, 49, 19, 335000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created'},
  {'FeatureGroupName': 'ml-ops-1',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/ml-ops-1',
   'CreationTime': datetime.datetime(2020, 12, 18, 7, 7, 15, 38000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created'},
  {'FeatureGroupName': 'identity-feature-group-15-05-22-59',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/identity-feature-group-15-05-22-59',
   'CreationTime': datetime.datetime(2020, 12, 15, 5, 23, 7, 513000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created',
   'OfflineStoreStatus': {'Status': 'Active'}},
  {'FeatureGroupName': 'heidelberg-mlops-fg-test1',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/heidelberg-mlops-fg-test1',
   'CreationTime': datetime.datetime(2020, 12, 30, 6, 41, 36, 615000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created'},
  {'FeatureGroupName': 'heidelberg-mlops-fg',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/heidelberg-mlops-fg',
   'CreationTime': datetime.datetime(2021, 1, 5, 17, 49, 57, 235000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Creating'},
  {'FeatureGroupName': 'heidelberg-fg-test2',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/heidelberg-fg-test2',
   'CreationTime': datetime.datetime(2020, 12, 29, 9, 18, 2, 298000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created'},
  {'FeatureGroupName': 'heidelberg-fg-test',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/heidelberg-fg-test',
   'CreationTime': datetime.datetime(2020, 12, 29, 8, 57, 48, 782000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created'},
  {'FeatureGroupName': 'demo-feature-group-2',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/demo-feature-group-2',
   'CreationTime': datetime.datetime(2020, 12, 29, 4, 56, 13, 540000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created'},
  {'FeatureGroupName': 'demo-feature-group',
   'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/demo-feature-group',
   'CreationTime': datetime.datetime(2020, 12, 28, 6, 17, 12, 601000, tzinfo=tzlocal()),
   'FeatureGroupStatus': 'Created'}],
 'NextToken': 'cIws2QhTXUIa8bi8XYNGwqMND6lavWZ6uZcw9539cUOD10M54amsd7l7yk4ucGW0YBYA+27e3qBpT0v/9eeXaZHI0OynQP0MGWxQIEMxEgPAFTlgHQc4BCc2dClH5/oyLuP4y3HU1Uc+hOt7PjxjfX85eToHqu60szYdvyQww5AIcHO98C+c6aArPfKWA9At4vupqSH+tFFjELqIHIc4VppahmW2c4V08+Ih3icbhVTdkJqtxW32ij3UaIEmXVj2ewAC85aPdqMp6PHmaua2EO6cdfewvaM4/TDk1kXkJblj4Un+QvQlTqL5q5HpO1LGfU5HIKxZNaoe3bC/szFmTTELP1QnIafcIPijnSvnTmHuytOw/Nk8pEhlABQ8yNBEQvy6Rh0cwxasIJdvzO/THM/8QwFTHXtTwp24StY+widOwWlh0SqGCdR/8UxYEFQEUZ3t4fi08RtBh8aQeWYadbd8IwJv6rLl4yUhEZM4KKxVoHI/B5Ge/Sg4Lf3Pq9wK3nS3QowfTbCLYj8CLs6tfvTfAQ==',
 'ResponseMetadata': {'RequestId': '369ebf64-ba06-4364-a38f-acb13ba54739',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '369ebf64-ba06-4364-a38f-acb13ba54739',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '2706',
   'date': 'Tue, 05 Jan 2021 17:49:59 GMT'},
  'RetryAttempts': 0}}

Describe each feature group

sm.describe_feature_group(FeatureGroupName=fg_name)
{'FeatureGroupArn': 'arn:aws:sagemaker:us-east-1:082830052325:feature-group/heidelberg-mlops-fg',
 'FeatureGroupName': 'heidelberg-mlops-fg',
 'RecordIdentifierFeatureName': 'id',
 'EventTimeFeatureName': 'event_time',
 'FeatureDefinitions': [{'FeatureName': 'kst_brutto',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'sm', 'FeatureType': 'Fractional'},
  {'FeatureName': 'tm', 'FeatureType': 'Fractional'},
  {'FeatureName': 'cl', 'FeatureType': 'Fractional'},
  {'FeatureName': 'so3', 'FeatureType': 'Fractional'},
  {'FeatureName': 'k2o', 'FeatureType': 'Fractional'},
  {'FeatureName': 'na2o', 'FeatureType': 'Fractional'},
  {'FeatureName': 'south_kiln_feed_01om886__tph__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'south_kiln_feed_01om886__tph__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'north_kiln_feed_01om885__tph__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'north_kiln_feed_01om885__tph__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'north_fan_speed_01oa943__rpm__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'north_fan_speed_01oa943__rpm__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'south_fan_speed_02oa943__rpm__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'south_fan_speed_02oa943__rpm__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'lignite_main_burner_03sk820__tph__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'lignite_main_burner_03sk820__tph__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'bpg_main_burner_03bf810__tph__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'bpg_main_burner_03bf810__tph__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'lignite_calciner_02sk820__tph__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'lignite_calciner_02sk820__tph__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'bpg_calciner_02bf810__tph__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'bpg_calciner_02bf810__tph__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kbs_calciner_00kb950__tph__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kbs_calciner_00kb950__tph__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_main_burner__gj_h__avg_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_main_burner__gj_h__max_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_main_burner__gj_h__avg_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_main_burner__gj_h__max_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_main_burner__gj_h__avg_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_main_burner__gj_h__max_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_main_burner__gj_h__avg_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_main_burner__gj_h__max_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_calciner__gj_h__avg_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_calciner__gj_h__max_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_calciner__gj_h__avg_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_calciner__gj_h__max_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_calciner__gj_h__avg_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_calciner__gj_h__max_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_calciner__gj_h__avg_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_to_calciner__gj_h__max_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tf__traditional_fuel__avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'tf__traditional_fuel__max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'af__alternative_fuel__avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'af__alternative_fuel__max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'shc__gj__t_kiln_feed__avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'shc__gj__t_kiln_feed__max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'nox_concentration_in_kiln_inlet_00oa983__ppm__avg_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'nox_concentration_in_kiln_inlet_00oa983__ppm__max_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'nox_concentration_in_kiln_inlet_00oa983__ppm__avg_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'nox_concentration_in_kiln_inlet_00oa983__ppm__max_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'nox_concentration_in_kiln_inlet_00oa983__ppm__avg_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'nox_concentration_in_kiln_inlet_00oa983__ppm__max_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'nox_concentration_in_kiln_inlet_00oa983__ppm__avg_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'nox_concentration_in_kiln_inlet_00oa983__ppm__max_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'co_concentration_in_kiln_inlet_00oa981__ppm__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'co_concentration_in_kiln_inlet_00oa981__ppm__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_concentration_in_kiln_inlet_00oa982_____avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_concentration_in_kiln_inlet_00oa982_____max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'bottom_cyclone_gas_temperature_00oa800___c___avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'bottom_cyclone_gas_temperature_00oa800___c___max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'secondary_air_temperature_01kk827___c___avg_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'secondary_air_temperature_01kk827___c___max_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'secondary_air_temperature_01kk827___c___avg_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'secondary_air_temperature_01kk827___c___max_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'secondary_air_temperature_01kk827___c___avg_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'secondary_air_temperature_01kk827___c___max_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'secondary_air_temperature_01kk827___c___avg_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'secondary_air_temperature_01kk827___c___max_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tertiary_air_temperature_01kb801___c___avg_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tertiary_air_temperature_01kb801___c___max_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tertiary_air_temperature_01kb801___c___avg_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tertiary_air_temperature_01kb801___c___max_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tertiary_air_temperature_01kb801___c___avg_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tertiary_air_temperature_01kb801___c___max_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tertiary_air_temperature_01kb801___c___avg_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'tertiary_air_temperature_01kb801___c___max_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_amps_01do812__amps__avg_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_amps_01do812__amps__max_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_amps_01do812__amps__avg_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_amps_01do812__amps__max_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_amps_01do812__amps__avg_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_amps_01do812__amps__max_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_amps_01do812__amps__avg_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_amps_01do812__amps__max_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'co_bottom_cyclone_north_00oa941__amps__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'co_bottom_cyclone_north_00oa941__amps__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_bottom_cyclone_north_00oa942_____avg_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_bottom_cyclone_north_00oa942_____max_0',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_bottom_cyclone_north_00oa942_____avg_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_bottom_cyclone_north_00oa942_____max_1',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_bottom_cyclone_north_00oa942_____avg_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_bottom_cyclone_north_00oa942_____max_2',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_bottom_cyclone_north_00oa942_____avg_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'o2_bottom_cyclone_north_00oa942_____max_3',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_speed_01do811__rpm__avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_speed_01do811__rpm__max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'primary_air_amount_01of850__nm3_h___avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'primary_air_amount_01of850__nm3_h___max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'axial_air_pressure_01of811__mbar__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'axial_air_pressure_01of811__mbar__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'radial_air_pressure_01of812__mbar__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'radial_air_pressure_01of812__mbar__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'central_air_pressure_01of813__mbar__avg',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'central_air_pressure_01of813__mbar__max',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'total_feed_avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'total_feed_max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'total_energy_max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'average_fan_speed_avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'average_fan_speed_max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'average_air_temperature_avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'average_air_temperature_max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_feed_rate_avg', 'FeatureType': 'Fractional'},
  {'FeatureName': 'kiln_feed_rate_max', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_c3s_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_mgo_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_fe2o3_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_al2o3_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_na2o_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_k2o_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_cao_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_sio2_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'heat_of_formation__kcal_kg_clinker__lag_shift',
   'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_so3_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_sm_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_am_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'klinker___nk_lsf_lag_shift', 'FeatureType': 'Fractional'},
  {'FeatureName': 'id', 'FeatureType': 'Fractional'},
  {'FeatureName': 'event_time', 'FeatureType': 'Fractional'}],
 'CreationTime': datetime.datetime(2021, 1, 5, 17, 49, 57, 235000, tzinfo=tzlocal()),
 'OnlineStoreConfig': {'EnableOnlineStore': True},
 'OfflineStoreConfig': {'S3StorageConfig': {'S3Uri': 's3://sagemaker-us-east-1-082830052325'},
  'DisableGlueTableCreation': False},
 'RoleArn': 'arn:aws:iam::082830052325:role/MySagemakerRoleHeidelberg3',
 'FeatureGroupStatus': 'Creating',
 'ResponseMetadata': {'RequestId': '22bc1c77-b973-49c7-a574-debd2aa3ffb8',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '22bc1c77-b973-49c7-a574-debd2aa3ffb8',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '11260',
   'date': 'Tue, 05 Jan 2021 17:50:01 GMT'},
  'RetryAttempts': 0}}

Create an Amazon Kinesis Data Stream

kinesis_client.create_stream(StreamName=STREAM_NAME, ShardCount=1)
{'ResponseMetadata': {'RequestId': 'eb540470-5ef8-75f8-b33a-ad63000d5a46',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': 'eb540470-5ef8-75f8-b33a-ad63000d5a46',
   'x-amz-id-2': '1aiJ/8+8IRwrKGfUkHHq76P5bGilrC/E/1H2debFOePX6SzYGUx6ZtxUDNb2VhE5GyNx8j4xOI1P5F1eYnSIGhPI9iJZcD0+',
   'date': 'Tue, 5 Jan 2021 17:50:11 GMT',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '0'},
  'RetryAttempts': 0}}
kinesis_client.list_streams()
{'StreamNames': ['Django-internal-error',
  'Foo',
  'cloudcrm-vdr-test',
  'cloudcrm_pivotal_kinesis_stream',
  'cn-support-vision-1-article-stream',
  'cn-support-vision-1-domain-stream',
  'cn-support-vision-2-dev-Stream',
  'csv-kba-summary',
  'heidelberg-mlops-stream',
  'model-stream',
  'real-time-analysis',
  'sococo-video-insights-stream',
  'solarwind-2-logs-stream',
  'test-data-stream',
  'topbox_ingestion_stream',
  'tu2k20_ashish.gupta1_kinesis',
  'tu2k20_shivangchopra11',
  'vdr-eventstream',
  'viswak-tu2k20'],
 'HasMoreStreams': False,
 'ResponseMetadata': {'RequestId': 'e5761aba-a456-6a2f-bd18-b3affaa34591',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': 'e5761aba-a456-6a2f-bd18-b3affaa34591',
   'x-amz-id-2': 'KRaSoOl3qWuLe5kBwOTVAe8xgoI8Opl5Rowgy4Z77+4iE1R0N3C9Rn3alXqYoGqMNgj3qX1ra8mKu4RVzbHLN2BmJjK35P/8',
   'date': 'Tue, 5 Jan 2021 17:50:13 GMT',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '502'},
  'RetryAttempts': 0}}
kinesis_client.describe_stream(StreamName=STREAM_NAME)
{'StreamDescription': {'StreamName': 'heidelberg-mlops-stream',
  'StreamARN': 'arn:aws:kinesis:us-east-1:082830052325:stream/heidelberg-mlops-stream',
  'StreamStatus': 'CREATING',
  'Shards': [],
  'HasMoreShards': False,
  'RetentionPeriodHours': 24,
  'StreamCreationTimestamp': datetime.datetime(2021, 1, 5, 17, 50, 10, tzinfo=tzlocal()),
  'EnhancedMonitoring': [{'ShardLevelMetrics': []}],
  'EncryptionType': 'NONE'},
 'ResponseMetadata': {'RequestId': 'd70a0a13-2cea-0a49-8f64-a305721f25f7',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': 'd70a0a13-2cea-0a49-8f64-a305721f25f7',
   'x-amz-id-2': '2wHUeiUHaRjrgMJWgiaE+1mFf753aalkJwhrL2yP7djOHoEPJ30owbKhgXB+FdLymwwxupJumKkb9KLfBbRWW2Us8OQiBkjK',
   'date': 'Tue, 5 Jan 2021 17:50:14 GMT',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '343'},
  'RetryAttempts': 0}}
import time
active_stream = False
while not active_stream:
    status = kinesis_client.describe_stream(StreamName=STREAM_NAME)['StreamDescription']['StreamStatus']
    if (status == 'CREATING'):
        print('Waiting for the Kinesis stream to become active...')
        time.sleep(20)  
    elif (status == 'ACTIVE'): 
        active_stream = True
        print('ACTIVE')
Waiting for the Kinesis stream to become active...
ACTIVE
stream_arn = kinesis_client.describe_stream(StreamName=STREAM_NAME)['StreamDescription']['StreamARN']
stream_arn
'arn:aws:kinesis:us-east-1:082830052325:stream/heidelberg-mlops-stream'

Map the Kinesis stream as an event source for Lambda Model detection

lambda_client.create_event_source_mapping(EventSourceArn=stream_arn,
                                          FunctionName=lambda_to_model_arn,
                                          StartingPosition='LATEST',
                                          Enabled=True,
                                          MaximumRecordAgeInSeconds=60*10
                                          ) 
#DestinationConfig would handle discarded records
# write your lambda name here
{'ResponseMetadata': {'RequestId': 'fb8d00e7-65e8-4433-90da-1b3d1bed683a',
  'HTTPStatusCode': 202,
  'HTTPHeaders': {'date': 'Tue, 05 Jan 2021 17:50:44 GMT',
   'content-type': 'application/json',
   'content-length': '821',
   'connection': 'keep-alive',
   'x-amzn-requestid': 'fb8d00e7-65e8-4433-90da-1b3d1bed683a'},
  'RetryAttempts': 0},
 'UUID': '9974f2db-2d9a-4081-9e31-7cbb227ca548',
 'StartingPosition': 'LATEST',
 'BatchSize': 100,
 'MaximumBatchingWindowInSeconds': 0,
 'ParallelizationFactor': 1,
 'EventSourceArn': 'arn:aws:kinesis:us-east-1:082830052325:stream/heidelberg-mlops-stream',
 'FunctionArn': 'arn:aws:lambda:us-east-1:082830052325:function:HeidelbergInvokeFraudEndpointLambda3',
 'LastModified': datetime.datetime(2021, 1, 5, 17, 50, 44, 109000, tzinfo=tzlocal()),
 'LastProcessingResult': 'No records processed',
 'State': 'Creating',
 'StateTransitionReason': 'User action',
 'DestinationConfig': {'OnFailure': {}},
 'MaximumRecordAgeInSeconds': 600,
 'BisectBatchOnFunctionError': False,
 'MaximumRetryAttempts': -1}

Create an Amazon Kinesis Data Applications (KDA) application

#                 '"cc_num"              BIGINT,\n' + \
#                 '"num_trans_last_10m"  SMALLINT,\n' + \
#                 '"avg_amt_last_10m"    REAL\n);\n\n' + \
#             'CREATE OR REPLACE PUMP "STREAM_PUMP" AS\n' + \
#             'INSERT INTO "DESTINATION_SQL_STREAM"\n' + \
#                 'SELECT STREAM "cc_num", \n' + \
#                     'COUNT(*) OVER LAST_10_MINUTES, \n' + \
#                     'AVG("amount") OVER LAST_10_MINUTES\n' + \
#                     'FROM "SOURCE_SQL_STREAM_001"\n' + \
#                     'WINDOW LAST_10_MINUTES AS (\n' + \
#                         'PARTITION BY "cc_num"\n' + \
#                         'RANGE INTERVAL \'10\' MINUTE PRECEDING);\n'
# print(sql_code_example)



# sql_code = ""  # Store features from stream to featurestore
CREATE OR REPLACE STREAM "DESTINATION_SQL_STREAM" (
"cc_num"              BIGINT,
"num_trans_last_10m"  SMALLINT,
"avg_amt_last_10m"    REAL
);

CREATE OR REPLACE PUMP "STREAM_PUMP" AS
INSERT INTO "DESTINATION_SQL_STREAM"
SELECT STREAM "cc_num", 
COUNT(*) OVER LAST_10_MINUTES, 
AVG("amount") OVER LAST_10_MINUTES
FROM "SOURCE_SQL_STREAM_001"
WINDOW LAST_10_MINUTES AS (
PARTITION BY "cc_num"
RANGE INTERVAL '10' MINUTE PRECEDING);

Application Code (SQL QUERY) For KDA

def get_features():
    s3 = boto3.resource('s3')
    obj = s3.Object(s3_bucket, s3_prefix+'/'+s3_transformed_data_filename)
    body = obj.get()['Body'].read()
    data=pd.read_csv(io.BytesIO(body))
    del data['target']
    data = data.round(5)
    data=data.fillna(0)
    return list(data)

features = get_features()
def get_sql_code():
    s = 'CREATE OR REPLACE STREAM "DESTINATION_SQL_STREAM" (\n'
    for index,i in enumerate(features):
        if index!= len(features)-1:
            s+='"'+i+'"'+"      REAL,\n"
        else:
            s+='"'+i+'"'+"      REAL\n"
            
    s+='); \n\n'

    s+='CREATE OR REPLACE PUMP "STREAM_PUMP" AS\n INSERT INTO "DESTINATION_SQL_STREAM"\n'
    s+='SELECT STREAM '
    for index,i in enumerate(features):
        if index!= len(features)-1:
            s+='"'+i+'", \n'
        else:
            s+='"'+i+'" \n'
    s+='FROM "SOURCE_SQL_STREAM_001"\n'
    s+='WINDOW LAST_10_MINUTES AS (\n' + \
            'PARTITION BY "id"\n' + \
            'RANGE INTERVAL \'10\' MINUTE PRECEDING);\n'
    return s;

sql_code=get_sql_code()
print(sql_code)
CREATE OR REPLACE STREAM "DESTINATION_SQL_STREAM" (
"kst_brutto"      REAL,
"sm"      REAL,
"tm"      REAL,
"cl"      REAL,
"so3"      REAL,
"k2o"      REAL,
"na2o"      REAL,
"south_kiln_feed_01om886__tph__avg"      REAL,
"south_kiln_feed_01om886__tph__max"      REAL,
"north_kiln_feed_01om885__tph__avg"      REAL,
"north_kiln_feed_01om885__tph__max"      REAL,
"north_fan_speed_01oa943__rpm__avg"      REAL,
"north_fan_speed_01oa943__rpm__max"      REAL,
"south_fan_speed_02oa943__rpm__avg"      REAL,
"south_fan_speed_02oa943__rpm__max"      REAL,
"lignite_main_burner_03sk820__tph__avg"      REAL,
"lignite_main_burner_03sk820__tph__max"      REAL,
"bpg_main_burner_03bf810__tph__avg"      REAL,
"bpg_main_burner_03bf810__tph__max"      REAL,
"lignite_calciner_02sk820__tph__avg"      REAL,
"lignite_calciner_02sk820__tph__max"      REAL,
"bpg_calciner_02bf810__tph__avg"      REAL,
"bpg_calciner_02bf810__tph__max"      REAL,
"kbs_calciner_00kb950__tph__avg"      REAL,
"kbs_calciner_00kb950__tph__max"      REAL,
"total_energy_to_main_burner__gj_h__avg_0"      REAL,
"total_energy_to_main_burner__gj_h__max_0"      REAL,
"total_energy_to_main_burner__gj_h__avg_1"      REAL,
"total_energy_to_main_burner__gj_h__max_1"      REAL,
"total_energy_to_main_burner__gj_h__avg_2"      REAL,
"total_energy_to_main_burner__gj_h__max_2"      REAL,
"total_energy_to_main_burner__gj_h__avg_3"      REAL,
"total_energy_to_main_burner__gj_h__max_3"      REAL,
"total_energy_to_calciner__gj_h__avg_0"      REAL,
"total_energy_to_calciner__gj_h__max_0"      REAL,
"total_energy_to_calciner__gj_h__avg_1"      REAL,
"total_energy_to_calciner__gj_h__max_1"      REAL,
"total_energy_to_calciner__gj_h__avg_2"      REAL,
"total_energy_to_calciner__gj_h__max_2"      REAL,
"total_energy_to_calciner__gj_h__avg_3"      REAL,
"total_energy_to_calciner__gj_h__max_3"      REAL,
"tf__traditional_fuel__avg"      REAL,
"tf__traditional_fuel__max"      REAL,
"af__alternative_fuel__avg"      REAL,
"af__alternative_fuel__max"      REAL,
"shc__gj__t_kiln_feed__avg"      REAL,
"shc__gj__t_kiln_feed__max"      REAL,
"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_0"      REAL,
"nox_concentration_in_kiln_inlet_00oa983__ppm__max_0"      REAL,
"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_1"      REAL,
"nox_concentration_in_kiln_inlet_00oa983__ppm__max_1"      REAL,
"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_2"      REAL,
"nox_concentration_in_kiln_inlet_00oa983__ppm__max_2"      REAL,
"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_3"      REAL,
"nox_concentration_in_kiln_inlet_00oa983__ppm__max_3"      REAL,
"co_concentration_in_kiln_inlet_00oa981__ppm__avg"      REAL,
"co_concentration_in_kiln_inlet_00oa981__ppm__max"      REAL,
"o2_concentration_in_kiln_inlet_00oa982_____avg"      REAL,
"o2_concentration_in_kiln_inlet_00oa982_____max"      REAL,
"bottom_cyclone_gas_temperature_00oa800___c___avg"      REAL,
"bottom_cyclone_gas_temperature_00oa800___c___max"      REAL,
"secondary_air_temperature_01kk827___c___avg_0"      REAL,
"secondary_air_temperature_01kk827___c___max_0"      REAL,
"secondary_air_temperature_01kk827___c___avg_1"      REAL,
"secondary_air_temperature_01kk827___c___max_1"      REAL,
"secondary_air_temperature_01kk827___c___avg_2"      REAL,
"secondary_air_temperature_01kk827___c___max_2"      REAL,
"secondary_air_temperature_01kk827___c___avg_3"      REAL,
"secondary_air_temperature_01kk827___c___max_3"      REAL,
"tertiary_air_temperature_01kb801___c___avg_0"      REAL,
"tertiary_air_temperature_01kb801___c___max_0"      REAL,
"tertiary_air_temperature_01kb801___c___avg_1"      REAL,
"tertiary_air_temperature_01kb801___c___max_1"      REAL,
"tertiary_air_temperature_01kb801___c___avg_2"      REAL,
"tertiary_air_temperature_01kb801___c___max_2"      REAL,
"tertiary_air_temperature_01kb801___c___avg_3"      REAL,
"tertiary_air_temperature_01kb801___c___max_3"      REAL,
"kiln_amps_01do812__amps__avg_0"      REAL,
"kiln_amps_01do812__amps__max_0"      REAL,
"kiln_amps_01do812__amps__avg_1"      REAL,
"kiln_amps_01do812__amps__max_1"      REAL,
"kiln_amps_01do812__amps__avg_2"      REAL,
"kiln_amps_01do812__amps__max_2"      REAL,
"kiln_amps_01do812__amps__avg_3"      REAL,
"kiln_amps_01do812__amps__max_3"      REAL,
"co_bottom_cyclone_north_00oa941__amps__avg"      REAL,
"co_bottom_cyclone_north_00oa941__amps__max"      REAL,
"o2_bottom_cyclone_north_00oa942_____avg_0"      REAL,
"o2_bottom_cyclone_north_00oa942_____max_0"      REAL,
"o2_bottom_cyclone_north_00oa942_____avg_1"      REAL,
"o2_bottom_cyclone_north_00oa942_____max_1"      REAL,
"o2_bottom_cyclone_north_00oa942_____avg_2"      REAL,
"o2_bottom_cyclone_north_00oa942_____max_2"      REAL,
"o2_bottom_cyclone_north_00oa942_____avg_3"      REAL,
"o2_bottom_cyclone_north_00oa942_____max_3"      REAL,
"kiln_speed_01do811__rpm__avg"      REAL,
"kiln_speed_01do811__rpm__max"      REAL,
"primary_air_amount_01of850__nm3_h___avg"      REAL,
"primary_air_amount_01of850__nm3_h___max"      REAL,
"axial_air_pressure_01of811__mbar__avg"      REAL,
"axial_air_pressure_01of811__mbar__max"      REAL,
"radial_air_pressure_01of812__mbar__avg"      REAL,
"radial_air_pressure_01of812__mbar__max"      REAL,
"central_air_pressure_01of813__mbar__avg"      REAL,
"central_air_pressure_01of813__mbar__max"      REAL,
"total_feed_avg"      REAL,
"total_feed_max"      REAL,
"total_energy_avg"      REAL,
"total_energy_max"      REAL,
"average_fan_speed_avg"      REAL,
"average_fan_speed_max"      REAL,
"average_air_temperature_avg"      REAL,
"average_air_temperature_max"      REAL,
"kiln_feed_rate_avg"      REAL,
"kiln_feed_rate_max"      REAL,
"klinker___nk_c3s_lag_shift"      REAL,
"klinker___nk_mgo_lag_shift"      REAL,
"klinker___nk_fe2o3_lag_shift"      REAL,
"klinker___nk_al2o3_lag_shift"      REAL,
"klinker___nk_na2o_lag_shift"      REAL,
"klinker___nk_k2o_lag_shift"      REAL,
"klinker___nk_cao_lag_shift"      REAL,
"klinker___nk_sio2_lag_shift"      REAL,
"heat_of_formation__kcal_kg_clinker__lag_shift"      REAL,
"klinker___nk_so3_lag_shift"      REAL,
"klinker___nk_sm_lag_shift"      REAL,
"klinker___nk_am_lag_shift"      REAL,
"klinker___nk_lsf_lag_shift"      REAL,
"id"      REAL,
"event_time"      REAL
); 

CREATE OR REPLACE PUMP "STREAM_PUMP" AS
 INSERT INTO "DESTINATION_SQL_STREAM"
SELECT STREAM "kst_brutto", 
"sm", 
"tm", 
"cl", 
"so3", 
"k2o", 
"na2o", 
"south_kiln_feed_01om886__tph__avg", 
"south_kiln_feed_01om886__tph__max", 
"north_kiln_feed_01om885__tph__avg", 
"north_kiln_feed_01om885__tph__max", 
"north_fan_speed_01oa943__rpm__avg", 
"north_fan_speed_01oa943__rpm__max", 
"south_fan_speed_02oa943__rpm__avg", 
"south_fan_speed_02oa943__rpm__max", 
"lignite_main_burner_03sk820__tph__avg", 
"lignite_main_burner_03sk820__tph__max", 
"bpg_main_burner_03bf810__tph__avg", 
"bpg_main_burner_03bf810__tph__max", 
"lignite_calciner_02sk820__tph__avg", 
"lignite_calciner_02sk820__tph__max", 
"bpg_calciner_02bf810__tph__avg", 
"bpg_calciner_02bf810__tph__max", 
"kbs_calciner_00kb950__tph__avg", 
"kbs_calciner_00kb950__tph__max", 
"total_energy_to_main_burner__gj_h__avg_0", 
"total_energy_to_main_burner__gj_h__max_0", 
"total_energy_to_main_burner__gj_h__avg_1", 
"total_energy_to_main_burner__gj_h__max_1", 
"total_energy_to_main_burner__gj_h__avg_2", 
"total_energy_to_main_burner__gj_h__max_2", 
"total_energy_to_main_burner__gj_h__avg_3", 
"total_energy_to_main_burner__gj_h__max_3", 
"total_energy_to_calciner__gj_h__avg_0", 
"total_energy_to_calciner__gj_h__max_0", 
"total_energy_to_calciner__gj_h__avg_1", 
"total_energy_to_calciner__gj_h__max_1", 
"total_energy_to_calciner__gj_h__avg_2", 
"total_energy_to_calciner__gj_h__max_2", 
"total_energy_to_calciner__gj_h__avg_3", 
"total_energy_to_calciner__gj_h__max_3", 
"tf__traditional_fuel__avg", 
"tf__traditional_fuel__max", 
"af__alternative_fuel__avg", 
"af__alternative_fuel__max", 
"shc__gj__t_kiln_feed__avg", 
"shc__gj__t_kiln_feed__max", 
"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_0", 
"nox_concentration_in_kiln_inlet_00oa983__ppm__max_0", 
"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_1", 
"nox_concentration_in_kiln_inlet_00oa983__ppm__max_1", 
"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_2", 
"nox_concentration_in_kiln_inlet_00oa983__ppm__max_2", 
"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_3", 
"nox_concentration_in_kiln_inlet_00oa983__ppm__max_3", 
"co_concentration_in_kiln_inlet_00oa981__ppm__avg", 
"co_concentration_in_kiln_inlet_00oa981__ppm__max", 
"o2_concentration_in_kiln_inlet_00oa982_____avg", 
"o2_concentration_in_kiln_inlet_00oa982_____max", 
"bottom_cyclone_gas_temperature_00oa800___c___avg", 
"bottom_cyclone_gas_temperature_00oa800___c___max", 
"secondary_air_temperature_01kk827___c___avg_0", 
"secondary_air_temperature_01kk827___c___max_0", 
"secondary_air_temperature_01kk827___c___avg_1", 
"secondary_air_temperature_01kk827___c___max_1", 
"secondary_air_temperature_01kk827___c___avg_2", 
"secondary_air_temperature_01kk827___c___max_2", 
"secondary_air_temperature_01kk827___c___avg_3", 
"secondary_air_temperature_01kk827___c___max_3", 
"tertiary_air_temperature_01kb801___c___avg_0", 
"tertiary_air_temperature_01kb801___c___max_0", 
"tertiary_air_temperature_01kb801___c___avg_1", 
"tertiary_air_temperature_01kb801___c___max_1", 
"tertiary_air_temperature_01kb801___c___avg_2", 
"tertiary_air_temperature_01kb801___c___max_2", 
"tertiary_air_temperature_01kb801___c___avg_3", 
"tertiary_air_temperature_01kb801___c___max_3", 
"kiln_amps_01do812__amps__avg_0", 
"kiln_amps_01do812__amps__max_0", 
"kiln_amps_01do812__amps__avg_1", 
"kiln_amps_01do812__amps__max_1", 
"kiln_amps_01do812__amps__avg_2", 
"kiln_amps_01do812__amps__max_2", 
"kiln_amps_01do812__amps__avg_3", 
"kiln_amps_01do812__amps__max_3", 
"co_bottom_cyclone_north_00oa941__amps__avg", 
"co_bottom_cyclone_north_00oa941__amps__max", 
"o2_bottom_cyclone_north_00oa942_____avg_0", 
"o2_bottom_cyclone_north_00oa942_____max_0", 
"o2_bottom_cyclone_north_00oa942_____avg_1", 
"o2_bottom_cyclone_north_00oa942_____max_1", 
"o2_bottom_cyclone_north_00oa942_____avg_2", 
"o2_bottom_cyclone_north_00oa942_____max_2", 
"o2_bottom_cyclone_north_00oa942_____avg_3", 
"o2_bottom_cyclone_north_00oa942_____max_3", 
"kiln_speed_01do811__rpm__avg", 
"kiln_speed_01do811__rpm__max", 
"primary_air_amount_01of850__nm3_h___avg", 
"primary_air_amount_01of850__nm3_h___max", 
"axial_air_pressure_01of811__mbar__avg", 
"axial_air_pressure_01of811__mbar__max", 
"radial_air_pressure_01of812__mbar__avg", 
"radial_air_pressure_01of812__mbar__max", 
"central_air_pressure_01of813__mbar__avg", 
"central_air_pressure_01of813__mbar__max", 
"total_feed_avg", 
"total_feed_max", 
"total_energy_avg", 
"total_energy_max", 
"average_fan_speed_avg", 
"average_fan_speed_max", 
"average_air_temperature_avg", 
"average_air_temperature_max", 
"kiln_feed_rate_avg", 
"kiln_feed_rate_max", 
"klinker___nk_c3s_lag_shift", 
"klinker___nk_mgo_lag_shift", 
"klinker___nk_fe2o3_lag_shift", 
"klinker___nk_al2o3_lag_shift", 
"klinker___nk_na2o_lag_shift", 
"klinker___nk_k2o_lag_shift", 
"klinker___nk_cao_lag_shift", 
"klinker___nk_sio2_lag_shift", 
"heat_of_formation__kcal_kg_clinker__lag_shift", 
"klinker___nk_so3_lag_shift", 
"klinker___nk_sm_lag_shift", 
"klinker___nk_am_lag_shift", 
"klinker___nk_lsf_lag_shift", 
"id", 
"event_time" 
FROM "SOURCE_SQL_STREAM_001"
WINDOW LAST_10_MINUTES AS (
PARTITION BY "id"
RANGE INTERVAL '10' MINUTE PRECEDING);

def get_record_columns():
    s3 = boto3.resource('s3')
    obj = s3.Object(s3_bucket, s3_prefix+'/'+s3_transformed_data_filename)
    body = obj.get()['Body'].read()
    data=pd.read_csv(io.BytesIO(body))
    data = data.round(5)
    columns = list(data)
    record_columns = []
    for column in columns:
        if column!='target':
            temp = {'Name': column,  'Mapping': '$.'+column,   'SqlType': 'REAL'}
            record_columns.append(temp)
    return record_columns
record_columns  = get_record_columns()
kda_inputs = [{
                'NamePrefix': 'SOURCE_SQL_STREAM',
                'KinesisStreamsInput': {
                       'ResourceARN': stream_arn,
                       'RoleARN': role
                },
                'InputSchema': {
                      'RecordFormat': {
                          'RecordFormatType': 'JSON',
                          'MappingParameters': {
                              'JSONMappingParameters': {
                                  'RecordRowPath': '$'
                              }
                          },
                      },
                      'RecordEncoding': 'UTF-8',
                      'RecordColumns': record_columns
                }
              }                         
             ]

Create Kinesis Data Analytics Application

We first lookup Lambda ARNs from CloudFormation output, then create a Kinesis Data Analytics application that connects its output to the Streaming Lambda. This Lambda will ingest the records and write them to the SageMaker Feature Group.

kda_outputs = [{'LambdaOutput': {'ResourceARN': lambda_to_fs_arn, 'RoleARN': role},
                'Name': 'DESTINATION_SQL_STREAM',
                'DestinationSchema': {'RecordFormatType': 'JSON'}}]
kda_outputs
[{'LambdaOutput': {'ResourceARN': 'arn:aws:lambda:us-east-1:082830052325:function:HeidelbergStreamingIngestAggFeatures3',
   'RoleARN': 'arn:aws:iam::082830052325:role/MySagemakerRoleHeidelberg3'},
  'Name': 'DESTINATION_SQL_STREAM',
  'DestinationSchema': {'RecordFormatType': 'JSON'}}]
kda_client.create_application(ApplicationName=APPLICATION_NAME, 
                              Inputs=kda_inputs,
                              Outputs=kda_outputs,
                              ApplicationCode=sql_code)
{'ApplicationSummary': {'ApplicationName': 'heidelberg-mlops-app',
  'ApplicationARN': 'arn:aws:kinesisanalytics:us-east-1:082830052325:application/heidelberg-mlops-app',
  'ApplicationStatus': 'READY'},
 'ResponseMetadata': {'RequestId': 'd2eb591b-650e-4c3a-acb7-737c98783b23',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': 'd2eb591b-650e-4c3a-acb7-737c98783b23',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '193',
   'date': 'Tue, 05 Jan 2021 17:51:13 GMT'},
  'RetryAttempts': 0}}
kda_client.describe_application(ApplicationName=APPLICATION_NAME)
{'ApplicationDetail': {'ApplicationName': 'heidelberg-mlops-app',
  'ApplicationARN': 'arn:aws:kinesisanalytics:us-east-1:082830052325:application/heidelberg-mlops-app',
  'ApplicationStatus': 'READY',
  'CreateTimestamp': datetime.datetime(2021, 1, 5, 17, 51, 14, tzinfo=tzlocal()),
  'LastUpdateTimestamp': datetime.datetime(2021, 1, 5, 17, 51, 14, tzinfo=tzlocal()),
  'InputDescriptions': [{'InputId': '1.1',
    'NamePrefix': 'SOURCE_SQL_STREAM',
    'InAppStreamNames': ['SOURCE_SQL_STREAM_001'],
    'KinesisStreamsInputDescription': {'ResourceARN': 'arn:aws:kinesis:us-east-1:082830052325:stream/heidelberg-mlops-stream',
     'RoleARN': 'arn:aws:iam::082830052325:role/MySagemakerRoleHeidelberg3'},
    'InputSchema': {'RecordFormat': {'RecordFormatType': 'JSON',
      'MappingParameters': {'JSONMappingParameters': {'RecordRowPath': '$'}}},
     'RecordEncoding': 'UTF-8',
     'RecordColumns': [{'Name': 'kst_brutto',
       'Mapping': '$.kst_brutto',
       'SqlType': 'REAL'},
      {'Name': 'sm', 'Mapping': '$.sm', 'SqlType': 'REAL'},
      {'Name': 'tm', 'Mapping': '$.tm', 'SqlType': 'REAL'},
      {'Name': 'cl', 'Mapping': '$.cl', 'SqlType': 'REAL'},
      {'Name': 'so3', 'Mapping': '$.so3', 'SqlType': 'REAL'},
      {'Name': 'k2o', 'Mapping': '$.k2o', 'SqlType': 'REAL'},
      {'Name': 'na2o', 'Mapping': '$.na2o', 'SqlType': 'REAL'},
      {'Name': 'south_kiln_feed_01om886__tph__avg',
       'Mapping': '$.south_kiln_feed_01om886__tph__avg',
       'SqlType': 'REAL'},
      {'Name': 'south_kiln_feed_01om886__tph__max',
       'Mapping': '$.south_kiln_feed_01om886__tph__max',
       'SqlType': 'REAL'},
      {'Name': 'north_kiln_feed_01om885__tph__avg',
       'Mapping': '$.north_kiln_feed_01om885__tph__avg',
       'SqlType': 'REAL'},
      {'Name': 'north_kiln_feed_01om885__tph__max',
       'Mapping': '$.north_kiln_feed_01om885__tph__max',
       'SqlType': 'REAL'},
      {'Name': 'north_fan_speed_01oa943__rpm__avg',
       'Mapping': '$.north_fan_speed_01oa943__rpm__avg',
       'SqlType': 'REAL'},
      {'Name': 'north_fan_speed_01oa943__rpm__max',
       'Mapping': '$.north_fan_speed_01oa943__rpm__max',
       'SqlType': 'REAL'},
      {'Name': 'south_fan_speed_02oa943__rpm__avg',
       'Mapping': '$.south_fan_speed_02oa943__rpm__avg',
       'SqlType': 'REAL'},
      {'Name': 'south_fan_speed_02oa943__rpm__max',
       'Mapping': '$.south_fan_speed_02oa943__rpm__max',
       'SqlType': 'REAL'},
      {'Name': 'lignite_main_burner_03sk820__tph__avg',
       'Mapping': '$.lignite_main_burner_03sk820__tph__avg',
       'SqlType': 'REAL'},
      {'Name': 'lignite_main_burner_03sk820__tph__max',
       'Mapping': '$.lignite_main_burner_03sk820__tph__max',
       'SqlType': 'REAL'},
      {'Name': 'bpg_main_burner_03bf810__tph__avg',
       'Mapping': '$.bpg_main_burner_03bf810__tph__avg',
       'SqlType': 'REAL'},
      {'Name': 'bpg_main_burner_03bf810__tph__max',
       'Mapping': '$.bpg_main_burner_03bf810__tph__max',
       'SqlType': 'REAL'},
      {'Name': 'lignite_calciner_02sk820__tph__avg',
       'Mapping': '$.lignite_calciner_02sk820__tph__avg',
       'SqlType': 'REAL'},
      {'Name': 'lignite_calciner_02sk820__tph__max',
       'Mapping': '$.lignite_calciner_02sk820__tph__max',
       'SqlType': 'REAL'},
      {'Name': 'bpg_calciner_02bf810__tph__avg',
       'Mapping': '$.bpg_calciner_02bf810__tph__avg',
       'SqlType': 'REAL'},
      {'Name': 'bpg_calciner_02bf810__tph__max',
       'Mapping': '$.bpg_calciner_02bf810__tph__max',
       'SqlType': 'REAL'},
      {'Name': 'kbs_calciner_00kb950__tph__avg',
       'Mapping': '$.kbs_calciner_00kb950__tph__avg',
       'SqlType': 'REAL'},
      {'Name': 'kbs_calciner_00kb950__tph__max',
       'Mapping': '$.kbs_calciner_00kb950__tph__max',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_main_burner__gj_h__avg_0',
       'Mapping': '$.total_energy_to_main_burner__gj_h__avg_0',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_main_burner__gj_h__max_0',
       'Mapping': '$.total_energy_to_main_burner__gj_h__max_0',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_main_burner__gj_h__avg_1',
       'Mapping': '$.total_energy_to_main_burner__gj_h__avg_1',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_main_burner__gj_h__max_1',
       'Mapping': '$.total_energy_to_main_burner__gj_h__max_1',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_main_burner__gj_h__avg_2',
       'Mapping': '$.total_energy_to_main_burner__gj_h__avg_2',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_main_burner__gj_h__max_2',
       'Mapping': '$.total_energy_to_main_burner__gj_h__max_2',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_main_burner__gj_h__avg_3',
       'Mapping': '$.total_energy_to_main_burner__gj_h__avg_3',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_main_burner__gj_h__max_3',
       'Mapping': '$.total_energy_to_main_burner__gj_h__max_3',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_calciner__gj_h__avg_0',
       'Mapping': '$.total_energy_to_calciner__gj_h__avg_0',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_calciner__gj_h__max_0',
       'Mapping': '$.total_energy_to_calciner__gj_h__max_0',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_calciner__gj_h__avg_1',
       'Mapping': '$.total_energy_to_calciner__gj_h__avg_1',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_calciner__gj_h__max_1',
       'Mapping': '$.total_energy_to_calciner__gj_h__max_1',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_calciner__gj_h__avg_2',
       'Mapping': '$.total_energy_to_calciner__gj_h__avg_2',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_calciner__gj_h__max_2',
       'Mapping': '$.total_energy_to_calciner__gj_h__max_2',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_calciner__gj_h__avg_3',
       'Mapping': '$.total_energy_to_calciner__gj_h__avg_3',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_to_calciner__gj_h__max_3',
       'Mapping': '$.total_energy_to_calciner__gj_h__max_3',
       'SqlType': 'REAL'},
      {'Name': 'tf__traditional_fuel__avg',
       'Mapping': '$.tf__traditional_fuel__avg',
       'SqlType': 'REAL'},
      {'Name': 'tf__traditional_fuel__max',
       'Mapping': '$.tf__traditional_fuel__max',
       'SqlType': 'REAL'},
      {'Name': 'af__alternative_fuel__avg',
       'Mapping': '$.af__alternative_fuel__avg',
       'SqlType': 'REAL'},
      {'Name': 'af__alternative_fuel__max',
       'Mapping': '$.af__alternative_fuel__max',
       'SqlType': 'REAL'},
      {'Name': 'shc__gj__t_kiln_feed__avg',
       'Mapping': '$.shc__gj__t_kiln_feed__avg',
       'SqlType': 'REAL'},
      {'Name': 'shc__gj__t_kiln_feed__max',
       'Mapping': '$.shc__gj__t_kiln_feed__max',
       'SqlType': 'REAL'},
      {'Name': 'nox_concentration_in_kiln_inlet_00oa983__ppm__avg_0',
       'Mapping': '$.nox_concentration_in_kiln_inlet_00oa983__ppm__avg_0',
       'SqlType': 'REAL'},
      {'Name': 'nox_concentration_in_kiln_inlet_00oa983__ppm__max_0',
       'Mapping': '$.nox_concentration_in_kiln_inlet_00oa983__ppm__max_0',
       'SqlType': 'REAL'},
      {'Name': 'nox_concentration_in_kiln_inlet_00oa983__ppm__avg_1',
       'Mapping': '$.nox_concentration_in_kiln_inlet_00oa983__ppm__avg_1',
       'SqlType': 'REAL'},
      {'Name': 'nox_concentration_in_kiln_inlet_00oa983__ppm__max_1',
       'Mapping': '$.nox_concentration_in_kiln_inlet_00oa983__ppm__max_1',
       'SqlType': 'REAL'},
      {'Name': 'nox_concentration_in_kiln_inlet_00oa983__ppm__avg_2',
       'Mapping': '$.nox_concentration_in_kiln_inlet_00oa983__ppm__avg_2',
       'SqlType': 'REAL'},
      {'Name': 'nox_concentration_in_kiln_inlet_00oa983__ppm__max_2',
       'Mapping': '$.nox_concentration_in_kiln_inlet_00oa983__ppm__max_2',
       'SqlType': 'REAL'},
      {'Name': 'nox_concentration_in_kiln_inlet_00oa983__ppm__avg_3',
       'Mapping': '$.nox_concentration_in_kiln_inlet_00oa983__ppm__avg_3',
       'SqlType': 'REAL'},
      {'Name': 'nox_concentration_in_kiln_inlet_00oa983__ppm__max_3',
       'Mapping': '$.nox_concentration_in_kiln_inlet_00oa983__ppm__max_3',
       'SqlType': 'REAL'},
      {'Name': 'co_concentration_in_kiln_inlet_00oa981__ppm__avg',
       'Mapping': '$.co_concentration_in_kiln_inlet_00oa981__ppm__avg',
       'SqlType': 'REAL'},
      {'Name': 'co_concentration_in_kiln_inlet_00oa981__ppm__max',
       'Mapping': '$.co_concentration_in_kiln_inlet_00oa981__ppm__max',
       'SqlType': 'REAL'},
      {'Name': 'o2_concentration_in_kiln_inlet_00oa982_____avg',
       'Mapping': '$.o2_concentration_in_kiln_inlet_00oa982_____avg',
       'SqlType': 'REAL'},
      {'Name': 'o2_concentration_in_kiln_inlet_00oa982_____max',
       'Mapping': '$.o2_concentration_in_kiln_inlet_00oa982_____max',
       'SqlType': 'REAL'},
      {'Name': 'bottom_cyclone_gas_temperature_00oa800___c___avg',
       'Mapping': '$.bottom_cyclone_gas_temperature_00oa800___c___avg',
       'SqlType': 'REAL'},
      {'Name': 'bottom_cyclone_gas_temperature_00oa800___c___max',
       'Mapping': '$.bottom_cyclone_gas_temperature_00oa800___c___max',
       'SqlType': 'REAL'},
      {'Name': 'secondary_air_temperature_01kk827___c___avg_0',
       'Mapping': '$.secondary_air_temperature_01kk827___c___avg_0',
       'SqlType': 'REAL'},
      {'Name': 'secondary_air_temperature_01kk827___c___max_0',
       'Mapping': '$.secondary_air_temperature_01kk827___c___max_0',
       'SqlType': 'REAL'},
      {'Name': 'secondary_air_temperature_01kk827___c___avg_1',
       'Mapping': '$.secondary_air_temperature_01kk827___c___avg_1',
       'SqlType': 'REAL'},
      {'Name': 'secondary_air_temperature_01kk827___c___max_1',
       'Mapping': '$.secondary_air_temperature_01kk827___c___max_1',
       'SqlType': 'REAL'},
      {'Name': 'secondary_air_temperature_01kk827___c___avg_2',
       'Mapping': '$.secondary_air_temperature_01kk827___c___avg_2',
       'SqlType': 'REAL'},
      {'Name': 'secondary_air_temperature_01kk827___c___max_2',
       'Mapping': '$.secondary_air_temperature_01kk827___c___max_2',
       'SqlType': 'REAL'},
      {'Name': 'secondary_air_temperature_01kk827___c___avg_3',
       'Mapping': '$.secondary_air_temperature_01kk827___c___avg_3',
       'SqlType': 'REAL'},
      {'Name': 'secondary_air_temperature_01kk827___c___max_3',
       'Mapping': '$.secondary_air_temperature_01kk827___c___max_3',
       'SqlType': 'REAL'},
      {'Name': 'tertiary_air_temperature_01kb801___c___avg_0',
       'Mapping': '$.tertiary_air_temperature_01kb801___c___avg_0',
       'SqlType': 'REAL'},
      {'Name': 'tertiary_air_temperature_01kb801___c___max_0',
       'Mapping': '$.tertiary_air_temperature_01kb801___c___max_0',
       'SqlType': 'REAL'},
      {'Name': 'tertiary_air_temperature_01kb801___c___avg_1',
       'Mapping': '$.tertiary_air_temperature_01kb801___c___avg_1',
       'SqlType': 'REAL'},
      {'Name': 'tertiary_air_temperature_01kb801___c___max_1',
       'Mapping': '$.tertiary_air_temperature_01kb801___c___max_1',
       'SqlType': 'REAL'},
      {'Name': 'tertiary_air_temperature_01kb801___c___avg_2',
       'Mapping': '$.tertiary_air_temperature_01kb801___c___avg_2',
       'SqlType': 'REAL'},
      {'Name': 'tertiary_air_temperature_01kb801___c___max_2',
       'Mapping': '$.tertiary_air_temperature_01kb801___c___max_2',
       'SqlType': 'REAL'},
      {'Name': 'tertiary_air_temperature_01kb801___c___avg_3',
       'Mapping': '$.tertiary_air_temperature_01kb801___c___avg_3',
       'SqlType': 'REAL'},
      {'Name': 'tertiary_air_temperature_01kb801___c___max_3',
       'Mapping': '$.tertiary_air_temperature_01kb801___c___max_3',
       'SqlType': 'REAL'},
      {'Name': 'kiln_amps_01do812__amps__avg_0',
       'Mapping': '$.kiln_amps_01do812__amps__avg_0',
       'SqlType': 'REAL'},
      {'Name': 'kiln_amps_01do812__amps__max_0',
       'Mapping': '$.kiln_amps_01do812__amps__max_0',
       'SqlType': 'REAL'},
      {'Name': 'kiln_amps_01do812__amps__avg_1',
       'Mapping': '$.kiln_amps_01do812__amps__avg_1',
       'SqlType': 'REAL'},
      {'Name': 'kiln_amps_01do812__amps__max_1',
       'Mapping': '$.kiln_amps_01do812__amps__max_1',
       'SqlType': 'REAL'},
      {'Name': 'kiln_amps_01do812__amps__avg_2',
       'Mapping': '$.kiln_amps_01do812__amps__avg_2',
       'SqlType': 'REAL'},
      {'Name': 'kiln_amps_01do812__amps__max_2',
       'Mapping': '$.kiln_amps_01do812__amps__max_2',
       'SqlType': 'REAL'},
      {'Name': 'kiln_amps_01do812__amps__avg_3',
       'Mapping': '$.kiln_amps_01do812__amps__avg_3',
       'SqlType': 'REAL'},
      {'Name': 'kiln_amps_01do812__amps__max_3',
       'Mapping': '$.kiln_amps_01do812__amps__max_3',
       'SqlType': 'REAL'},
      {'Name': 'co_bottom_cyclone_north_00oa941__amps__avg',
       'Mapping': '$.co_bottom_cyclone_north_00oa941__amps__avg',
       'SqlType': 'REAL'},
      {'Name': 'co_bottom_cyclone_north_00oa941__amps__max',
       'Mapping': '$.co_bottom_cyclone_north_00oa941__amps__max',
       'SqlType': 'REAL'},
      {'Name': 'o2_bottom_cyclone_north_00oa942_____avg_0',
       'Mapping': '$.o2_bottom_cyclone_north_00oa942_____avg_0',
       'SqlType': 'REAL'},
      {'Name': 'o2_bottom_cyclone_north_00oa942_____max_0',
       'Mapping': '$.o2_bottom_cyclone_north_00oa942_____max_0',
       'SqlType': 'REAL'},
      {'Name': 'o2_bottom_cyclone_north_00oa942_____avg_1',
       'Mapping': '$.o2_bottom_cyclone_north_00oa942_____avg_1',
       'SqlType': 'REAL'},
      {'Name': 'o2_bottom_cyclone_north_00oa942_____max_1',
       'Mapping': '$.o2_bottom_cyclone_north_00oa942_____max_1',
       'SqlType': 'REAL'},
      {'Name': 'o2_bottom_cyclone_north_00oa942_____avg_2',
       'Mapping': '$.o2_bottom_cyclone_north_00oa942_____avg_2',
       'SqlType': 'REAL'},
      {'Name': 'o2_bottom_cyclone_north_00oa942_____max_2',
       'Mapping': '$.o2_bottom_cyclone_north_00oa942_____max_2',
       'SqlType': 'REAL'},
      {'Name': 'o2_bottom_cyclone_north_00oa942_____avg_3',
       'Mapping': '$.o2_bottom_cyclone_north_00oa942_____avg_3',
       'SqlType': 'REAL'},
      {'Name': 'o2_bottom_cyclone_north_00oa942_____max_3',
       'Mapping': '$.o2_bottom_cyclone_north_00oa942_____max_3',
       'SqlType': 'REAL'},
      {'Name': 'kiln_speed_01do811__rpm__avg',
       'Mapping': '$.kiln_speed_01do811__rpm__avg',
       'SqlType': 'REAL'},
      {'Name': 'kiln_speed_01do811__rpm__max',
       'Mapping': '$.kiln_speed_01do811__rpm__max',
       'SqlType': 'REAL'},
      {'Name': 'primary_air_amount_01of850__nm3_h___avg',
       'Mapping': '$.primary_air_amount_01of850__nm3_h___avg',
       'SqlType': 'REAL'},
      {'Name': 'primary_air_amount_01of850__nm3_h___max',
       'Mapping': '$.primary_air_amount_01of850__nm3_h___max',
       'SqlType': 'REAL'},
      {'Name': 'axial_air_pressure_01of811__mbar__avg',
       'Mapping': '$.axial_air_pressure_01of811__mbar__avg',
       'SqlType': 'REAL'},
      {'Name': 'axial_air_pressure_01of811__mbar__max',
       'Mapping': '$.axial_air_pressure_01of811__mbar__max',
       'SqlType': 'REAL'},
      {'Name': 'radial_air_pressure_01of812__mbar__avg',
       'Mapping': '$.radial_air_pressure_01of812__mbar__avg',
       'SqlType': 'REAL'},
      {'Name': 'radial_air_pressure_01of812__mbar__max',
       'Mapping': '$.radial_air_pressure_01of812__mbar__max',
       'SqlType': 'REAL'},
      {'Name': 'central_air_pressure_01of813__mbar__avg',
       'Mapping': '$.central_air_pressure_01of813__mbar__avg',
       'SqlType': 'REAL'},
      {'Name': 'central_air_pressure_01of813__mbar__max',
       'Mapping': '$.central_air_pressure_01of813__mbar__max',
       'SqlType': 'REAL'},
      {'Name': 'total_feed_avg',
       'Mapping': '$.total_feed_avg',
       'SqlType': 'REAL'},
      {'Name': 'total_feed_max',
       'Mapping': '$.total_feed_max',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_avg',
       'Mapping': '$.total_energy_avg',
       'SqlType': 'REAL'},
      {'Name': 'total_energy_max',
       'Mapping': '$.total_energy_max',
       'SqlType': 'REAL'},
      {'Name': 'average_fan_speed_avg',
       'Mapping': '$.average_fan_speed_avg',
       'SqlType': 'REAL'},
      {'Name': 'average_fan_speed_max',
       'Mapping': '$.average_fan_speed_max',
       'SqlType': 'REAL'},
      {'Name': 'average_air_temperature_avg',
       'Mapping': '$.average_air_temperature_avg',
       'SqlType': 'REAL'},
      {'Name': 'average_air_temperature_max',
       'Mapping': '$.average_air_temperature_max',
       'SqlType': 'REAL'},
      {'Name': 'kiln_feed_rate_avg',
       'Mapping': '$.kiln_feed_rate_avg',
       'SqlType': 'REAL'},
      {'Name': 'kiln_feed_rate_max',
       'Mapping': '$.kiln_feed_rate_max',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_c3s_lag_shift',
       'Mapping': '$.klinker___nk_c3s_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_mgo_lag_shift',
       'Mapping': '$.klinker___nk_mgo_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_fe2o3_lag_shift',
       'Mapping': '$.klinker___nk_fe2o3_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_al2o3_lag_shift',
       'Mapping': '$.klinker___nk_al2o3_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_na2o_lag_shift',
       'Mapping': '$.klinker___nk_na2o_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_k2o_lag_shift',
       'Mapping': '$.klinker___nk_k2o_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_cao_lag_shift',
       'Mapping': '$.klinker___nk_cao_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_sio2_lag_shift',
       'Mapping': '$.klinker___nk_sio2_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'heat_of_formation__kcal_kg_clinker__lag_shift',
       'Mapping': '$.heat_of_formation__kcal_kg_clinker__lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_so3_lag_shift',
       'Mapping': '$.klinker___nk_so3_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_sm_lag_shift',
       'Mapping': '$.klinker___nk_sm_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_am_lag_shift',
       'Mapping': '$.klinker___nk_am_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'klinker___nk_lsf_lag_shift',
       'Mapping': '$.klinker___nk_lsf_lag_shift',
       'SqlType': 'REAL'},
      {'Name': 'id', 'Mapping': '$.id', 'SqlType': 'REAL'},
      {'Name': 'event_time', 'Mapping': '$.event_time', 'SqlType': 'REAL'}]},
    'InputParallelism': {'Count': 1},
    'InputStartingPositionConfiguration': {}}],
  'OutputDescriptions': [{'OutputId': '1.1',
    'Name': 'DESTINATION_SQL_STREAM',
    'LambdaOutputDescription': {'ResourceARN': 'arn:aws:lambda:us-east-1:082830052325:function:HeidelbergStreamingIngestAggFeatures3',
     'RoleARN': 'arn:aws:iam::082830052325:role/MySagemakerRoleHeidelberg3'},
    'DestinationSchema': {'RecordFormatType': 'JSON'}}],
  'ApplicationCode': 'CREATE OR REPLACE STREAM "DESTINATION_SQL_STREAM" (\n"kst_brutto"      REAL,\n"sm"      REAL,\n"tm"      REAL,\n"cl"      REAL,\n"so3"      REAL,\n"k2o"      REAL,\n"na2o"      REAL,\n"south_kiln_feed_01om886__tph__avg"      REAL,\n"south_kiln_feed_01om886__tph__max"      REAL,\n"north_kiln_feed_01om885__tph__avg"      REAL,\n"north_kiln_feed_01om885__tph__max"      REAL,\n"north_fan_speed_01oa943__rpm__avg"      REAL,\n"north_fan_speed_01oa943__rpm__max"      REAL,\n"south_fan_speed_02oa943__rpm__avg"      REAL,\n"south_fan_speed_02oa943__rpm__max"      REAL,\n"lignite_main_burner_03sk820__tph__avg"      REAL,\n"lignite_main_burner_03sk820__tph__max"      REAL,\n"bpg_main_burner_03bf810__tph__avg"      REAL,\n"bpg_main_burner_03bf810__tph__max"      REAL,\n"lignite_calciner_02sk820__tph__avg"      REAL,\n"lignite_calciner_02sk820__tph__max"      REAL,\n"bpg_calciner_02bf810__tph__avg"      REAL,\n"bpg_calciner_02bf810__tph__max"      REAL,\n"kbs_calciner_00kb950__tph__avg"      REAL,\n"kbs_calciner_00kb950__tph__max"      REAL,\n"total_energy_to_main_burner__gj_h__avg_0"      REAL,\n"total_energy_to_main_burner__gj_h__max_0"      REAL,\n"total_energy_to_main_burner__gj_h__avg_1"      REAL,\n"total_energy_to_main_burner__gj_h__max_1"      REAL,\n"total_energy_to_main_burner__gj_h__avg_2"      REAL,\n"total_energy_to_main_burner__gj_h__max_2"      REAL,\n"total_energy_to_main_burner__gj_h__avg_3"      REAL,\n"total_energy_to_main_burner__gj_h__max_3"      REAL,\n"total_energy_to_calciner__gj_h__avg_0"      REAL,\n"total_energy_to_calciner__gj_h__max_0"      REAL,\n"total_energy_to_calciner__gj_h__avg_1"      REAL,\n"total_energy_to_calciner__gj_h__max_1"      REAL,\n"total_energy_to_calciner__gj_h__avg_2"      REAL,\n"total_energy_to_calciner__gj_h__max_2"      REAL,\n"total_energy_to_calciner__gj_h__avg_3"      REAL,\n"total_energy_to_calciner__gj_h__max_3"      REAL,\n"tf__traditional_fuel__avg"      REAL,\n"tf__traditional_fuel__max"      REAL,\n"af__alternative_fuel__avg"      REAL,\n"af__alternative_fuel__max"      REAL,\n"shc__gj__t_kiln_feed__avg"      REAL,\n"shc__gj__t_kiln_feed__max"      REAL,\n"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_0"      REAL,\n"nox_concentration_in_kiln_inlet_00oa983__ppm__max_0"      REAL,\n"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_1"      REAL,\n"nox_concentration_in_kiln_inlet_00oa983__ppm__max_1"      REAL,\n"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_2"      REAL,\n"nox_concentration_in_kiln_inlet_00oa983__ppm__max_2"      REAL,\n"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_3"      REAL,\n"nox_concentration_in_kiln_inlet_00oa983__ppm__max_3"      REAL,\n"co_concentration_in_kiln_inlet_00oa981__ppm__avg"      REAL,\n"co_concentration_in_kiln_inlet_00oa981__ppm__max"      REAL,\n"o2_concentration_in_kiln_inlet_00oa982_____avg"      REAL,\n"o2_concentration_in_kiln_inlet_00oa982_____max"      REAL,\n"bottom_cyclone_gas_temperature_00oa800___c___avg"      REAL,\n"bottom_cyclone_gas_temperature_00oa800___c___max"      REAL,\n"secondary_air_temperature_01kk827___c___avg_0"      REAL,\n"secondary_air_temperature_01kk827___c___max_0"      REAL,\n"secondary_air_temperature_01kk827___c___avg_1"      REAL,\n"secondary_air_temperature_01kk827___c___max_1"      REAL,\n"secondary_air_temperature_01kk827___c___avg_2"      REAL,\n"secondary_air_temperature_01kk827___c___max_2"      REAL,\n"secondary_air_temperature_01kk827___c___avg_3"      REAL,\n"secondary_air_temperature_01kk827___c___max_3"      REAL,\n"tertiary_air_temperature_01kb801___c___avg_0"      REAL,\n"tertiary_air_temperature_01kb801___c___max_0"      REAL,\n"tertiary_air_temperature_01kb801___c___avg_1"      REAL,\n"tertiary_air_temperature_01kb801___c___max_1"      REAL,\n"tertiary_air_temperature_01kb801___c___avg_2"      REAL,\n"tertiary_air_temperature_01kb801___c___max_2"      REAL,\n"tertiary_air_temperature_01kb801___c___avg_3"      REAL,\n"tertiary_air_temperature_01kb801___c___max_3"      REAL,\n"kiln_amps_01do812__amps__avg_0"      REAL,\n"kiln_amps_01do812__amps__max_0"      REAL,\n"kiln_amps_01do812__amps__avg_1"      REAL,\n"kiln_amps_01do812__amps__max_1"      REAL,\n"kiln_amps_01do812__amps__avg_2"      REAL,\n"kiln_amps_01do812__amps__max_2"      REAL,\n"kiln_amps_01do812__amps__avg_3"      REAL,\n"kiln_amps_01do812__amps__max_3"      REAL,\n"co_bottom_cyclone_north_00oa941__amps__avg"      REAL,\n"co_bottom_cyclone_north_00oa941__amps__max"      REAL,\n"o2_bottom_cyclone_north_00oa942_____avg_0"      REAL,\n"o2_bottom_cyclone_north_00oa942_____max_0"      REAL,\n"o2_bottom_cyclone_north_00oa942_____avg_1"      REAL,\n"o2_bottom_cyclone_north_00oa942_____max_1"      REAL,\n"o2_bottom_cyclone_north_00oa942_____avg_2"      REAL,\n"o2_bottom_cyclone_north_00oa942_____max_2"      REAL,\n"o2_bottom_cyclone_north_00oa942_____avg_3"      REAL,\n"o2_bottom_cyclone_north_00oa942_____max_3"      REAL,\n"kiln_speed_01do811__rpm__avg"      REAL,\n"kiln_speed_01do811__rpm__max"      REAL,\n"primary_air_amount_01of850__nm3_h___avg"      REAL,\n"primary_air_amount_01of850__nm3_h___max"      REAL,\n"axial_air_pressure_01of811__mbar__avg"      REAL,\n"axial_air_pressure_01of811__mbar__max"      REAL,\n"radial_air_pressure_01of812__mbar__avg"      REAL,\n"radial_air_pressure_01of812__mbar__max"      REAL,\n"central_air_pressure_01of813__mbar__avg"      REAL,\n"central_air_pressure_01of813__mbar__max"      REAL,\n"total_feed_avg"      REAL,\n"total_feed_max"      REAL,\n"total_energy_avg"      REAL,\n"total_energy_max"      REAL,\n"average_fan_speed_avg"      REAL,\n"average_fan_speed_max"      REAL,\n"average_air_temperature_avg"      REAL,\n"average_air_temperature_max"      REAL,\n"kiln_feed_rate_avg"      REAL,\n"kiln_feed_rate_max"      REAL,\n"klinker___nk_c3s_lag_shift"      REAL,\n"klinker___nk_mgo_lag_shift"      REAL,\n"klinker___nk_fe2o3_lag_shift"      REAL,\n"klinker___nk_al2o3_lag_shift"      REAL,\n"klinker___nk_na2o_lag_shift"      REAL,\n"klinker___nk_k2o_lag_shift"      REAL,\n"klinker___nk_cao_lag_shift"      REAL,\n"klinker___nk_sio2_lag_shift"      REAL,\n"heat_of_formation__kcal_kg_clinker__lag_shift"      REAL,\n"klinker___nk_so3_lag_shift"      REAL,\n"klinker___nk_sm_lag_shift"      REAL,\n"klinker___nk_am_lag_shift"      REAL,\n"klinker___nk_lsf_lag_shift"      REAL,\n"id"      REAL,\n"event_time"      REAL\n); \n\nCREATE OR REPLACE PUMP "STREAM_PUMP" AS\n INSERT INTO "DESTINATION_SQL_STREAM"\nSELECT STREAM "kst_brutto", \n"sm", \n"tm", \n"cl", \n"so3", \n"k2o", \n"na2o", \n"south_kiln_feed_01om886__tph__avg", \n"south_kiln_feed_01om886__tph__max", \n"north_kiln_feed_01om885__tph__avg", \n"north_kiln_feed_01om885__tph__max", \n"north_fan_speed_01oa943__rpm__avg", \n"north_fan_speed_01oa943__rpm__max", \n"south_fan_speed_02oa943__rpm__avg", \n"south_fan_speed_02oa943__rpm__max", \n"lignite_main_burner_03sk820__tph__avg", \n"lignite_main_burner_03sk820__tph__max", \n"bpg_main_burner_03bf810__tph__avg", \n"bpg_main_burner_03bf810__tph__max", \n"lignite_calciner_02sk820__tph__avg", \n"lignite_calciner_02sk820__tph__max", \n"bpg_calciner_02bf810__tph__avg", \n"bpg_calciner_02bf810__tph__max", \n"kbs_calciner_00kb950__tph__avg", \n"kbs_calciner_00kb950__tph__max", \n"total_energy_to_main_burner__gj_h__avg_0", \n"total_energy_to_main_burner__gj_h__max_0", \n"total_energy_to_main_burner__gj_h__avg_1", \n"total_energy_to_main_burner__gj_h__max_1", \n"total_energy_to_main_burner__gj_h__avg_2", \n"total_energy_to_main_burner__gj_h__max_2", \n"total_energy_to_main_burner__gj_h__avg_3", \n"total_energy_to_main_burner__gj_h__max_3", \n"total_energy_to_calciner__gj_h__avg_0", \n"total_energy_to_calciner__gj_h__max_0", \n"total_energy_to_calciner__gj_h__avg_1", \n"total_energy_to_calciner__gj_h__max_1", \n"total_energy_to_calciner__gj_h__avg_2", \n"total_energy_to_calciner__gj_h__max_2", \n"total_energy_to_calciner__gj_h__avg_3", \n"total_energy_to_calciner__gj_h__max_3", \n"tf__traditional_fuel__avg", \n"tf__traditional_fuel__max", \n"af__alternative_fuel__avg", \n"af__alternative_fuel__max", \n"shc__gj__t_kiln_feed__avg", \n"shc__gj__t_kiln_feed__max", \n"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_0", \n"nox_concentration_in_kiln_inlet_00oa983__ppm__max_0", \n"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_1", \n"nox_concentration_in_kiln_inlet_00oa983__ppm__max_1", \n"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_2", \n"nox_concentration_in_kiln_inlet_00oa983__ppm__max_2", \n"nox_concentration_in_kiln_inlet_00oa983__ppm__avg_3", \n"nox_concentration_in_kiln_inlet_00oa983__ppm__max_3", \n"co_concentration_in_kiln_inlet_00oa981__ppm__avg", \n"co_concentration_in_kiln_inlet_00oa981__ppm__max", \n"o2_concentration_in_kiln_inlet_00oa982_____avg", \n"o2_concentration_in_kiln_inlet_00oa982_____max", \n"bottom_cyclone_gas_temperature_00oa800___c___avg", \n"bottom_cyclone_gas_temperature_00oa800___c___max", \n"secondary_air_temperature_01kk827___c___avg_0", \n"secondary_air_temperature_01kk827___c___max_0", \n"secondary_air_temperature_01kk827___c___avg_1", \n"secondary_air_temperature_01kk827___c___max_1", \n"secondary_air_temperature_01kk827___c___avg_2", \n"secondary_air_temperature_01kk827___c___max_2", \n"secondary_air_temperature_01kk827___c___avg_3", \n"secondary_air_temperature_01kk827___c___max_3", \n"tertiary_air_temperature_01kb801___c___avg_0", \n"tertiary_air_temperature_01kb801___c___max_0", \n"tertiary_air_temperature_01kb801___c___avg_1", \n"tertiary_air_temperature_01kb801___c___max_1", \n"tertiary_air_temperature_01kb801___c___avg_2", \n"tertiary_air_temperature_01kb801___c___max_2", \n"tertiary_air_temperature_01kb801___c___avg_3", \n"tertiary_air_temperature_01kb801___c___max_3", \n"kiln_amps_01do812__amps__avg_0", \n"kiln_amps_01do812__amps__max_0", \n"kiln_amps_01do812__amps__avg_1", \n"kiln_amps_01do812__amps__max_1", \n"kiln_amps_01do812__amps__avg_2", \n"kiln_amps_01do812__amps__max_2", \n"kiln_amps_01do812__amps__avg_3", \n"kiln_amps_01do812__amps__max_3", \n"co_bottom_cyclone_north_00oa941__amps__avg", \n"co_bottom_cyclone_north_00oa941__amps__max", \n"o2_bottom_cyclone_north_00oa942_____avg_0", \n"o2_bottom_cyclone_north_00oa942_____max_0", \n"o2_bottom_cyclone_north_00oa942_____avg_1", \n"o2_bottom_cyclone_north_00oa942_____max_1", \n"o2_bottom_cyclone_north_00oa942_____avg_2", \n"o2_bottom_cyclone_north_00oa942_____max_2", \n"o2_bottom_cyclone_north_00oa942_____avg_3", \n"o2_bottom_cyclone_north_00oa942_____max_3", \n"kiln_speed_01do811__rpm__avg", \n"kiln_speed_01do811__rpm__max", \n"primary_air_amount_01of850__nm3_h___avg", \n"primary_air_amount_01of850__nm3_h___max", \n"axial_air_pressure_01of811__mbar__avg", \n"axial_air_pressure_01of811__mbar__max", \n"radial_air_pressure_01of812__mbar__avg", \n"radial_air_pressure_01of812__mbar__max", \n"central_air_pressure_01of813__mbar__avg", \n"central_air_pressure_01of813__mbar__max", \n"total_feed_avg", \n"total_feed_max", \n"total_energy_avg", \n"total_energy_max", \n"average_fan_speed_avg", \n"average_fan_speed_max", \n"average_air_temperature_avg", \n"average_air_temperature_max", \n"kiln_feed_rate_avg", \n"kiln_feed_rate_max", \n"klinker___nk_c3s_lag_shift", \n"klinker___nk_mgo_lag_shift", \n"klinker___nk_fe2o3_lag_shift", \n"klinker___nk_al2o3_lag_shift", \n"klinker___nk_na2o_lag_shift", \n"klinker___nk_k2o_lag_shift", \n"klinker___nk_cao_lag_shift", \n"klinker___nk_sio2_lag_shift", \n"heat_of_formation__kcal_kg_clinker__lag_shift", \n"klinker___nk_so3_lag_shift", \n"klinker___nk_sm_lag_shift", \n"klinker___nk_am_lag_shift", \n"klinker___nk_lsf_lag_shift", \n"id", \n"event_time" \nFROM "SOURCE_SQL_STREAM_001"\nWINDOW LAST_10_MINUTES AS (\nPARTITION BY "id"\nRANGE INTERVAL \'10\' MINUTE PRECEDING);\n',
  'ApplicationVersionId': 1},
 'ResponseMetadata': {'RequestId': 'e0e7f7e5-17ee-45ab-85d2-e6f03c16948a',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': 'e0e7f7e5-17ee-45ab-85d2-e6f03c16948a',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '27895',
   'date': 'Tue, 05 Jan 2021 17:51:15 GMT'},
  'RetryAttempts': 0}}
kda_client.start_application(ApplicationName=APPLICATION_NAME,
                             InputConfigurations=[{'Id': '1.1',
                                                   'InputStartingPositionConfiguration': 
                                                     {'InputStartingPosition':'NOW'}}])
{'ResponseMetadata': {'RequestId': '65d9eecd-8466-4fcb-8de5-88a6d0369662',
  'HTTPStatusCode': 200,
  'HTTPHeaders': {'x-amzn-requestid': '65d9eecd-8466-4fcb-8de5-88a6d0369662',
   'content-type': 'application/x-amz-json-1.1',
   'content-length': '2',
   'date': 'Tue, 05 Jan 2021 17:51:22 GMT'},
  'RetryAttempts': 0}}

Training and Deploying the Model

1. Train and Deploy the model (Hyperparameter Training)

2. Get the endpoint of deployed model

Split the data in train and val and train the model using XGBOOST

s3 = boto3.resource('s3')
obj = s3.Object(s3_bucket,s3_prefix + '/' + s3_transformed_data_filename )
body = obj.get()['Body'].read()
df=pd.read_csv(io.BytesIO(body))
from sklearn.model_selection import train_test_split

train, val = train_test_split(df, test_size=0.3)
train.to_csv(f'train.csv', header=False, index=False)
val.to_csv(f'val.csv', header=False, index=False)
!aws s3 cp train.csv s3://{s3_bucket}/{s3_prefix}/
!aws s3 cp val.csv s3://{s3_bucket}/{s3_prefix}/
upload: ./train.csv to s3://sagemaker-us-east-1-082830052325/heidelberg/data/train.csv
upload: ./val.csv to s3://sagemaker-us-east-1-082830052325/heidelberg/data/val.csv
from sagemaker.inputs import TrainingInput

# initialize hyperparameters
hyperparameters = {
        "max_depth":"5",
        "eta":"0.2",
        "gamma":"4",
        "min_child_weight":"6",
        "subsample":"0.7",
        "objective":"reg:linear",
        "num_round":"100"}

output_path = 's3://{}/{}/output'.format(s3_bucket, s3_prefix)

# this line automatically looks for the XGBoost image URI and builds an XGBoost container.
# specify the repo_version depending on your preference.
xgboost_container = sagemaker.image_uris.retrieve("xgboost", sagemaker.Session().boto_region_name, "1.2-1")

# construct a SageMaker estimator that calls the xgboost-container
estimator = sagemaker.estimator.Estimator(image_uri=xgboost_container, 
                                          hyperparameters=hyperparameters,
                                          role=sagemaker.get_execution_role(),
                                          instance_count=1, 
                                          instance_type='ml.m5.2xlarge', 
                                          volume_size=5, # 5 GB 
                                          output_path=output_path)

# define the data type and paths to the training and validation datasets
content_type = "csv"
train_input = TrainingInput("s3://{}/{}/{}".format(s3_bucket, s3_prefix, 'train.csv'), content_type=content_type)
validation_input = TrainingInput("s3://{}/{}/{}".format(s3_bucket, s3_prefix, 'val.csv'), content_type=content_type)

# execute the XGBoost training job
estimator.fit({'train': train_input, 'validation': validation_input})
2021-01-05 17:52:09 Starting - Starting the training job...
2021-01-05 17:52:35 Starting - Launching requested ML instancesProfilerReport-1609869129: InProgress
......
2021-01-05 17:53:36 Starting - Preparing the instances for training...
2021-01-05 17:54:05 Downloading - Downloading input data...
2021-01-05 17:54:38 Training - Training image download completed. Training in progress..INFO:sagemaker-containers:Imported framework sagemaker_xgboost_container.training
INFO:sagemaker-containers:Failed to parse hyperparameter objective value reg:linear to Json.
Returning the value itself
INFO:sagemaker-containers:No GPUs detected (normal if no gpus installed)
INFO:sagemaker_xgboost_container.training:Running XGBoost Sagemaker in algorithm mode
INFO:root:Determined delimiter of CSV input is ','
INFO:root:Determined delimiter of CSV input is ','
INFO:root:Determined delimiter of CSV input is ','
INFO:root:Determined delimiter of CSV input is ','
INFO:root:Single node training.
INFO:root:Train matrix has 4610 rows
INFO:root:Validation matrix has 1977 rows
[17:54:39] WARNING: ../src/objective/regression_obj.cu:174: reg:linear is now deprecated in favor of reg:squarederror.
[0]#011train-rmse:0.79014#011validation-rmse:0.78483
[1]#011train-rmse:0.69008#011validation-rmse:0.69400
[2]#011train-rmse:0.61087#011validation-rmse:0.62580
[3]#011train-rmse:0.55353#011validation-rmse:0.57829
[4]#011train-rmse:0.50958#011validation-rmse:0.54266
[5]#011train-rmse:0.47277#011validation-rmse:0.51461
[6]#011train-rmse:0.44566#011validation-rmse:0.49453
[7]#011train-rmse:0.42497#011validation-rmse:0.47962
[8]#011train-rmse:0.40860#011validation-rmse:0.46705
[9]#011train-rmse:0.39718#011validation-rmse:0.46049
[10]#011train-rmse:0.38588#011validation-rmse:0.45371
[11]#011train-rmse:0.37803#011validation-rmse:0.44784
[12]#011train-rmse:0.37213#011validation-rmse:0.44465
[13]#011train-rmse:0.36463#011validation-rmse:0.44022
[14]#011train-rmse:0.36064#011validation-rmse:0.43627
[15]#011train-rmse:0.35529#011validation-rmse:0.43212
[16]#011train-rmse:0.35148#011validation-rmse:0.43007
[17]#011train-rmse:0.34854#011validation-rmse:0.42757
[18]#011train-rmse:0.34676#011validation-rmse:0.42632
[19]#011train-rmse:0.34477#011validation-rmse:0.42534
[20]#011train-rmse:0.34297#011validation-rmse:0.42405
[21]#011train-rmse:0.34094#011validation-rmse:0.42318
[22]#011train-rmse:0.33841#011validation-rmse:0.42140
[23]#011train-rmse:0.33624#011validation-rmse:0.42078
[24]#011train-rmse:0.33624#011validation-rmse:0.42078
[25]#011train-rmse:0.33382#011validation-rmse:0.41874
[26]#011train-rmse:0.33209#011validation-rmse:0.41872
[27]#011train-rmse:0.32774#011validation-rmse:0.41662
[28]#011train-rmse:0.32774#011validation-rmse:0.41662
[29]#011train-rmse:0.32775#011validation-rmse:0.41663
[30]#011train-rmse:0.32506#011validation-rmse:0.41543
[31]#011train-rmse:0.32506#011validation-rmse:0.41543
[32]#011train-rmse:0.32506#011validation-rmse:0.41543
[33]#011train-rmse:0.32506#011validation-rmse:0.41543
[34]#011train-rmse:0.32506#011validation-rmse:0.41543
[35]#011train-rmse:0.32506#011validation-rmse:0.41543
[36]#011train-rmse:0.32506#011validation-rmse:0.41543
[37]#011train-rmse:0.32506#011validation-rmse:0.41543
[38]#011train-rmse:0.32506#011validation-rmse:0.41543
[39]#011train-rmse:0.32506#011validation-rmse:0.41543
[40]#011train-rmse:0.32506#011validation-rmse:0.41543
[41]#011train-rmse:0.32506#011validation-rmse:0.41544
[42]#011train-rmse:0.32506#011validation-rmse:0.41544
[43]#011train-rmse:0.32295#011validation-rmse:0.41409
[44]#011train-rmse:0.32158#011validation-rmse:0.41344
[45]#011train-rmse:0.32158#011validation-rmse:0.41343
[46]#011train-rmse:0.32158#011validation-rmse:0.41343
[47]#011train-rmse:0.32158#011validation-rmse:0.41343
[48]#011train-rmse:0.32158#011validation-rmse:0.41343
[49]#011train-rmse:0.32158#011validation-rmse:0.41343
[50]#011train-rmse:0.31999#011validation-rmse:0.41251
[51]#011train-rmse:0.31999#011validation-rmse:0.41251
[52]#011train-rmse:0.31999#011validation-rmse:0.41251
[53]#011train-rmse:0.32000#011validation-rmse:0.41251
[54]#011train-rmse:0.31999#011validation-rmse:0.41251
[55]#011train-rmse:0.31999#011validation-rmse:0.41251
[56]#011train-rmse:0.31999#011validation-rmse:0.41251
[57]#011train-rmse:0.31999#011validation-rmse:0.41251
[58]#011train-rmse:0.31999#011validation-rmse:0.41251
[59]#011train-rmse:0.31999#011validation-rmse:0.41251
[60]#011train-rmse:0.31923#011validation-rmse:0.41215
[61]#011train-rmse:0.31924#011validation-rmse:0.41215
[62]#011train-rmse:0.31923#011validation-rmse:0.41215
[63]#011train-rmse:0.31923#011validation-rmse:0.41215
[64]#011train-rmse:0.31839#011validation-rmse:0.41165
[65]#011train-rmse:0.31680#011validation-rmse:0.41002
[66]#011train-rmse:0.31680#011validation-rmse:0.41002
[67]#011train-rmse:0.31680#011validation-rmse:0.41002
[68]#011train-rmse:0.31680#011validation-rmse:0.41002
[69]#011train-rmse:0.31514#011validation-rmse:0.41000
[70]#011train-rmse:0.31514#011validation-rmse:0.41000
[71]#011train-rmse:0.31515#011validation-rmse:0.40999
[72]#011train-rmse:0.31515#011validation-rmse:0.40999
[73]#011train-rmse:0.31515#011validation-rmse:0.40999
[74]#011train-rmse:0.31515#011validation-rmse:0.40999
[75]#011train-rmse:0.31514#011validation-rmse:0.41000
[76]#011train-rmse:0.31515#011validation-rmse:0.41001
[77]#011train-rmse:0.31515#011validation-rmse:0.41000
[78]#011train-rmse:0.31515#011validation-rmse:0.41000
[79]#011train-rmse:0.31515#011validation-rmse:0.41000
[80]#011train-rmse:0.31514#011validation-rmse:0.41000
[81]#011train-rmse:0.31514#011validation-rmse:0.41000
[82]#011train-rmse:0.31514#011validation-rmse:0.41000
[83]#011train-rmse:0.31515#011validation-rmse:0.40999
[84]#011train-rmse:0.31514#011validation-rmse:0.40999
[85]#011train-rmse:0.31515#011validation-rmse:0.40999
[86]#011train-rmse:0.31514#011validation-rmse:0.41000
[87]#011train-rmse:0.31514#011validation-rmse:0.41000
[88]#011train-rmse:0.31514#011validation-rmse:0.41000
[89]#011train-rmse:0.31514#011validation-rmse:0.40999
[90]#011train-rmse:0.31514#011validation-rmse:0.41000
[91]#011train-rmse:0.31308#011validation-rmse:0.40913
[92]#011train-rmse:0.31308#011validation-rmse:0.40913
[93]#011train-rmse:0.31308#011validation-rmse:0.40913
[94]#011train-rmse:0.31308#011validation-rmse:0.40913
[95]#011train-rmse:0.31308#011validation-rmse:0.40913
[96]#011train-rmse:0.31308#011validation-rmse:0.40913
[97]#011train-rmse:0.31308#011validation-rmse:0.40913
[98]#011train-rmse:0.31308#011validation-rmse:0.40913
[99]#011train-rmse:0.31308#011validation-rmse:0.40913
[17:54:40] WARNING: ../src/objective/regression_obj.cu:174: reg:linear is now deprecated in favor of reg:squarederror.

2021-01-05 17:54:57 Uploading - Uploading generated training model
2021-01-05 17:54:57 Completed - Training job completed
Training seconds: 46
Billable seconds: 46
predictor = estimator.deploy(
    initial_instance_count=1, 
    instance_type='ml.t2.medium',
    serializer=sagemaker.serializers.CSVSerializer(), wait=True)
---------------------!
endpoint_name=predictor.endpoint_name
#predictor.endpoint_name
#Store the endpoint name for later cleanup 
%store endpoint_name
endpoint_name
Stored 'endpoint_name' (str)
'sagemaker-xgboost-2021-01-05-17-55-28-234'

(TESTING PURPOSE) Now to check that our endpoint is working, let's call it directly with a record from our test hold-out set.

# Testing code for endpoint
payload_df = df.drop(['target'], axis=1)
payload = payload_df.head(1).to_csv(index=False, header=False).strip()
payload
'0.528384279,0.467741935,0.347826087,0.120689655,0.481481481,0.6521739129999999,0.222222222,0.89211593,0.815234731,0.891824174,0.826809847,0.818747008,0.790460807,0.845313157,0.8135465000000001,0.952188843,0.966913627,0.001595844,0.031735957,0.407821166,0.4427397,0.906654154,0.7025761309999999,0.0,0.0,0.6677419689999999,0.6071359479999999,0.6016636639999999,0.6008397089999999,0.6265824729999999,0.65160482,0.695344011,0.641205199,0.352858223,0.362426861,0.495575534,0.288251453,0.507363451,0.246757564,0.422013598,0.27402085600000003,0.7520242079999999,0.767547988,0.247975792,0.273029205,0.37539531,0.20433238,0.309886113,0.304407087,0.238270631,0.221075679,0.236838573,0.262799678,0.334076875,0.332396145,0.003750389,0.005742277,0.475591607,0.8703220690000001,0.449176795,0.299913568,0.321962498,0.322896068,0.317556703,0.320800742,0.312070381,0.313770855,0.313072295,0.31379601100000004,0.780272629,0.7256131259999999,0.533413581,0.561219567,0.567581641,0.5251290679999999,0.587453926,0.597155654,0.654579548,0.658859218,0.656066615,0.6460508970000001,0.678739764,0.694673013,0.73408697,0.734159693,0.06496118,0.024459304,0.356061856,0.375025372,0.376197507,0.368124987,0.33101366600000004,0.332998568,0.310408517,0.304687332,0.932074385,0.912608131,0.039718891,0.13091892800000002,0.273478774,0.351279113,0.00985079,0.06804862,0.77932029,0.889879199,0.892085206,0.8359682159999999,0.551347335,0.34291684100000003,0.83160143,0.801750414,0.37722755,0.436862148,0.261414554,0.090391326,0.770538244,0.422222222,0.460606061,0.651785714,0.28571428600000004,0.432989691,0.582116788,0.642222222,0.553800982,0.100719424,0.456521739,0.3917525770000001,0.423580786,1.0,1609311810.4112825'
float(predictor.predict(payload).decode('utf-8'))
1.9875482320785522
!rm train.csv
!rm val.csv

Making predictions using streaming aggregated features

Now,we will input data to our input Kinesis stream and show that we can detect output.

Ensure Lambda knows which SageMaker endpoint to use

Our Lambda function that invokes the endpoint thus needs a way to know the endpoint name. We handle that through a Lambda environment variable.

This section of code simply takes care of updating end ENDPOINT_NAME Lambda environment variable. It is important to do so before we start feeding transactions into our Kinesis stream.

print(f'Updating Lambda to use endpoint: {endpoint_name} for ARN: {lambda_to_model_arn}')

variables = lambda_client.get_function_configuration(FunctionName=lambda_to_model_arn)['Environment']['Variables']
variables['ENDPOINT_NAME'] = endpoint_name
resp = lambda_client.update_function_configuration(
    FunctionName=lambda_to_model_arn,
      Environment={
        'Variables': variables
    }
)
Updating Lambda to use endpoint: sagemaker-xgboost-2021-01-05-17-55-28-234 for ARN: arn:aws:lambda:us-east-1:082830052325:function:HeidelbergInvokeFraudEndpointLambda3

Lambda functions

  1. InvokeFraudEndpoint (https://console.aws.amazon.com/lambda/home?region=us-east-1#/functions/HeidelbergInvokeFraudEndpointLambda3?tab=configuration)
  2. StreamingInjectAggregateFeature( https://console.aws.amazon.com/lambda/home?region=us-east-1#/functions/HeidelbergStreamingIngestAggFeatures3?tab=configuration)
  3. Lambdatoputincomingdata ( https://console.aws.amazon.com/lambda/home?region=us-east-1#/functions/lambda_mlops?tab=configuration)

Template (CLoudFormation Stack)

https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/template?filteringText=&filteringStatus=active&viewNested=true&hideStacks=false&stackId=arn%3Aaws%3Acloudformation%3Aus-east-1%3A082830052325%3Astack%2Fheidelberg-mlops-stack-3%2Ffc283870-49d8-11eb-b6cb-0ea6aa6eaed9

LogStream (CloudWatch)

ENd point logstream,

https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#logsV2:log-groups/log-group/$252Faws$252Flambda$252FHeidelbergInvokeFraudEndpointLambda3

Update FeatureStore Logstream

https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#logsV2:log-groups/log-group/$252Faws$252Flambda$252FHeidelbergStreamingIngestAggFeatures3

Streaming lambda

https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#logsV2:log-groups/log-group/$252Faws$252Flambda$252Flambda_mlops

KDA Application

https://console.aws.amazon.com/kinesisanalytics/home?region=us-east-1#/wizard/hub?applicationName=heidelberg-mlops-app

Real time lambda update s3 bucket

https://s3.console.aws.amazon.com/s3/buckets/lambda-trigger-mlops?region=us-east-1&tab=objects