R. Sch
R. Sch

Reputation: 19

How can I solve this error? NameError: name ‘model’ is not defined

When I try to enter a text in order to make predictions the execute gives me "NameError: name ‘model’ is not defined"

evaluate a neural network model

def evaluate_mode(Xtrain, ytrain, Xtest, ytest):

    scores = list()
    n_repeats = 2
    n_words = Xtest.shape[1]
    for i in range(n_repeats):
        # define network
        model = Sequential()
        model.add(Dense(50, input_shape=(n_words,), activation='relu'))
        model.add(Dense(1, activation='sigmoid'))
        # compile network
        model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
        # fit network
        model.fit(Xtrain, ytrain, epochs=10, verbose=2)
        # evaluate
        loss, acc = model.evaluate(Xtest, ytest, verbose=0)
        scores.append(acc)

        print('%d accuracy: %s' % ((i+1), acc))
    return scores

prepare bag of words encoding of docs

def prepare_data(train_docs, test_docs, mode):

    # create the tokenizer
    tokenizer = Tokenizer()
    # fit the tokenizer on the documents
    tokenizer.fit_on_texts(train_docs)
    # encode training data set
    Xtrain = tokenizer.texts_to_matrix(train_docs, mode=mode)
    # encode testing data set
    Xtest = tokenizer.texts_to_matrix(test_docs, mode=mode)
    return Xtrain, Xtest

def predict_sentiment(review, vocab, tokenizer, model):

        # clean
        tokens = clean_doc(review)
        # filter by vocab
        tokens = [w for w in tokens if w in vocab]
        # convert to line
        line = ' '.join(tokens)
        # encode
        encoded = tokenizer.texts_to_matrix([line], mode='freq')
        # prediction
        yhat = model.predict(encoded, verbose=0)
        return round(yhat[0,0])

Upvotes: 1

Views: 9949

Answers (2)

Kukesh
Kukesh

Reputation: 510

In evaluate_mode function your are not returning the model with out returning the model it will so such a kind of error.return the model for the next prediction in predict_statement.

Upvotes: 0

StkUsr0919
StkUsr0919

Reputation: 46

If you do the training process in evaluate_mode(), the model is a local variable and cannot be shared with predict_sentiment(). You should make evaluate_mode() return model and let predict_sentiment() take it as fourth argument.

Upvotes: 2

Related Questions