ValueError: Variable rnnlm/multi_rnn_cell/cell_0/basic_lstm_cell/kernel already exists, disallowed.

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuqiuai/article/details/83758678

报错:
ValueError: Variable rnnlm/multi_rnn_cell/cell_0/basic_lstm_cell/kernel already exists, disallowed.

原因:模型重用

解决方法:在构建图的代码块上加上with tf.Graph().as_default():

graph = tf.Graph()
with graph.as_default():

    #定义输入,输出
    x=tf.placeholder(dtype=tf.float32,shape=[None,sequence_length*frame_size],name="inputx")
    y=tf.placeholder(dtype=tf.float32,shape=[None,n_classes],name="expected_y")
    #定义权值
    weights=tf.Variable(tf.truncated_normal(shape=[hidden_num,n_classes]))
    bias=tf.Variable(tf.zeros(shape=[n_classes]))

    # 定义RNN网络
    def RNN(x,weights,bias):
        '''返回[batch_size,n_classes]'''
        x=tf.reshape(x,shape=[-1,sequence_length,frame_size])
#         rnn_cell=tf.nn.rnn_cell.BasicRNNCell(hidden_num) # RNN/LSTM/GRU在此处选择BasicRNNCell/BasicLSTMCell/GRUCell。该网络中包含一个深度RNN网络,这个RNN包含hidden_num个隐层单元/RNN cell
        rnn_cell = tf.nn.rnn_cell.MultiRNNCell([tf.nn.rnn_cell.GRUCell(hidden_num) for _ in range(3)]) # 构建多层RNN/LSTM/GRU网络,3表示3层(这里都是用MultiRNNCell,没有MultiGRUCell等)
    
        output,states=tf.nn.dynamic_rnn(rnn_cell,x,dtype=tf.float32)
        return tf.nn.softmax(tf.matmul(output[:,-1,:],weights)+bias,1)

    # 计算预计输出
    predy=RNN(x,weights,bias)
    # 定义损失函数和优化算法
    cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=predy,labels=y))
    train=tf.train.AdamOptimizer(train_rate).minimize(cost)
    # 计算accuracy
    correct_pred=tf.equal(tf.argmax(predy,1),tf.argmax(y,1))
    accuracy=tf.reduce_mean(tf.to_float(correct_pred))


## 开始训练
with tf.Session(graph=graph) as sess:
    print('step','accuracy','loss')
    sess.run(tf.initialize_all_variables())
    step=1
    testx,testy=mnist.test.next_batch(batch_size)
    while step<train_step:
        batch_x,batch_y=mnist.train.next_batch(batch_size)
    #    batch_x=tf.reshape(batch_x,shape=[batch_size,sequence_length,frame_size])
        _loss,__=sess.run([cost,train],feed_dict={x:batch_x,y:batch_y})
        if step % display_step ==0:
            acc,loss=sess.run([accuracy,cost],feed_dict={x:testx,y:testy})
            print(step,acc,loss)

        step+=1

这样就不会报错了。

猜你喜欢

转载自blog.csdn.net/fuqiuai/article/details/83758678
今日推荐