In [1]:
import warnings
warnings.filterwarnings('ignore')
In [2]:
%matplotlib inline
%pylab inline
In [3]:
import pandas as pd
print(pd.__version__)
In [4]:
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
print(tf.__version__)
In [5]:
import keras
print(keras.__version__)
In [6]:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.datasets import make_blobs
# http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html#sklearn.datasets.make_blobs
# https://www.welt.de/motor/news/article156991316/Unfallstatistik-2015.html
# http://www.openculture.com/2017/12/why-incompetent-people-think-theyre-amazing.html
# 0: young drivers with fast cars: red
# 1: reasonable drivers: green
# 2: a little bit older, more kilometers, general noise: yellow
# 3: really old drivers: red
# 4: young drivers: red
# 5: another green just to have a counter part to all the red ones: green
# 6: people who do not drive a lot: green
# 7: people who drive a lot: yellow
# 8: young people with slow cars: yellow
centers = [(200, 35, 50), (160, 50, 25), (170, 55, 30), (170, 75, 20), (170, 30, 30), (190, 45, 40), (160, 40, 15), (180, 50, 45), (140, 25, 15)]
cluster_std = [4, 9, 18, 8, 9, 5, 8, 12, 5]
X, y = make_blobs(n_samples=1500, n_features=3, centers=centers, random_state=42, cluster_std = cluster_std)
# http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_classification.html
# X, y = make_classification(n_features=3, n_redundant=0, n_informative=3,
# n_clusters_per_class=2, n_classes=3, random_state=42)
feature_names = ['max speed', 'age' ,'thousand km per year']
df = pd.DataFrame(X, columns=feature_names)
df = df.round()
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.clip.html
df['max speed'] = df['max speed'].clip(90,400)
df['age'] = df['age'].clip(18,90)
df['thousand km per year'] = df['thousand km per year'].clip(5,500)
X = df.as_matrix()
# merges clusters into one group
for group in np.nditer(y, op_flags=['readwrite']):
if group == 3 or group == 4:
group[...] = 0
if group == 5 or group == 6:
group[...] = 1
if group == 7 or group == 8:
group[...] = 2
In [7]:
from sklearn.model_selection import train_test_split
In [8]:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42, stratify=y)
In [9]:
# tiny little pieces of feature engeneering
from keras.utils.np_utils import to_categorical
num_categories = 3
y_train = to_categorical(y_train, num_categories)
y_test = to_categorical(y_test, num_categories)
In [10]:
X_train.shape, y_train.shape, X_test.shape, y_test.shape
Out[10]:
In [11]:
# ignore this, it is just technical code
# should come from a lib, consider it to appear magically
# http://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
cmap_bold = ListedColormap(['#AA4444', '#006000', '#AAAA00'])
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#FFFFDD'])
font_size=25
def meshGrid(x_data, y_data):
h = 1 # step size in the mesh
x_min, x_max = x_data.min() - 1, x_data.max() + 1
y_min, y_max = y_data.min() - 1, y_data.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
return (xx,yy)
def plotPrediction(model, x_data, y_data, x_label, y_label, colors, title="", mesh=True):
xx,yy = meshGrid(x_data, y_data)
grid_X = np.array(np.c_[yy.ravel(), xx.ravel()])
# print(grid_X)
Z = model.predict(grid_X)
Z = np.argmax(Z, axis=1)
# print(Z)
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(figsize=(20,10))
if mesh:
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.scatter(x_data, y_data, c=np.argmax(colors, axis=1), cmap=cmap_bold, s=80, marker='o')
plt.xlabel(x_label, fontsize=font_size)
plt.ylabel(y_label, fontsize=font_size)
plt.title(title, fontsize=font_size)
In [12]:
X_train_kmh_age = X_train[:, :2]
X_test_kmh_age = X_test[:, :2]
In [13]:
X_train_2_dim = X_train_kmh_age
X_test_2_dim = X_test_kmh_age
In [14]:
from keras.layers import Input
from keras.layers import Dense
from keras.models import Model
from keras.layers import Dropout
drop_out = 0.3
inputs = Input(name='input', shape=(2, ))
x = Dense(100, name='hidden1', activation='sigmoid')(inputs)
x = Dropout(drop_out)(x)
x = Dense(100, name='hidden2', activation='sigmoid')(x)
x = Dropout(drop_out)(x)
x = Dense(100, name='hidden3', activation='sigmoid')(x)
x = Dropout(drop_out)(x)
# x = Dense(100, name='hidden4', activation='sigmoid')(x)
# x = Dropout(drop_out)(x)
# x = Dense(100, name='hidden5', activation='sigmoid')(x)
# x = Dropout(drop_out)(x)
predictions = Dense(3, name='softmax', activation='softmax')(x)
model = Model(input=inputs, output=predictions)
# loss function: http://cs231n.github.io/linear-classify/#softmax
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()
In [15]:
%time model.fit(X_train_2_dim, y_train, epochs=1000, validation_split=0.2, verbose=0, batch_size=100)
Out[15]:
In [16]:
train_loss, train_accuracy = model.evaluate(X_train_2_dim, y_train, batch_size=100)
train_loss, train_accuracy
Out[16]:
In [17]:
plotPrediction(model, X_train_2_dim[:, 1], X_train_2_dim[:, 0],
'Age', 'Max Speed', y_train,
title="Train Data Max Speed vs Age with Classification")
In [18]:
test_loss, test_accuracy = model.evaluate(X_test_2_dim, y_test, batch_size=100)
test_loss, test_accuracy
Out[18]:
In [19]:
plotPrediction(model, X_test_2_dim[:, 1], X_test_2_dim[:, 0],
'Age', 'Max Speed', y_test,
title="Test Data Max Speed vs Age with Prediction")
In [45]:
from keras.layers import Input
from keras.layers import Dense
from keras.models import Model
from keras.layers import Dropout
drop_out = 0.3
inputs = Input(name='input', shape=(3, ))
x = Dense(100, name='hidden1', activation='sigmoid')(inputs)
# x = Dropout(drop_out)(x)
x = Dense(100, name='hidden2', activation='sigmoid')(x)
# x = Dropout(drop_out)(x)
x = Dense(100, name='hidden3', activation='sigmoid')(x)
# x = Dropout(drop_out)(x)
# x = Dense(100, name='hidden4', activation='sigmoid')(x)
# x = Dropout(drop_out)(x)
# x = Dense(100, name='hidden5', activation='sigmoid')(x)
# x = Dropout(drop_out)(x)
predictions = Dense(3, name='softmax', activation='softmax')(x)
model = Model(input=inputs, output=predictions)
# loss function: http://cs231n.github.io/linear-classify/#softmax
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
%time model.fit(X_train, y_train, epochs=1000, validation_split=0.2, verbose=0, batch_size=100)
Out[45]:
In [46]:
train_loss, train_accuracy = model.evaluate(X_train, y_train, batch_size=100)
train_loss, train_accuracy
Out[46]:
In [47]:
test_loss, test_accuracy = model.evaluate(X_test, y_test, batch_size=100)
test_loss, test_accuracy
Out[47]:
In [48]:
!rm -rf tf
In [50]:
import os
from keras import backend as K
# K.clear_session()
K.set_learning_phase(0)
# tf.app.flags.DEFINE_integer('model_version', 1, 'version number of the model.')
# tf.app.flags.DEFINE_string('work_dir', '/tmp', 'Working directory.')
# FLAGS = tf.app.flags.FLAGS
export_path_base = 'tf'
export_path = os.path.join(
tf.compat.as_bytes(export_path_base),
tf.compat.as_bytes(str(FLAGS.model_version)))
sess = K.get_session()
classification_inputs = tf.saved_model.utils.build_tensor_info(model.input)
classification_outputs_scores = tf.saved_model.utils.build_tensor_info(model.output)
from tensorflow.python.saved_model.signature_def_utils_impl import build_signature_def, predict_signature_def
signature = predict_signature_def(inputs={'inputs': model.input},
outputs={'scores': model.output})
builder = tf.saved_model.builder.SavedModelBuilder(export_path)
builder.add_meta_graph_and_variables(
sess,
tags=[tf.saved_model.tag_constants.SERVING],
signature_def_map={
tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature
})
builder.save()
Out[50]:
In [51]:
!ls -lhR tf tf
In [52]:
!saved_model_cli show --dir tf/1 --tag_set serve --signature_def serving_default
In [54]:
!saved_model_cli run --dir tf/1 --tag_set serve --signature_def serving_default --input_exprs 'inputs=[[160.0,46.0,10.0]]'
In [ ]:
# https://cloud.google.com/ml-engine/docs/deploying-models
# gsutil cp -R tf/1 gs://insurance1
# create model and version at https://console.cloud.google.com/mlengine
# gcloud ml-engine predict --model=insurance_estimator --version=keras_v1 --json-instances=./sample_insurance.json
# SCORES
# [0.9954029321670532, 0.004596732556819916, 3.3544753819114703e-07]
In [55]:
prediction = model.predict(X)
y_pred = np.argmax(prediction, axis=1)
y_pred
Out[55]:
In [57]:
y_true = y
y_true
Out[57]:
In [58]:
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_true, y_pred)
cm
Out[58]:
In [59]:
import seaborn as sns
sns.heatmap(cm, annot=True, cmap="YlGnBu")
figure = plt.gcf()
figure.set_size_inches(10, 10)
ax = figure.add_subplot(111)
ax.set_xlabel('Prediction')
ax.set_ylabel('Ground Truth')
Out[59]: