Tensorflow - 尝试运行BasicLSTMCell一次

时间:2017-09-28 21:37:26

标签: tensorflow initialization

我想运行BasicLSTMCell一次,得到结果,看看我是否可以手动重现结果。但是,我坚持执行BasicLSTMCell一次。这是我的代码:

import tensorflow as tf
BATCH_SIZE = 7 
SEQUENCE_LENGTH = 5
VECTOR_SIZE = 3
STATE_SIZE = 4

x = tf.placeholder(tf.float32, [BATCH_SIZE, SEQUENCE_LENGTH, VECTOR_SIZE],
                   name='input_placeholder')
y = tf.placeholder(tf.float32, [BATCH_SIZE, SEQUENCE_LENGTH],
                   name='labels_placeholder')
rnn_inputs = tf.unstack(x, axis = 1)
init_state = tf.zeros([BATCH_SIZE, STATE_SIZE], tf.float32)

cell = tf.contrib.rnn.BasicLSTMCell(STATE_SIZE, state_is_tuple = True)
X = np.zeros([BATCH_SIZE, SEQUENCE_LENGTH, VECTOR_SIZE])
Y = np.zeros([BATCH_SIZE, SEQUENCE_LENGTH])

sess = tf.Session()
output_state = sess.run([cell(rnn_inputs[0], (init_state, init_state))], feed_dict = {x:X,y:Y})

它会产生很长的错误消息,我在下面发布,但总结如下:

FailedPreconditionError: Attempting to use uninitialized value basic_lstm_cell/kernel
     [[Node: basic_lstm_cell/kernel/read = Identity[T=DT_FLOAT, _class=["loc:@basic_lstm_cell/kernel"], _device="/job:localhost/replica:0/task:0/cpu:0"](basic_lstm_cell/kernel)]]

你看到我没有初始化的价值吗?

这是完整的错误跟踪:

---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1326     try:
-> 1327       return fn(*args)
   1328     except errors.OpError as e:

~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1305                                    feed_dict, fetch_list, target_list,
-> 1306                                    status, run_metadata)
   1307 

~\AppData\Local\conda\conda\envs\tensorflow\lib\contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

~\AppData\Local\conda\conda\envs\tensorflow\lib\site-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:

FailedPreconditionError: Attempting to use uninitialized value basic_lstm_cell/bias
     [[Node: basic_lstm_cell/bias/read = Identity[T=DT_FLOAT, _class=["loc:@basic_lstm_cell/bias"], _device="/job:localhost/replica:0/task:0/cpu:0"](basic_lstm_cell/bias)]]

During handling of the above exception, another exception occurred:

FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-2-730be9dd8e3e> in <module>()
     18 
     19 sess = tf.Session()
---> 20 output_state = sess.run([cell(rnn_inputs[0], (init_state, init_state))], feed_dict = {x:X,y:Y})
     21 
     22 

~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    893     try:
    894       result = self._run(None, fetches, feed_dict, options_ptr,
--> 895                          run_metadata_ptr)
    896       if run_metadata:
    897         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1122     if final_fetches or final_targets or (handle and feed_dict_tensor):
   1123       results = self._do_run(handle, final_targets, final_fetches,
-> 1124                              feed_dict_tensor, options, run_metadata)
   1125     else:
   1126       results = []

~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1319     if handle is None:
   1320       return self._do_call(_run_fn, self._session, feeds, fetches, targets,
-> 1321                            options, run_metadata)
   1322     else:
   1323       return self._do_call(_prun_fn, self._session, handle, feeds, fetches)

~\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1338         except KeyError:
   1339           pass
-> 1340       raise type(e)(node_def, op, message)
   1341 
   1342   def _extend_graph(self):

FailedPreconditionError: Attempting to use uninitialized value basic_lstm_cell/bias
     [[Node: basic_lstm_cell/bias/read = Identity[T=DT_FLOAT, _class=["loc:@basic_lstm_cell/bias"], _device="/job:localhost/replica:0/task:0/cpu:0"](basic_lstm_cell/bias)]]

Caused by op 'basic_lstm_cell/bias/read', defined at:
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\ipykernel\kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tornado\ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 235, in dispatch_shell
    handler(stream, idents, msg)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request
    user_expressions, allow_stdin)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2698, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2802, in run_ast_nodes
    if self.run_code(code, result):
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-730be9dd8e3e>", line 20, in <module>
    output_state = sess.run([cell(rnn_inputs[0], (init_state, init_state))], feed_dict = {x:X,y:Y})
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\rnn_cell_impl.py", line 180, in __call__
    return super(RNNCell, self).__call__(inputs, state)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\layers\base.py", line 450, in __call__
    outputs = self.call(inputs, *args, **kwargs)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\rnn_cell_impl.py", line 401, in call
    concat = _linear([inputs, h], 4 * self._num_units, True)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\rnn_cell_impl.py", line 1053, in _linear
    initializer=bias_initializer)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 1065, in get_variable
    use_resource=use_resource, custom_getter=custom_getter)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 962, in get_variable
    use_resource=use_resource, custom_getter=custom_getter)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 360, in get_variable
    validate_shape=validate_shape, use_resource=use_resource)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\rnn_cell_impl.py", line 183, in _rnn_get_variable
    variable = getter(*args, **kwargs)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 352, in _true_getter
    use_resource=use_resource)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\variable_scope.py", line 725, in _get_single_variable
    validate_shape=validate_shape)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\variables.py", line 199, in __init__
    expected_shape=expected_shape)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\variables.py", line 330, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1400, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 2630, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\Users\some_user\AppData\Local\conda\conda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 1204, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value basic_lstm_cell/bias
     [[Node: basic_lstm_cell/bias/read = Identity[T=DT_FLOAT, _class=["loc:@basic_lstm_cell/bias"], _device="/job:localhost/replica:0/task:0/cpu:0"](basic_lstm_cell/bias)]]

2 个答案:

答案 0 :(得分:2)

cell 是BasicLSTMCell的一个对象,它是填充输出和新状态的图形的一部分。

感谢python可读性

cell(rnn_inputs[0], (init_state, init_state))

实际上是:

cell.__call__(rnn_inputs[0], (init_state, init_state))

可以将单元格调用放在tf.Session()之前,因为您无法运行它。 使用python 3.5和tensorflow 1.3测试以下代码:

import tensorflow as tf
import numpy as np

BATCH_SIZE = 7 
SEQUENCE_LENGTH = 5
VECTOR_SIZE = 3
STATE_SIZE = 4

x = tf.placeholder(tf.float32, [BATCH_SIZE, SEQUENCE_LENGTH, VECTOR_SIZE],
                   name='input_placeholder')
y = tf.placeholder(tf.float32, [BATCH_SIZE, SEQUENCE_LENGTH],
                   name='labels_placeholder')
rnn_inputs = tf.unstack(x, axis = 1)
init_state = tf.zeros([BATCH_SIZE, STATE_SIZE], tf.float32)

cell = tf.contrib.rnn.BasicLSTMCell(STATE_SIZE, state_is_tuple = True)
X = np.zeros([BATCH_SIZE, SEQUENCE_LENGTH, VECTOR_SIZE])
Y = np.zeros([BATCH_SIZE, SEQUENCE_LENGTH])


output, newstate = cell.__call__(rnn_inputs[0], (init_state, init_state))

sess = tf.Session()
sess.run(tf.global_variables_initializer())
result = sess.run([output, newstate], feed_dict = {x:X,y:Y})
print (result)
sess.close()

答案 1 :(得分:1)

You need to initialize all variables,例如,tf.global_variables_initializer()(或从之前训练过的图表中恢复它们),然后才能真正使用它们。创建LSTM单元格时,您将向图形添加许多变量(单元格的权重和偏差)。要初始化这些,请添加以下行:

sess.run(tf.global_variables_initializer())
sess.run行之前

。请注意,这会将所有变量初始化为无用的值 - 我认为权重的正态分布随机值和偏差的零。运行此网络一次并不能为您做任何事情。你可以restore the network from a previously-trained one。该链接和this one描述了如何使用tf.train.Saver对象在图形中保存和恢复变量,以及保存和恢复整个图形(网络结构,操作等)。