!pip install witwidget
Requirement already satisfied: witwidget in /opt/conda/lib/python3.7/site-packages (1.7.0)
Requirement already satisfied: six>=1.12.0 in /opt/conda/lib/python3.7/site-packages (from witwidget) (1.14.0)
Requirement already satisfied: tensorflow>=1.12.1 in /opt/conda/lib/python3.7/site-packages (from witwidget) (2.4.0)
Requirement already satisfied: oauth2client>=4.1.3 in /opt/conda/lib/python3.7/site-packages (from witwidget) (4.1.3)
Requirement already satisfied: jupyter<2,>=1.0 in /opt/conda/lib/python3.7/site-packages (from witwidget) (1.0.0)
Requirement already satisfied: absl-py>=0.4 in /opt/conda/lib/python3.7/site-packages (from witwidget) (0.11.0)
Requirement already satisfied: google-api-python-client>=1.7.8 in /opt/conda/lib/python3.7/site-packages (from witwidget) (1.12.8)
Requirement already satisfied: ipywidgets>=7.0.0 in /opt/conda/lib/python3.7/site-packages (from witwidget) (7.5.1)
Requirement already satisfied: termcolor~=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (1.1.0)
Requirement already satisfied: flatbuffers~=1.12.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (1.12)
Requirement already satisfied: typing-extensions~=3.7.4 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (3.7.4.3)
Requirement already satisfied: google-pasta~=0.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (0.2.0)
Requirement already satisfied: numpy~=1.19.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (1.19.4)
Requirement already satisfied: wheel~=0.35 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (0.36.2)
Requirement already satisfied: gast==0.3.3 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (0.3.3)
Requirement already satisfied: astunparse~=1.6.3 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (1.6.3)
Requirement already satisfied: tensorflow-estimator<2.5.0,>=2.4.0rc0 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (2.4.0)
Requirement already satisfied: wrapt~=1.12.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (1.12.1)
Requirement already satisfied: keras-preprocessing~=1.1.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (1.1.2)
Requirement already satisfied: tensorboard~=2.4 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (2.4.0)
Requirement already satisfied: grpcio~=1.32.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (1.32.0)
Requirement already satisfied: h5py~=2.10.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (2.10.0)
Requirement already satisfied: protobuf>=3.9.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (3.14.0)
Requirement already satisfied: opt-einsum~=3.3.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow>=1.12.1->witwidget) (3.3.0)
Requirement already satisfied: pyasn1-modules>=0.0.5 in /opt/conda/lib/python3.7/site-packages (from oauth2client>=4.1.3->witwidget) (0.2.8)
Requirement already satisfied: httplib2>=0.9.1 in /opt/conda/lib/python3.7/site-packages (from oauth2client>=4.1.3->witwidget) (0.18.1)
Requirement already satisfied: rsa>=3.1.4 in /opt/conda/lib/python3.7/site-packages (from oauth2client>=4.1.3->witwidget) (4.5)
Requirement already satisfied: pyasn1>=0.1.7 in /opt/conda/lib/python3.7/site-packages (from oauth2client>=4.1.3->witwidget) (0.4.8)
Requirement already satisfied: qtconsole in /opt/conda/lib/python3.7/site-packages (from jupyter<2,>=1.0->witwidget) (4.6.0)
Requirement already satisfied: nbconvert in /opt/conda/lib/python3.7/site-packages (from jupyter<2,>=1.0->witwidget) (5.6.1)
Requirement already satisfied: notebook in /opt/conda/lib/python3.7/site-packages (from jupyter<2,>=1.0->witwidget) (6.0.3)
Requirement already satisfied: ipykernel in /opt/conda/lib/python3.7/site-packages (from jupyter<2,>=1.0->witwidget) (5.1.4)
Requirement already satisfied: jupyter-console in /opt/conda/lib/python3.7/site-packages (from jupyter<2,>=1.0->witwidget) (6.1.0)
Requirement already satisfied: google-auth-httplib2>=0.0.3 in /opt/conda/lib/python3.7/site-packages (from google-api-python-client>=1.7.8->witwidget) (0.0.4)
Requirement already satisfied: google-auth>=1.16.0 in /opt/conda/lib/python3.7/site-packages (from google-api-python-client>=1.7.8->witwidget) (1.24.0)
Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /opt/conda/lib/python3.7/site-packages (from google-api-python-client>=1.7.8->witwidget) (3.0.1)
Requirement already satisfied: google-api-core<2dev,>=1.21.0 in /opt/conda/lib/python3.7/site-packages (from google-api-python-client>=1.7.8->witwidget) (1.24.1)
Requirement already satisfied: nbformat>=4.2.0 in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.0.0->witwidget) (5.0.4)
Requirement already satisfied: ipython>=4.0.0; python_version >= "3.3" in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.0.0->witwidget) (7.12.0)
Requirement already satisfied: widgetsnbextension~=3.5.0 in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.0.0->witwidget) (3.5.1)
Requirement already satisfied: traitlets>=4.3.1 in /opt/conda/lib/python3.7/site-packages (from ipywidgets>=7.0.0->witwidget) (4.3.3)
Requirement already satisfied: werkzeug>=0.11.15 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (1.0.0)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (1.7.0)
Requirement already satisfied: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (3.3.3)
Requirement already satisfied: setuptools>=41.0.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (45.2.0.post20200210)
Requirement already satisfied: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (2.22.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (0.4.2)
Requirement already satisfied: jupyter-client>=4.1 in /opt/conda/lib/python3.7/site-packages (from qtconsole->jupyter<2,>=1.0->witwidget) (5.3.4)
Requirement already satisfied: ipython-genutils in /opt/conda/lib/python3.7/site-packages (from qtconsole->jupyter<2,>=1.0->witwidget) (0.2.0)
Requirement already satisfied: jupyter-core in /opt/conda/lib/python3.7/site-packages (from qtconsole->jupyter<2,>=1.0->witwidget) (4.6.1)
Requirement already satisfied: pygments in /opt/conda/lib/python3.7/site-packages (from qtconsole->jupyter<2,>=1.0->witwidget) (2.5.2)
Requirement already satisfied: testpath in /opt/conda/lib/python3.7/site-packages (from nbconvert->jupyter<2,>=1.0->witwidget) (0.4.4)
Requirement already satisfied: bleach in /opt/conda/lib/python3.7/site-packages (from nbconvert->jupyter<2,>=1.0->witwidget) (3.1.0)
Requirement already satisfied: entrypoints>=0.2.2 in /opt/conda/lib/python3.7/site-packages (from nbconvert->jupyter<2,>=1.0->witwidget) (0.3)
Requirement already satisfied: jinja2>=2.4 in /opt/conda/lib/python3.7/site-packages (from nbconvert->jupyter<2,>=1.0->witwidget) (2.11.1)
Requirement already satisfied: mistune<2,>=0.8.1 in /opt/conda/lib/python3.7/site-packages (from nbconvert->jupyter<2,>=1.0->witwidget) (0.8.4)
Requirement already satisfied: pandocfilters>=1.4.1 in /opt/conda/lib/python3.7/site-packages (from nbconvert->jupyter<2,>=1.0->witwidget) (1.4.2)
Requirement already satisfied: defusedxml in /opt/conda/lib/python3.7/site-packages (from nbconvert->jupyter<2,>=1.0->witwidget) (0.6.0)
Requirement already satisfied: Send2Trash in /opt/conda/lib/python3.7/site-packages (from notebook->jupyter<2,>=1.0->witwidget) (1.5.0)
Requirement already satisfied: tornado>=5.0 in /opt/conda/lib/python3.7/site-packages (from notebook->jupyter<2,>=1.0->witwidget) (6.0.3)
Requirement already satisfied: pyzmq>=17 in /opt/conda/lib/python3.7/site-packages (from notebook->jupyter<2,>=1.0->witwidget) (18.1.1)
Requirement already satisfied: terminado>=0.8.1 in /opt/conda/lib/python3.7/site-packages (from notebook->jupyter<2,>=1.0->witwidget) (0.8.3)
Requirement already satisfied: prometheus-client in /opt/conda/lib/python3.7/site-packages (from notebook->jupyter<2,>=1.0->witwidget) (0.7.1)
Requirement already satisfied: prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from jupyter-console->jupyter<2,>=1.0->witwidget) (3.0.3)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /opt/conda/lib/python3.7/site-packages (from google-auth>=1.16.0->google-api-python-client>=1.7.8->witwidget) (4.2.0)
Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /opt/conda/lib/python3.7/site-packages (from google-api-core<2dev,>=1.21.0->google-api-python-client>=1.7.8->witwidget) (1.52.0)
Requirement already satisfied: pytz in /opt/conda/lib/python3.7/site-packages (from google-api-core<2dev,>=1.21.0->google-api-python-client>=1.7.8->witwidget) (2019.3)
Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /opt/conda/lib/python3.7/site-packages (from nbformat>=4.2.0->ipywidgets>=7.0.0->witwidget) (3.2.0)
Requirement already satisfied: pexpect; sys_platform != "win32" in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets>=7.0.0->witwidget) (4.8.0)
Requirement already satisfied: decorator in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets>=7.0.0->witwidget) (4.4.1)
Requirement already satisfied: jedi>=0.10 in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets>=7.0.0->witwidget) (0.14.1)
Requirement already satisfied: backcall in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets>=7.0.0->witwidget) (0.1.0)
Requirement already satisfied: pickleshare in /opt/conda/lib/python3.7/site-packages (from ipython>=4.0.0; python_version >= "3.3"->ipywidgets>=7.0.0->witwidget) (0.7.5)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /opt/conda/lib/python3.7/site-packages (from markdown>=2.6.8->tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (1.5.0)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (2019.11.28)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (1.25.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (2.8)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /opt/conda/lib/python3.7/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (1.3.0)
Requirement already satisfied: python-dateutil>=2.1 in /opt/conda/lib/python3.7/site-packages (from jupyter-client>=4.1->qtconsole->jupyter<2,>=1.0->witwidget) (2.8.1)
Requirement already satisfied: webencodings in /opt/conda/lib/python3.7/site-packages (from bleach->nbconvert->jupyter<2,>=1.0->witwidget) (0.5.1)
Requirement already satisfied: MarkupSafe>=0.23 in /opt/conda/lib/python3.7/site-packages (from jinja2>=2.4->nbconvert->jupyter<2,>=1.0->witwidget) (1.1.1)
Requirement already satisfied: wcwidth in /opt/conda/lib/python3.7/site-packages (from prompt-toolkit!=3.0.0,!=3.0.1,<3.1.0,>=2.0.0->jupyter-console->jupyter<2,>=1.0->witwidget) (0.1.8)
Requirement already satisfied: attrs>=17.4.0 in /opt/conda/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets>=7.0.0->witwidget) (19.3.0)
Requirement already satisfied: pyrsistent>=0.14.0 in /opt/conda/lib/python3.7/site-packages (from jsonschema!=2.5.0,>=2.4->nbformat>=4.2.0->ipywidgets>=7.0.0->witwidget) (0.15.7)
Requirement already satisfied: ptyprocess>=0.5 in /opt/conda/lib/python3.7/site-packages (from pexpect; sys_platform != "win32"->ipython>=4.0.0; python_version >= "3.3"->ipywidgets>=7.0.0->witwidget) (0.6.0)
Requirement already satisfied: parso>=0.5.0 in /opt/conda/lib/python3.7/site-packages (from jedi>=0.10->ipython>=4.0.0; python_version >= "3.3"->ipywidgets>=7.0.0->witwidget) (0.5.2)
Requirement already satisfied: zipp>=0.5 in /opt/conda/lib/python3.7/site-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (2.2.0)
Requirement already satisfied: oauthlib>=3.0.0 in /opt/conda/lib/python3.7/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.4->tensorflow>=1.12.1->witwidget) (3.1.0)

