我在名为fit.py
的脚本中有以下tensorflow代码以适合给定数据。我重复使用变量w
和b
作为整个序列长度。
seq_len=10
x_data=np.random.uniform(0,1,(10,1))
y_data=x_data*0.8 + 0.5
x=tf.placeholer('float',[seq_len,1])
y=tf.placeholer('float',[seq_len,1])
with tf.variable_scope('network_cell'):
w = tf.get_variable('w', [1] )
b = tf.get_variable('b', [1])
def give_output(inputs):
output=[]
cell = tf.nn.rnn_cell.BasicRNNCell(state_size)
rnn_outputs, _ = tf.nn.rnn(cell, rnn_inputs, dtype = tf.float32, initial_state=init_state)
with tf.variable_scope('network_cell', reuse=True):
W = tf.get_variable('W', [1] )
b = tf.get_variable('b', [1])
output = rnn_outputs*W+b
return output
def train_network():
prediction= give_output(x)
loss=tf.nn.l2_loss(prediction-y)
optimizer = tf.train.AdamOptimizer().minimize(loss)
s=tf.Session()
init=tf.global_variables_initializer()
s.run(init)
_, loss_value=s.run([optimizer,loss], feed_dict={x:x_data,y: y_data})
return loss_value
我从名为run.py
的其他脚本调用此脚本,以便为多次运行收集loss_value
:
from fit import *
loss_values=np.zeros(10)
for i in range(10):
loss_values(i)= train_network()
print("Successfully done",i)
但是,在我调用脚本一次后,我收到以下错误:
Successfully done 0
Valueerror: Variable/RNN/BasicRNNCell/Linear/Matrix already exists, disallowed.
Did you men to set reuse=True in VarScope?
我认为问题是因为它使用与迭代0
相同的图形,即使对于迭代1
也是如此。每次拨打fit.py
时,如何确保重新调用整个脚本train_network
?