【问题标题】:Keras set_learning_phase for Dropout when saving TensorFlow SessionKeras set_learning_phase 用于保存 TensorFlow Session 时的 Dropout
【发布时间】:2017-02-03 13:41:10
【问题描述】:

我一直关注this post,尤其是第二部分,以使用 Keras 作为 TensorFlow 的接口。

例如,我一直在使用 MNIST 数据集训练 CNN。我的目标是在 TF 会话中训练和评估模型,然后使用 tf.train.Saver() 保存会话,以便我可以在 CloudML 上部署模型。

我可以为不使用 Dropout 的模型执行此操作,但是,当我在 Keras 中包含 Dropout 层时,您需要指定 learning_phase(训练 = 1,测试 = 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')

【问题讨论】:

    标签: tensorflow google-cloud-platform keras keras-layer


    【解决方案1】:

    由于这是一个非常面向 Keras 的编程问题,因此最好将此问题直接发布到他们的 GitHub Issue Tracker

    您还可以在他们的问题跟踪器中发现this same issue 已经报告并解决了many times。您的问题的解决方案也可能包含在Keras documentation 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-15
      • 2018-11-10
      • 2019-06-02
      • 2018-10-31
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      相关资源
      最近更新 更多