I have a Python error

Asked

Viewed 90 times

1

I have the following code saved as main.py

import nltk
from nltk.stem.lancaster import LancasterStemmer

stemmer = LancasterStemmer()

import numpy
import tflearn
import tensorflow
import random
import json
import pickle

try:
    nltk.download('punkt')
except:
    pass

with open("intents.json") as file:
    data = json.load(file)
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 != "?"]
    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.lower()) 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("model.tflearn")
except:
    model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
    model.save("model.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)


def chat():
    print("Comece a falar com o Bot! (Escreva sair para parar o Bot)")
    while True:
        inp = input("Você:")
        if inp.lower() == "sair":
            break
        results = model.predict([bag_of_words(inp, words)])[0]
        results_index = numpy.argmax(results)
        tag = labels[results_index]

        if results[results_index] > 0.7:
            for tg in data["intents"]:
                if tg['tag'] == "tag":
                    responses = tg['responses']

            print(random.choice(responses))
        else:
            print("Não entendi, tente repetir a pergunta ou me diga outra coisa.")


chat()

When I run it I get the following error

C:\Users\Viana\AppData\Local\Programs\Python\Python37\python.exe C:/Users/Viana/Desktop/Projetos/Curso/Python/Jessie/Codigo/main.py
C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])
curses is not supported on this machine (please install/reinstall curses for an optimal experience)
WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\helpers\summarizer.py:9: The name tf.summary.merge is deprecated. Please use tf.compat.v1.summary.merge instead.

WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\helpers\trainer.py:25: The name tf.summary.FileWriter is deprecated. Please use tf.compat.v1.summary.FileWriter instead.

WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\collections.py:13: The name tf.GraphKeys is deprecated. Please use tf.compat.v1.GraphKeys instead.

WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\config.py:123: The name tf.get_collection is deprecated. Please use tf.compat.v1.get_collection instead.

Scipy not supported!
WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\config.py:129: The name tf.add_to_collection is deprecated. Please use tf.compat.v1.add_to_collection instead.

WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\config.py:131: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.

[nltk_data] Downloading package punkt to
[nltk_data]     C:\Users\Viana\AppData\Roaming\nltk_data...
[nltk_data]   Package punkt is already up-to-date!
WARNING:tensorflow:From C:/Users/Viana/Desktop/Projetos/Curso/Python/Jessie/Codigo/main.py:71: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead.

WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\initializations.py:174: calling TruncatedNormal.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer instance with the dtype argument instead of passing it to the constructor
WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\optimizers.py:238: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead.

WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\objectives.py:66: calling reduce_sum_v1 (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.
Instructions for updating:
keep_dims is deprecated, use keepdims instead
2019-09-25 19:25:50.808762: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\summaries.py:46: The name tf.summary.scalar is deprecated. Please use tf.compat.v1.summary.scalar instead.

WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\ops\math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\helpers\trainer.py:134: The name tf.train.Saver is deprecated. Please use tf.compat.v1.train.Saver instead.

WARNING:tensorflow:From C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\training\saver.py:1276: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.
Instructions for updating:
Use standard file APIs to check for files with this prefix.
---------------------------------
Run id: QAZDGH
Log directory: /tmp/tflearn_logs/
Traceback (most recent call last):
  File "C:/Users/Viana/Desktop/Projetos/Curso/Python/Jessie/Codigo/main.py", line 81, in <module>
    model.load("model.tflearn")
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\models\dnn.py", line 308, in load
    self.trainer.restore(model_file, weights_only, **optargs)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\helpers\trainer.py", line 490, in restore
    self.restorer.restore(self.session, model_file)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\training\saver.py", line 1278, in restore
    compat.as_text(save_path))
ValueError: The passed save_path is not a valid checkpoint: C:\Users\Viana\Desktop\Projetos\Curso\Python\Jessie\Codigo\model.tflearn

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Viana/Desktop/Projetos/Curso/Python/Jessie/Codigo/main.py", line 83, in <module>
    model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\models\dnn.py", line 216, in fit
    callbacks=callbacks)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\helpers\trainer.py", line 339, in fit
    show_metric)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\helpers\trainer.py", line 816, in _train
    tflearn.is_training(True, session=self.session)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tflearn\config.py", line 95, in is_training
    tf.get_collection('is_training_ops')[0].eval(session=session)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\ops.py", line 731, in eval
    return _eval_using_default_session(self, feed_dict, self.graph, session)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\framework\ops.py", line 5579, in _eval_using_default_session
    return session.run(tensors, feed_dict)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 950, in run
    run_metadata_ptr)
  File "C:\Users\Viana\AppData\Local\Programs\Python\Python37\lib\site-packages\tensorflow\python\client\session.py", line 1096, in _run
---------------------------------
Training samples: 12
Validation samples: 0
--
    raise RuntimeError('Attempted to use a closed Session.')
RuntimeError: Attempted to use a closed Session.

Process finished with exit code 1

I already reinstalled all the frameworks I use in the project and still the error continues. I don’t know what’s going on and I don’t have the knowledge to solve it, I would like you to help me solve it. Thank you

  • I found a solution for model error in this part of the code: try:&#xA; model.load("model.tflearn")&#xA;except:&#xA; model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)&#xA; model.save("model.tflearn") Just remove Try: and except: and leave only the last two lines, the code in that part will look like this: model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True)&#xA; model.save("model.tflearn")

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.