tf.contrib.keras + tf.placeholder出错

时间:2017-08-09 08:33:52

标签: tensorflow keras

我正在尝试在Keras中使用内置模型。

这很有效:

import tensorflow as tf
keras = tf.contrib.keras

imgs = tf.placeholder(tf.float32, shape=(None, 150, 150, 3))

x = keras.applications.InceptionV3(weights='imagenet', include_top=False, pooling='avg', input_shape=(150,150,3))(imgs)

这不是:

import tensorflow as tf
keras = tf.contrib.keras

init_imgs = tf.placeholder(dtype=tf.float32)
imgs = tf.get_variable('imgs', initializer=init_imgs, trainable=False, validate_shape=False, dtype=tf.float32)

x = keras.applications.InceptionV3(weights='imagenet', include_top=False, pooling='avg', input_shape=(150,150,3))(imgs)

它会产生错误You must feed a value for placeholder tensor 'Placeholder' with dtype float,但我没有sess.run()。当我试图构建图表时,为什么会抱怨Feed?

添加

这是堆栈跟踪。错误来自model.load_weights。但是,我认为加载InceptionV3权重应该独立于图的其他部分。

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1138     try:
-> 1139       return fn(*args)
   1140     except errors.OpError as e:

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1120                                  feed_dict, fetch_list, target_list,
-> 1121                                  status, run_metadata)
   1122 

/usr/lib/python3.5/contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

InvalidArgumentError: You must feed a value for placeholder tensor 'my_own_placeholder' with dtype float
     [[Node: my_own_placeholder = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-1-cf7678dd8501> in <module>()
      8 imgs = tf.get_variable('imgs', initializer=init_imgs, trainable=False, validate_shape=False, dtype=tf.float32)
      9 
---> 10 x = keras.applications.InceptionV3(weights='imagenet', include_top=False, pooling='avg', input_shape=(150,150,3))(imgs)

/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/keras/python/keras/applications/inception_v3.py in InceptionV3(include_top, weights, input_tensor, input_shape, pooling, classes)
    394           cache_subdir='models',
    395           md5_hash='bcbd6486424b2319ff4ef7d526e38f63')
--> 396     model.load_weights(weights_path)
    397     if K.backend() == 'theano':
    398       convert_all_kernels_in_model(model)

/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/keras/python/keras/engine/topology.py in load_weights(self, filepath, by_name)
   2279       load_weights_from_hdf5_group_by_name(f, self.layers)
   2280     else:
-> 2281       load_weights_from_hdf5_group(f, self.layers)
   2282 
   2283     if hasattr(f, 'close'):

/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/keras/python/keras/engine/topology.py in load_weights_from_hdf5_group(f, layers)
   2666                        str(len(weight_values)) + ' elements.')
   2667     weight_value_tuples += zip(symbolic_weights, weight_values)
-> 2668   K.batch_set_value(weight_value_tuples)
   2669 
   2670 

/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/keras/python/keras/backend.py in batch_set_value(tuples)
   2222       assign_ops.append(assign_op)
   2223       feed_dict[assign_placeholder] = value
-> 2224     get_session().run(assign_ops, feed_dict=feed_dict)
   2225 
   2226 

/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/keras/python/keras/backend.py in get_session()
    369   if not _MANUAL_VAR_INIT:
    370     with session.graph.as_default():
--> 371       _initialize_variables()
    372   return session
    373 

/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/keras/python/keras/backend.py in _initialize_variables()
    518   if uninitialized_variables:
    519     sess = get_session()
--> 520     sess.run(variables_module.variables_initializer(uninitialized_variables))
    521 
    522 

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    787     try:
    788       result = self._run(None, fetches, feed_dict, options_ptr,
--> 789                          run_metadata_ptr)
    790       if run_metadata:
    791         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    995     if final_fetches or final_targets:
    996       results = self._do_run(handle, final_targets, final_fetches,
--> 997                              feed_dict_string, options, run_metadata)
    998     else:
    999       results = []

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1130     if handle is None:
   1131       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1132                            target_list, options, run_metadata)
   1133     else:
   1134       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1150         except KeyError:
   1151           pass
-> 1152       raise type(e)(node_def, op, message)
   1153 
   1154   def _extend_graph(self):

InvalidArgumentError: You must feed a value for placeholder tensor 'my_own_placeholder' with dtype float
     [[Node: my_own_placeholder = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]

Caused by op 'my_own_placeholder', defined at:
  File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python3.5/dist-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python3.5/dist-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/lib/python3.5/dist-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python3.5/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python3.5/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python3.5/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2802, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-1-cf7678dd8501>", line 7, in <module>
    init_imgs = tf.placeholder(dtype=tf.float32, name='my_own_placeholder')
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/array_ops.py", line 1530, in placeholder
    return gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 1954, in _placeholder
    name=name)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2506, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 1269, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'my_own_placeholder' with dtype float
     [[Node: my_own_placeholder = Placeholder[dtype=DT_FLOAT, shape=<unknown>, _device="/job:localhost/replica:0/task:0/gpu:0"]()]]

1 个答案:

答案 0 :(得分:0)

查看代码,InceptionV3不仅尝试初始化其权重,还尝试初始化所有tf.global_variables()。

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/keras/python/keras/backend.py#L534

因此,当前的Keras模型不能用作Tensorflow的子图。