In [1]:
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.estimators import model_fn
In [2]:
# read in some of the data
df = pd.read_csv('../data/facial keypoints training.csv', nrows=5000)
In [3]:
df = df[['left_eye_center_x', 'left_eye_center_y','Image']]
# for now only train on the left eye center
df = df[df['left_eye_center_x'].notnull() & df['left_eye_center_y'].notnull()]
# round the left eye x, y coordinates to integers (could multiply by powers of ten to get higher position resolution)
df[['left_eye_center_x', 'left_eye_center_y']] = df[['left_eye_center_x', 'left_eye_center_y']].round(0)
print(df[['left_eye_center_x', 'left_eye_center_y']].head())
In [4]:
# encode. must give column names if numeric
left_eye_x = pd.get_dummies(df['left_eye_center_x'], columns=['left_eye_center_x'])
left_eye_y = pd.get_dummies(df['left_eye_center_y'], columns=['left_eye_center_y'])
# convert faces to dataframe
faces = df.Image.apply(lambda x: pd.Series(np.fromstring(x, dtype=np.float32, sep=' ')))
In [5]:
# see the results
print(faces.head())
print(faces.shape)
In [6]:
# free space
del df['Image']
faces = faces.as_matrix()
left_eye_x = left_eye_x.as_matrix()
num_labels = left_eye_x.shape[1]
image_size = 96
# have a look
print(faces.shape)
print(left_eye_x.shape)
In [7]:
def model(features, targets, mode, params):
'''model function for estimator'''
weights = tf.Variable(tf.truncated_normal([image_size*image_size, num_labels]))
biases = tf.Variable(tf.zeros([num_labels]))
# loss
logits = tf.matmul(features, weights) + biases
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=targets, logits=logits))
# predictions
train_prediction = tf.nn.softmax(logits)
# saver
saver = tf.train.Saver(tf.global_variables())
#predictions_dict = {"x-coordinate": logits.argmax(axis=1)}
predictions_dict = {"x-coordinate": logits}
train_op = tf.contrib.layers.optimize_loss(
loss=loss,
global_step=tf.contrib.framework.get_global_step(),
learning_rate=params['learning_rate'],
optimizer='SGD')
return model_fn.ModelFnOps(
mode=mode,
predictions=predictions_dict,
loss=loss,
train_op=train_op)
In [16]:
nn = tf.contrib.learn.Estimator(model_fn=model, params={'learning_rate':0.5})
In [17]:
nn.fit(x=faces, y=left_eye_x, steps=100)
Out[17]:
In [18]:
nn.evaluate(x=faces, y=left_eye_x, steps=1)
Out[18]:
In [19]:
predictions = nn.predict(x=faces[:10,:], as_iterable=True)
for i, p in enumerate(predictions):
print("Prediction %s: %s" % (i + 1, p['x-coordinate'].argmax()))
In [ ]: