3

I start learning to build a simple network to classify mnist by tensorflow.contrib.keras.

The codes are listed below:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.keras import layers as klayer
from tensorflow.contrib.keras import losses as kloss

def main(argv):

mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)

with tf.Graph().as_default():
    img = tf.placeholder(tf.float32, shape=(None, 784))
    labels = tf.placeholder(tf.float32, shape=(None, 10))

    x = klayer.Dense(128, activation='relu')(img)
    x = klayer.Dropout(0.5)(x)  # this line would raise an error

    preds = klayer.Dense(10, activation='softmax')(x)

    loss = tf.reduce_mean(kloss.categorical_crossentropy(labels, preds))

    train_op = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

    with tf.Session() as sess:

        writer = tf.summary.FileWriter('output', sess.graph)
        writer.close()
        sess.run(tf.global_variables_initializer())          
        for i in range(1000):
            batch = mnist_data.train.next_batch(100)
            train_op.run(feed_dict={img: batch[0], labels: batch[1]})                        

if __name__ == '__main__':
    tf.app.run()

But there is an error raised when I use Dropout, where the error are listed as below:

2017-06-30 14:23:16.422782: W tensorflow/core/framework/op_kernel.cc:1152] Invalid argument: You must feed a value for placeholder tensor 'dropout_1/keras_learning_phase' with dtype bool
 [[Node: dropout_1/keras_learning_phase = Placeholder[dtype=DT_BOOL, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]

How should I resolve this problem? Thanks

Wilson
  • 536
  • 1
  • 5
  • 15
  • 1
    Have you tried setting the learning phase as per this [answer](https://stackoverflow.com/questions/42969779/keras-error-you-must-feed-a-value-for-placeholder-tensor-bidirectional-1-keras)? – jkschin Jun 30 '17 at 06:47
  • 1
    I just found how to resolve it. Thanks. from tensorflow.contrib.keras import backend as kbackend train_op.run(feed_dict={img: batch[0], labels: batch[1], kbackend.learning_phase(): 1}) – Wilson Jun 30 '17 at 07:08

0 Answers0