为什么这个tensorflow教程代码不起作用

为什么这个tensorflow教程代码不起作用

问题描述:

现在我正在尝试lstm教程,看看一些人的书。但它没有奏效。有什么问题? :为什么这个tensorflow教程代码不起作用

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()) 

错误消息就是这样。请解决这个问题。

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)]] 

您还没有初始化某些图形变量,如提到的错误。将您的代码转移到此,它将工作。

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

最佳做法是有init就在你的图形月底和sess.run前。

编辑:请参阅What does tf.global_variables_initializer() do under the hood?了解更多见解。

+0

不要发布重复问题的答案。关闭他们作为重复 –

+0

我非常感谢您的帮助。 –

您在创建变量之前定义操作init。因此,只有在当时定义的变量上才会执行此操作,即使您在创建变量后运行该变量。

所以,只要移动init的定义,你会没事的。

+0

不要发布重复问题的答案。将它们作为副本关闭 –

+0

感谢您的解释 –