Problema con python

di il
1 risposte

Problema con python

Ciao a tutti sto cercando di programmare un chatbot in python ma esce questo errore:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 52, in <module>
NameError: name 'train_x' is not defined
Questo è il codice di programmazione
Codice:
import nltk

nltk.download('punkt')

nltk.download('wordnet')

from nltk.stem import WordNetLemmatizer


import json

import pickle


import numpy as np

from keras.models import Sequential

from keras.layers import Dense, Dropout

from keras.optimizers import SGD

words = []

classes = []

documents = []

ignore_words = ['?', '!']

data_file = open('Intents.json').read()

intents = json.loads(data_file)

for intent in intents['intents']:

    for pattern in intent['patterns']:


        # tokenizzo ogni parola

        w = nltk.word_tokenize(pattern)

        words.extend(w)


        # aggiungo all'array documents

        documents.append((w, intent['tag']))


        # aggiungo classi al nostro elenco

        if intent['tag'] not in classes:

            classes.append(intent['tag'])

lemmatizer = WordNetLemmatizer()

words = [lemmatizer.lemmatize(w.lower()) for w in words if w not in ignore_words]

training = []

output_empty = [0] * len(classes)

for doc in documents:

    # bag of words

    bag = []

    # lista di token

    pattern_words = doc[0]

    # lemmatizzazione dei token

    pattern_words = [lemmatizer.lemmatize(word.lower()) for word in pattern_words]

    # se la parola corrisponde inserisco 1, altrimenti 0

    for w in words:

        bag.append(1) if w in pattern_words else bag.append(0)


    output_row = list(output_empty)

    output_row[classes.index(doc[1])] = 1

    training.append([bag, output_row])

# creazione del modello

model = Sequential()

model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(64, activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(len(train_y[0]), activation='softmax'))


sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)

model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])


#fitting and saving the model

hist = model.fit(np.array(train_x), np.array(train_y), epochs=300, batch_size=5, verbose=1)

model.save('chatbot_model.h5', hist)


print("Modello creato!")

# pre-elaborazione input utente

def clean_up_sentence(sentence):

    sentence_words = nltk.word_tokenize(sentence)

    sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]

    return sentence_words


# creazione bag of words

def bow(sentence, words, show_details=True):

    sentence_words = clean_up_sentence(sentence)

    bag = [0]*len(words)

    for s in sentence_words:

        for i,w in enumerate(words):

            if w == s:

                bag = 1

                if show_details:

                    print ("found in bag: %s" % w)

    return(np.array(bag))

# calcolo delle possibili risposte

def calcola_pred(sentence, model):

    p = bow(sentence, words,show_details=False)

    res = model.predict(np.array([p]))[0]

    ERROR_THRESHOLD = 0.25

    results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]

    # sort by strength of probability

    results.sort(key=lambda x: x[1], reverse=True)

    return_list = []

    for r in results:

        return_list.append({"intent": classes[r[0]], "probability": str(r[1])})

    return return_list

# restituzione della risposta

def getRisposta(ints, intents_json):

    tag = ints[0]['intent']

    list_of_intents = intents_json['intents']

    for i in list_of_intents:

        if(i['tag']== tag):

            result = random.choice(i['responses'])

            break

    return result

def conversa(msg):

    ints = calcola_pred(msg, model)

    res = getRisposta(ints, intents)

    print(res)

    return res


utente = ''

print('Benvenuto! Per uscire, scrivi "Esci"')


while utente.lower() != 'esci':

    utente = str(input(""))

    res = conversa(utente)

    print('AI:' + res) 
Grazie in anticipo per le risposte

1 Risposte

  • Re: Problema con python

    Te lo dice l'errore quale e' il problema!
    
    NameError: name 'train_x' is not defined
    
    RAGIONA!

    E sopprattutto, PRIMA STUDIA!
Devi accedere o registrarti per scrivere nel forum
1 risposte