【问题标题】:TensorFlow reusing Variable ScopeTensorFlow 重用变量作用域
【发布时间】:2018-04-11 18:02:54
【问题描述】:

这是我在张量流中的代码,我已经定义了一个 Bi-LSTM,对于某个任务,我需要遍历我的图。虽然我在Scope Variable中设置了reuse=True,但它会产生代码下面提到的错误。

for run in range(0, 2):


   with tf.variable_scope("LSTM", reuse= True) as scope:

     def LSTM(input_data):



        LSTM_cell_fw= tf.contrib.rnn.BasicLSTMCell(num_units= hidden_size)
        LSTM_cell_bw= tf.contrib.rnn.BasicLSTMCell(num_units= hidden_size)          
        output, states = tf.nn.bidirectional_dynamic_rnn(LSTM_cell_fw, LSTM_cell_bw, inputs= input_data, dtype=tf.float32)
        output_1= output[0]
        output_2= output[1]
        output_1= output_1[-1, -1, :]
        output_1= tf.reshape(output_1, shape= (1, hidden_size))
        output_2= output_2[-1, -1, :]
        output_2= tf.reshape(output_2, shape= (1, hidden_size))
        fin_output= tf.concat((output_1, output_2), axis=1)

        return fin_output

错误是:ValueError: 变量 bidirectional_rnn/fw/basic_lstm_cell/kernel 已经存在,不允许。您的意思是在 VarScope 中设置 reuse=True 吗?最初定义于:

文件“alpha-rep.py”,第 65 行,在 LSTM 中 输出,状态 = tf.nn.bidirectional_dynamic_rnn(LSTM_cell_fw,LSTM_cell_bw,输入= input_data,dtype=tf.float32) 文件“alpha-rep.py”,第 77 行,在 out= LSTM(input_data)

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    要重用一个变量,您首先必须定义它,然后才能重用它。

    定义定义变量的函数:

    def LSTM(input_data):
        LSTM_cell_fw= tf.contrib.rnn.BasicLSTMCell(num_units= hidden_size)
        LSTM_cell_bw= tf.contrib.rnn.BasicLSTMCell(num_units= hidden_size)          
        output, states = tf.nn.bidirectional_dynamic_rnn(LSTM_cell_fw, LSTM_cell_bw, inputs= input_data, dtype=tf.float32)
        output_1= output[0]
        output_2= output[1]
        output_1= output_1[-1, -1, :]
        output_1= tf.reshape(output_1, shape= (1, hidden_size))
        output_2= output_2[-1, -1, :]
        output_2= tf.reshape(output_2, shape= (1, hidden_size))
        return tf.concat((output_1, output_2), axis=1)
    

    然后第一次调用它来定义变量并将其放在所需的范围内:

    with tf.variable_scope("LSTM", reuse=False) as scope:
        first = LSTM(your_input_here)
    

    现在您可以在同一范围内定义其他层,重用已定义的变量:

    with tf.variable_scope("LSTM", reuse=True) as scope:
        second = LSTM(your_other_input_here)
    

    【讨论】:

    • 感谢您的回复,您的意思是,例如,图第一次正常工作(run=0),重用应为假,而当 run>0 时,应为真,对吧?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多