{RuntimeError:尝试使用封闭的会话。”

时间:2019-08-08 22:03:17

标签: python python-3.x tensorflow tflearn

我正在使用“扩展”功能对聊天机器人进行编程,但最终仍会出现此错误。我知道很多人已经回答了,但是我的代码完全不同。当我尝试使用新词汇重新训练模型时,便开始发生这种情况。警告:我在网上找到了代码并对其进行了修改(最后一部分,我没有显示)。

我试图更改目录,删除他创建的所有文件(模型和数据),删除'model.load(“ ...”)'和其他东西,我真的很绝望。

其他一些信息:

  • 我使用Conda Virtual Env Python 3.6

  • 我在C盘上工作,但我使用另一个硬盘存储东西

  • 某些导入的模块需要使用pip下载

这是代码的一部分:

# coding: utf-8

import time, pickle, tflearn, nltk, tensorflow, json, random, numpy, os, platform, sys, pyttsx3, speech_recognition, winsound, webbrowser
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()

with open("intents.json") as file:
    data = json.load(file)

file = open("configuration.settings", "r", encoding='utf-8')
leggi = file.readlines()
file.close()

def cleaner():
    try:
        if platform.system().lower() == "linux" or platform.system().lower() == "darwin":
            os.system("clear")
        elif platform.system().lower() == "windows":
            os.system("cls")
    except:
        pass

try:
    with open("data.pickle", "rb") as f:
        words, labels, training, output = pickle.load(f)
except:
    words = []
    labels = []
    docs_x = []
    docs_y = []

    for intent in data["intents"]:
        for pattern in intent["patterns"]:
            wrds = nltk.word_tokenize(pattern)
            words.extend(wrds)
            docs_x.append(wrds)
            docs_y.append(intent["tag"])
            if intent["tag"] not in labels:
                labels.append(intent["tag"])

    words = [stemmer.stem(w.lower()) for w in words if w not in "?"]
    words = sorted(list(set(words)))
    labels = sorted(labels)
    training = []
    output = []
    out_empty = [0 for _ in range(len(labels))]

    for x, doc in enumerate(docs_x):
        bag = []
        wrds = [stemmer.stem(w) for w in doc]
        for w in words:
            if w in wrds:
                bag.append(1)
            else:
                bag.append(0)
        output_row = out_empty[:]
        output_row[labels.index(docs_y[x])] = 1
        training.append(bag)
        output.append(output_row)

    training = numpy.array(training)
    output = numpy.array(output)

    with open("data.pickle", "wb") as f:
        pickle.dump((words, labels, training, output), f)

tensorflow.reset_default_graph()

net = tflearn.input_data(shape=[None, len(training[0])])
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, 8)
net = tflearn.fully_connected(net, len(output[0]), activation="softmax")
net = tflearn.regression(net)

model = tflearn.DNN(net)

try:
    model.load("cbot.tflearn")
except:
    model.fit(training, output, n_epoch=1500, batch_size=8, show_metric=True)
    model.save("cbot.tflearn")

def bag_of_words(s, words):
    bag = [0 for _ in range(len(words))]
    s_words = nltk.word_tokenize(s)
    s_words = [stemmer.stem(word.lower()) for word in s_words]

    for se in s_words:
        for i, w in enumerate(words):
            if w == se:
                bag[i] = 1
    return numpy.array(bag)

### OTHER CODE ###
[...]

这是完整的回溯:

Instructions for updating:
Use standard file APIs to check for files with this prefix.
---------------------------------
Run id: OK6TM7
Log directory: /tmp/tflearn_logs/
---------------------------------
Training samples: 57
Validation samples: 0
--
Traceback (most recent call last):
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 1356, in _do_call
    return fn(*args)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 1341, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 1429, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [8,15] rhs shape= [8,12]
         [[{{node save_1/Assign_16}}]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 1286, in restore
    {self.saver_def.filename_tensor_name: save_path})
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 950, in run
    run_metadata_ptr)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 1173, in _run
    feed_dict_tensor, options, run_metadata)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 1350, in _do_run
    run_metadata)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 1370, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Assign requires shapes of both tensors to match. lhs shape= [8,15] rhs shape= [8,12]
         [[node save_1/Assign_16 (defined at S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\helpers\trainer.py:147) ]]

Errors may have originated from an input operation.
Input Source operations connected to node save_1/Assign_16:
 FullyConnected_2/W (defined at S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\variables.py:65)

