【问题标题】:RuntimeError: Attempted to use a closed Session. with tflearn.DNN()RuntimeError:尝试使用已关闭的会话。使用 tflearn.DNN()
【发布时间】:2021-03-09 08:40:50
【问题描述】:

我正在使用 tflearn 制作一个 AI 聊天机器人程序,但每次我运行它时,它都会在 tflearn.DNN() 上给我一个 Traceback 错误。这是错误:

Traceback (most recent call last):
  File "c:/Users/sande/Desktop/Vihaan/ThirdPartySoftware/Python/ChatBot/main.py", line 85, in <module>
    model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
  File "C:\Users\sande\AppData\Local\Programs\Python\Python38\lib\site-packages\tflearn\models\dnn.py", line 196, in fit
    self.trainer.fit(feed_dicts, val_feed_dicts=val_feed_dicts,
  File "C:\Users\sande\AppData\Local\Programs\Python\Python38\lib\site-packages\tflearn\helpers\trainer.py", line 341, in fit
    snapshot = train_op._train(self.training_state.step,
  File "C:\Users\sande\AppData\Local\Programs\Python\Python38\lib\site-packages\tflearn\helpers\trainer.py", line 826, in _train
    tflearn.is_training(True, session=self.session)
  File "C:\Users\sande\AppData\Local\Programs\Python\Python38\lib\site-packages\tflearn\config.py", line 95, in is_training
    tf.get_collection('is_training_ops')[0].eval(session=session)
  File "C:\Users\sande\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\framework\ops.py", line 913, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "C:\Users\sande\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\framework\ops.py", line 5512, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "C:\Users\sande\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\client\session.py", line 957, in run
    result = self._run(None, fetches, feed_dict, options_ptr,
  File "C:\Users\sande\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\client\session.py", line 1104, in _run
    raise RuntimeError('Attempted to use a closed Session.')
RuntimeError: Attempted to use a closed Session.

代码如下:

import numpy
import tflearn
import tensorflow
import random
import json
import pickle
import nltk
nltk.download("punkt")
from nltk.stem.lancaster import LancasterStemmer

stemmer = LancasterStemmer()

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

try:
    with open("data.pickle", "rb")as f:
        words, label, 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 != "?"]
    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.compat.v1.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("model.tflearn")

except:
    model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
    model.save("model.tflearn")

我尝试了多种修复方法,但似乎都没有奏效。我什至尝试重新安装 Tensorflow 和 Tflearn,因为 tensorflow 也给了我一个错误。

我该如何解决这个问题?

顺便说一句,这是 file.intents:

{"intents": [
        {"tag": "greeting",
         "patterns": ["Hi", "How are you", "Is anyone there?", "Hello", "Good day", "Whats up"],
         "responses": ["Hello!", "Good to see you again!", "Hi there, how can I help?"],
         "context_set": ""
        },
        {"tag": "goodbye",
         "patterns": ["See you later", "Goodbye", "I am Leaving", "Have a Good day"],
         "responses": ["Sad to see you go :(", "Talk to you later", "Goodbye!"],
         "context_set": ""
        },
        {"tag": "age",
         "patterns": ["how old", "how old is vihaan", "what is your age", "how old are you", "age?"],
         "responses": ["I am 12 years old!", "12 years young!"],
         "context_set": ""
        },
        {"tag": "name",
         "patterns": ["what is your name", "what should I call you", "whats your name?"],
         "responses": ["You can call me Vihaan.", "I'm Vihaan!", "I'm Vihaan aka PyGamerViharo."],
         "context_set": ""
        },
        {"tag": "code",
         "patterns": ["Do you like python?", "like python?", "what language", "what language do you recommend?"],
         "responses": ["Yes! We have made multiple projects. Check them out at www.github.com/PyGamerViharo", "I always recommend Python, even for developers!"],
         "context_set": ""
        }
   ]
}

【问题讨论】:

  • 看来您使用的是 Tensorflow 1 版本。要在 tensorflow 1 中运行训练,它需要一个会话环境。这个网站描述了会话是如何工作的tensorflow.org/api_docs/python/tf/compat/v1/Session?hl=de
  • 我试过了,它修复了一个错误,但之后又弹出另一个错误。张量流没有属性reset_default_graph
  • 观看此问题:stackoverflow.com/questions/40782271/… 我刚刚搜索了您的错误。可能出现这个问题是因为你把完整的代码放到了会话中?
  • 我已经这样做了,但是没有用
  • 你能证明文件intents.json吗?

标签: python tensorflow


【解决方案1】:

我运行您的代码并像这样更改代码,这对我有用。我猜出于某种原因,对象模型在 'model.load("model.tflearn")' 处被破坏后被处理了

model = tflearn.DNN(net)
try:
    model.load("model.tflearn")

except:
    model = tflearn.DNN(net)
    model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
    model.save("model.tflearn")`

【讨论】:

  • 这是正确答案。模型在加载后以某种方式处理。违反直觉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
  • 2014-03-03
  • 1970-01-01
  • 2018-08-20
相关资源
最近更新 更多