why this tensorflow tutorial code not working

眉间皱痕 提交于 2019-12-12 06:57:24

问题


Now i'm trying lstm tutorial, look some one's book. But it didn't work. What's the problem? :

import tensorflow as tf

import numpy as np

from tensorflow.contrib import rnn

import pprint

pp = pprint.PrettyPrinter(indent=4)

sess = tf.InteractiveSession()

a = [1, 0, 0, 0]

b = [0, 1, 0, 0]

c = [0, 0, 1, 0]

d = [0, 0, 0, 1]

init=tf.global_variables_initializer()

with tf.variable_scope('one_cell') as scope:
    hidden_size = 2  
    cell = tf.contrib.rnn.BasicRNNCell(num_units=hidden_size)  
    print(cell.output_size, cell.state_size)  

    x_data = np.array([[a]], dtype=np.float32) 
    pp.pprint(x_data)
    outputs, _states = tf.nn.dynamic_rnn(cell, x_data, dtype=tf.float32)
    sess.run(init)
    pp.pprint(outputs.eval())

Error message is like that. Please solve this problem.

Attempting to use uninitialized value one_cell/rnn/basic_rnn_cell/weights
     [[Node: one_cell/rnn/basic_rnn_cell/weights/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](one_cell/rnn/basic_rnn_cell/weights)]]

回答1:


You haven't initialized some graph variables, as the error mentioned. Shift your code to this and it will work.

outputs, _states = tf.nn.dynamic_rnn(cell, x_data, dtype=tf.float32)
init=tf.global_variables_initializer()
sess.run(init)

Best practice is to have init right at the end of your graph and before sess.run.

EDIT: Refer to What does tf.global_variables_initializer() do under the hood? for more insights.




回答2:


You define the operation init before creating your variables. Thus this operation will be performed only on the variables defined at that time, even if you run it after creating your variables.

So just move the definition of init and you will be fine.



来源:https://stackoverflow.com/questions/44584809/why-this-tensorflow-tutorial-code-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!