Install ndoejs via conda

!conda install nodejs --yes
Collecting package metadata (current_repodata.json): done
Solving environment: done

# All requested packages already installed.

Extensions for widgets

!jupyter nbextension install --py --symlink --sys-prefix witwidget
!jupyter nbextension enable --py --sys-prefix witwidget
2021-01-04 04:48:30.158764: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2021-01-04 04:48:30.158802: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Installing /opt/conda/lib/python3.7/site-packages/witwidget/static -> wit-widget
- Validating: OK

    To initialize this nbextension in the browser every time the notebook (or other app) loads:
    
          jupyter nbextension enable witwidget --py --sys-prefix
    
2021-01-04 04:48:35.959057: W tensorflow/stream_executor/platform/default/dso_loader.cc:60] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2021-01-04 04:48:35.959097: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Enabling notebook extension wit-widget/extension...
      - Validating: OK
!jupyter labextension install wit-widget
!jupyter labextension install jupyter-widgets/jupyterlab-manager --yes
Building jupyterlab assets (build:prod:minimize)
Install labextension(s)

 Usage

    jupyter labextension install [--pin-version-as <alias,...>] <package...>

This installs JupyterLab extensions similar to yarn add or npm install.

Pass a list of comma seperate names to the --pin-version-as flag to use as
alises for the packages providers. This is useful to install multiple versions
of the same extension. These can be uninstalled with the alias you provided to
the flag, similar to the "alias" feature of yarn add.

