我在Jupyter Notebook中实现了一个RNN单词生成器模型。当我尝试使用训练好的模型生成一些单词时:
with open(os.path.join(cfgs['save_dir'], 'config.pkl'), 'rb') as f: saved_args = cPickle.load(f) with open(os.path.join(cfgs['save_dir'], 'words_vocab.pkl'), 'rb') as f: words, vocab = cPickle.load(f) with tf.Session() as sess: model = Model(saved_args, True) tf.global_variables_initializer().run() saver = tf.train.Saver(tf.global_variables()) ckpt = tf.train.get_checkpoint_state(cfgs['save_dir']) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) print(model.sample(sess, words, vocab, cfgs['n'], cfgs['prime'], cfgs['sample'], cfgs['pick'], cfgs['width']))
第一次运行时一切正常,但如果我再次运行代码,就会出现错误:
ValueError: Variable rnnlm/softmax_w already exists, disallowed. Did you mean to set reuse=True in VarScope?
目前我必须关闭ipynb文件,然后重新运行代码才能获得新的样本。如何修改代码以避免这种情况?
回答:
你可以多次调用model.sample函数而不会出现问题,但其他操作(创建会话、构建模型、加载检查点)应该只运行一次。如果你重构你的代码,就不会再看到这个错误消息了。