Я слежу за this post, в частности частью II, чтобы использовать Keras в качестве интерфейса к TensorFlow.Keras set_learning_phase for Dropout при сохранении сеанса TensorFlow
В качестве примера я обучаю CNN, используя набор данных MNIST. Моя цель - подготовить и оценить модель в сеансе TF, а затем сохранить сеанс, используя tf.train.Saver()
, чтобы я мог развернуть модель на CloudML.
Я могу сделать это для модели, которая не использует Dropout, однако, когда я включаю слои Dropouts в Keras, вам нужно указать Learning_phase (training = 1, testing = 0), это делается через feed_dict (см. код ниже).
Локально Я могу контролировать это, делая что-то вроде
test_accuracy = accuracy.eval(feed_dict={images: mnist_data.test.images, labels: mnist_data.test.labels, K.learning_phase(): 0})
Однако когда я загрузить свою модель, чтобы CloudML и попытаться проверить я получаю следующее сообщение об ошибке
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'keras_learning_phase' with dtype bool
[[Node: keras_learning_phase = Placeholder[dtype=DT_BOOL, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Я знаю, что это из-за строки в feed_dict, но я понятия не имею, как обойти это. В разделе IV блога он рассказывает об этой проблеме в контексте TensorFlow, где загружается и повторно сохраняется модель. Я не мог заставить это работать для моего подхода, потому что мне нужно экспортировать экспорт сессии и export.meta, а не модель Keras.
# Make a session in tf
sess = tf.Session()
# sess = tf.InteractiveSession()
# Register the tf session with Keras
K.set_session(sess)
# Generate placeholders for the images and labels and mark as input.
images = tf.placeholder(tf.float32, shape=(None, 28, 28, 1))
keys_placeholder = tf.placeholder(tf.int64, shape=(None,))
labels = tf.placeholder(tf.float32, shape=(None, 10))
inputs = {'key': keys_placeholder.name, 'image': images.name}
tf.add_to_collection('inputs', json.dumps(inputs))
# To be able to extract the id, we need to add the identity function.
keys = tf.identity(keys_placeholder)
# Define a simple network
# Two fully-connected layer with 128 units and ReLU activation
model = Sequential()
model.add(Convolution2D(32, 5, 5, activation='relu', input_shape=(28, 28, 1)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(64, 5, 5, activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.50))
model.add(Dense(10, activation='softmax'))
preds = model(images) # Output
# Define some Ops
prediction = tf.argmax(preds ,1)
scores = tf.nn.softmax(preds)
# Use the Keras caterforical crossentropy_function and the tf reduce mean
loss = tf.reduce_mean(categorical_crossentropy(labels, preds))
# Define the optimizer
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
# Initialization op
init_op = tf.initialize_all_variables()
# Saver op
saver = tf.train.Saver()
# Mark the outputs.
outputs = {'key': keys.name,
'prediction': prediction.name,
'scores': scores.name}
tf.add_to_collection('outputs', json.dumps(outputs))
# Get the data
mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True, reshape=False)
# Open session
with sess.as_default():
sess.run(init_op)
# print keras_learning_phase.eval()
for i in range(100):
batch = mnist_data.train.next_batch(50)
train_step.run(feed_dict={images: batch[0],
labels: batch[1],
K.learning_phase(): 1})
saver.save(sess, 'test/export')