Options
-------

Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.

--debug
    set log level to logging.DEBUG (maximize logging output)
--generate-config
    generate default config file
-y
    Answer yes to any questions instead of prompting.
--no-build
    Defer building the app after the action.
--clean
    Cleanup intermediate files after the action.
--log-level=<Enum> (Application.log_level)
    Default: 30
    Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')
    Set the log level by value or name.
--config=<Unicode> (JupyterApp.config_file)
    Default: ''
    Full path of a config file.
--app-dir=<Unicode> (BaseExtensionApp.app_dir)
    Default: ''
    The app directory to target
--dev-build=<Bool> (BaseExtensionApp.dev_build)
    Default: None
    Whether to build in dev mode. Defaults to True (dev mode) if there are any
    locally linked extensions, else defaults to False (prod mode).
--minimize=<Bool> (BaseExtensionApp.minimize)
    Default: True
    Whether to use a minifier during the Webpack build (defaults to True). Only
    affects production builds.
--debug-log-path=<Unicode> (DebugLogFileMixin.debug_log_path)
    Default: ''
    Path to use for the debug log file
--pin-version-as=<Unicode> (InstallLabExtensionApp.pin)
    Default: ''
    Pin this version with a certain alias

To see all available configurables, use `--help-all`

Bad config encountered during initialization:
Unrecognized flag: '--yes'

Imports

from witwidget.notebook.visualization import WitWidget, WitConfigBuilder

Already Build Model

PROJECT_ID = 'YOUR_PROJECT_ID'
MODEL_NAME = 'YOUR_MODEL_NAME'
VERSION_NAME = 'YOUR_VERSION_NAME'
TARGET_FEATURE = 'mortgage_status'
LABEL_VOCAB = ['denied', 'approved']

config_builder = (WitConfigBuilder(test_examples.tolist(), features.columns.tolist() + ['mortgage_status'])
  .set_ai_platform_model(PROJECT_ID, MODEL_NAME, VERSION_NAME, adjust_prediction=adjust_prediction)
  .set_target_feature(TARGET_FEATURE)
  .set_label_vocab(LABEL_VOCAB))
WitWidget(config_builder, height=800)

Define Helper function

import pandas as pd
import numpy as np
import tensorflow as tf
import functools

# Creates a tf feature spec from the dataframe and columns specified.
def create_feature_spec(df, columns=None):
    feature_spec = {}
    if columns == None:
        columns = df.columns.values.tolist()
    for f in columns:
        if df[f].dtype is np.dtype(np.int64) or df[f].dtype is np.dtype(np.int32):
            feature_spec[f] = tf.io.FixedLenFeature(shape=(), dtype=tf.int64)
        elif df[f].dtype is np.dtype(np.float64):
            feature_spec[f] = tf.io.FixedLenFeature(shape=(), dtype=tf.float32)
        else:
            feature_spec[f] = tf.io.FixedLenFeature(shape=(), dtype=tf.string)
    return feature_spec

# Creates simple numeric and categorical feature columns from a feature spec and a
# list of columns from that spec to use.
#
# NOTE: Models might perform better with some feature engineering such as bucketed
# numeric columns and hash-bucket/embedding columns for categorical features.
def create_feature_columns(columns, feature_spec):
    ret = []
    for col in columns:
        if feature_spec[col].dtype is tf.int64 or feature_spec[col].dtype is tf.float32:
            ret.append(tf.feature_column.numeric_column(col))
        else:
            ret.append(tf.feature_column.indicator_column(
                tf.feature_column.categorical_column_with_vocabulary_list(col, list(df[col].unique()))))
    return ret

# An input function for providing input to a model from tf.Examples
def tfexamples_input_fn(examples, feature_spec, label, mode=tf.estimator.ModeKeys.EVAL,
                       num_epochs=None, 
                       batch_size=64):
    def ex_generator():
        for i in range(len(examples)):
            yield examples[i].SerializeToString()
    dataset = tf.data.Dataset.from_generator(
      ex_generator, tf.dtypes.string, tf.TensorShape([]))
    if mode == tf.estimator.ModeKeys.TRAIN:
        dataset = dataset.shuffle(buffer_size=2 * batch_size + 1)
    dataset = dataset.batch(batch_size)
    dataset = dataset.map(lambda tf_example: parse_tf_example(tf_example, label, feature_spec))
    dataset = dataset.repeat(num_epochs)
    return dataset

# Parses Tf.Example protos into features for the input function.
def parse_tf_example(example_proto, label, feature_spec):
    parsed_features = tf.io.parse_example(serialized=example_proto, features=feature_spec)
    target = parsed_features.pop(label)
    return parsed_features, target

# Converts a dataframe into a list of tf.Example protos.
def df_to_examples(df, columns=None):
    examples = []
    if columns == None:
        columns = df.columns.values.tolist()
    for index, row in df.iterrows():
        example = tf.train.Example()
        for col in columns:
            if df[col].dtype is np.dtype(np.int64) or df[col].dtype is np.dtype(np.int32):
                example.features.feature[col].int64_list.value.append(int(row[col]))
            elif df[col].dtype is np.dtype(np.float64):
                example.features.feature[col].float_list.value.append(row[col])
            elif row[col] == row[col]:
                example.features.feature[col].bytes_list.value.append(row[col].encode('utf-8'))
        examples.append(example)
    return examples

# Converts a dataframe column into a column of 0's and 1's based on the provided test.
# Used to force label columns to be numeric for binary classification using a TF estimator.
def make_label_column_numeric(df, label_column, test):
  df[label_column] = np.where(test(df[label_column]), 1, 0)

Read training dataset and stored in df

import boto3
import sagemaker
import io
s3_bucket = sagemaker.Session().default_bucket()
s3_prefix = 'heidelberg/data'
s3_filename = "transformed.csv"



s3 = boto3.resource('s3')
obj = s3.Object(s3_bucket, s3_prefix+'/'+s3_filename)
body = obj.get()['Body'].read()
df=pd.read_csv(io.BytesIO(body))

Specify input columns and column to predict

features=list(df)
features=features[1:]
import numpy as np

# Set the column in the dataset you wish for the model to predict
label_column = 'target'

# Set list of all columns from the dataset we will use for model input.
input_features = features

# Create a list containing all input features and the label column
features_and_labels = input_features + [label_column]

Convert dataset to tf.Example protos

examples = df_to_examples(df)

Create and Train the Regressor

num_steps = 200  #@param {type: "number"}

# Create a feature spec for the classifier
feature_spec = create_feature_spec(df, features_and_labels)

# Define and train the classifier
train_inpf = functools.partial(tfexamples_input_fn, examples, feature_spec, label_column)
regressor = tf.estimator.LinearRegressor(
    feature_columns=create_feature_columns(input_features, feature_spec))