Original stack trace for 'save_1/Assign_16':
  File "D:\\cbot-tts_stt.py", line 94, in <module>
    model = tflearn.DNN(net)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\models\dnn.py", line 65, in __init__
    best_val_accuracy=best_val_accuracy)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\helpers\trainer.py", line 147, in __init__
    allow_empty=True)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 825, in __init__
    self.build()
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 837, in build
    self._build(self._filename, build_save=True, build_restore=True)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 875, in _build
    build_restore=build_restore)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 508, in _build_internal
    restore_sequentially, reshape)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 350, in _AddRestoreOps
    assign_ops.append(saveable.restore(saveable_tensors, shapes))
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saving\saveable_object_util.py", line 72, in restore
    self.op.get_shape().is_fully_defined())
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\ops\state_ops.py", line 227, in assign
    validate_shape=validate_shape)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\ops\gen_state_ops.py", line 69, in assign
    use_locking=use_locking, name=name)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 788, in _apply_op_helper
    op_def=op_def)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\util\deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\framework\ops.py", line 3616, in create_op
    op_def=op_def)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\framework\ops.py", line 2005, in __init__
    self._traceback = tf_stack.extract_stack()


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\\cbot-tts_stt.py", line 97, in <module>
    model.load("cbot.tflearn")
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\models\dnn.py", line 308, in load
    self.trainer.restore(model_file, weights_only, **optargs)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\helpers\trainer.py", line 490, in restore
    self.restorer.restore(self.session, model_file)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 1322, in restore
    err, "a mismatch between the current graph and the graph")
tensorflow.python.framework.errors_impl.InvalidArgumentError: Restoring from checkpoint failed. This is most likely due to a mismatch between the current graph and the graph from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error:

Assign requires shapes of both tensors to match. lhs shape= [8,15] rhs shape= [8,12]
         [[node save_1/Assign_16 (defined at S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\helpers\trainer.py:147) ]]

Errors may have originated from an input operation.
Input Source operations connected to node save_1/Assign_16:
 FullyConnected_2/W (defined at S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\variables.py:65)

Original stack trace for 'save_1/Assign_16':
  File "D:\\cbot-tts_stt.py", line 94, in <module>
    model = tflearn.DNN(net)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\models\dnn.py", line 65, in __init__
    best_val_accuracy=best_val_accuracy)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\helpers\trainer.py", line 147, in __init__
    allow_empty=True)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 825, in __init__
    self.build()
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 837, in build
    self._build(self._filename, build_save=True, build_restore=True)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 875, in _build
    build_restore=build_restore)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 508, in _build_internal
    restore_sequentially, reshape)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saver.py", line 350, in _AddRestoreOps
    assign_ops.append(saveable.restore(saveable_tensors, shapes))
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\training\saving\saveable_object_util.py", line 72, in restore
    self.op.get_shape().is_fully_defined())
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\ops\state_ops.py", line 227, in assign
    validate_shape=validate_shape)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\ops\gen_state_ops.py", line 69, in assign
    use_locking=use_locking, name=name)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 788, in _apply_op_helper
    op_def=op_def)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\util\deprecation.py", line 507, in new_func
    return func(*args, **kwargs)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\framework\ops.py", line 3616, in create_op
    op_def=op_def)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\framework\ops.py", line 2005, in __init__
    self._traceback = tf_stack.extract_stack()


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\\cbot-tts_stt.py", line 99, in <module>
    model.fit(training, output, n_epoch=1500, batch_size=8, show_metric=True)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\models\dnn.py", line 216, in fit
    callbacks=callbacks)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\helpers\trainer.py", line 339, in fit
    show_metric)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\helpers\trainer.py", line 816, in _train
    tflearn.is_training(True, session=self.session)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tflearn\config.py", line 95, in is_training
    tf.get_collection('is_training_ops')[0].eval(session=session)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\framework\ops.py", line 731, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\framework\ops.py", line 5579, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 950, in run
    run_metadata_ptr)
  File "S:\WindowsPrograms\Anaconda3\envs\ptg\lib\site-packages\tensorflow\python\client\session.py", line 1096, in _run
    raise RuntimeError('Attempted to use a closed Session.')
RuntimeError: Attempted to use a closed Session.

感谢您阅读本文,对于文本中的某些错误,我深表歉意。 感谢您给我的时间!

1 个答案:

答案 0 :(得分:0)

Traceback具有您所需的所有信息,但是您需要从上至下阅读它,因为报告的最低错误并不总是实际的错误消息。

  

分配需要两个张量的形状匹配。 lhs shape = [8,15] rhs shape = [8,12]

再往下走:

  

从检查点恢复失败。这很可能是由于当前图形与来自检查点的图形之间的不匹配。请确保您没有更改基于检查点的预期图形。

您正在“脏”文件夹中运行模型(它包含先前尝试使用其他模型的结果)。删除旧的检查点或更改培训目录。