regressor.train(train_inpf, steps=num_steps)
INFO:tensorflow:Using default config.
WARNING:tensorflow:Using temporary folder as model directory: /tmp/tmpv78wrrdi
INFO:tensorflow:Using config: {'_model_dir': '/tmp/tmpv78wrrdi', '_tf_random_seed': None, '_save_summary_steps': 100, '_save_checkpoints_steps': None, '_save_checkpoints_secs': 600, '_session_config': allow_soft_placement: true
graph_options {
  rewrite_options {
    meta_optimizer_iterations: ONE
  }
}
, '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1}
WARNING:tensorflow:From /opt/conda/lib/python3.7/site-packages/tensorflow/python/training/training_util.py:236: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version.
Instructions for updating:
Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts.
WARNING:tensorflow:From <ipython-input-5-471492688c87>:45: calling DatasetV2.from_generator (from tensorflow.python.data.ops.dataset_ops) with output_types is deprecated and will be removed in a future version.
Instructions for updating:
Use output_signature instead
WARNING:tensorflow:From <ipython-input-5-471492688c87>:45: calling DatasetV2.from_generator (from tensorflow.python.data.ops.dataset_ops) with output_shapes is deprecated and will be removed in a future version.
Instructions for updating:
Use output_signature instead
INFO:tensorflow:Calling model_fn.
WARNING:tensorflow:From /opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/optimizer_v2/ftrl.py:134: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
INFO:tensorflow:Done calling model_fn.
INFO:tensorflow:Create CheckpointSaverHook.
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Running local_init_op.
INFO:tensorflow:Done running local_init_op.
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0...
INFO:tensorflow:Saving checkpoints for 0 into /tmp/tmpv78wrrdi/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0...
INFO:tensorflow:loss = 3.2560234, step = 0
INFO:tensorflow:global_step/sec: 30.0161
INFO:tensorflow:loss = 0.7137667, step = 100 (3.332 sec)
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 200...
INFO:tensorflow:Saving checkpoints for 200 into /tmp/tmpv78wrrdi/model.ckpt.
INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 200...
INFO:tensorflow:Loss for final step: 0.87051874.
<tensorflow_estimator.python.estimator.canned.linear.LinearRegressorV2 at 0x7f30b4576990>

Invoke What-If Tool for test data and the trained model

num_datapoints = 2000  #@param {type: "number"}
tool_height_in_px = 1000  #@param {type: "number"}

from witwidget.notebook.visualization import WitConfigBuilder
from witwidget.notebook.visualization import WitWidget

# Load up the test dataset


# test_csv_path = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test'
# test_df = pd.read_csv(test_csv_path, names=csv_columns, skipinitialspace=True,
#   skiprows=1)
test_examples = df_to_examples(df[0:num_datapoints])

# Setup the tool with the test examples and the trained classifier
config_builder = WitConfigBuilder(test_examples[0:num_datapoints]).set_estimator_and_feature_spec(
    regressor, feature_spec).set_model_type('regression')
WitWidget(config_builder, height=tool_height_in_px)

Exploration ideas

  • Create a scatter plot of age on the X-axis by inference value on the Y-axis to see how the predicted age compares to the actual age for all test examples.

    • How does the model do overall? Is there a pattern to the errors it creates?
  • In the "Performance" tab, set the ground truth feature to "age". You can now see a simple breakdown of the mean error, mean absolute error, and mean squared error over the entire test set. Additionally, you can set a scatter axis or binning option to be any of those three calculations (i.e. you can make a scatter plot of age vs inference error).

  • Replace the LinearRegressor with a DNNRegressor (you'll need to decide on the size and number of the hidden layers). Can you create a better model? Does this model have the same pattern of performance issues as the previous model, or are there errors more evenly distributed?

    • If you look at the WIT Model Comparison notebook, you can see how to compare the two models on a single WIT.
  • In the "Performance" tab, slice the dataset by any feature or pair of features. Are there feature values for which the model seems to perform better or worse on?