我该如何解决这个错误? NameError:名称“ model”未定义

时间:2018-06-23 11:45:57

标签: python machine-learning scikit-learn deep-learning

当我尝试输入文本以进行预测时,执行程序将显示“ NameError:未定义名称'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

准备文档单词编码包

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])

2 个答案:

答案 0 :(得分:1)

如果您在evaluate_mode()中进行训练,则该模型是局部变量,无法与predict_sentiment()共享。您应该让evaluate_mode()返回model,然后让predict_sentiment()当作第四个参数。

答案 1 :(得分:0)

evaluate_mode 函数中,您不会在不返回模型的情况下返回模型,因此会出现此类错误。在 predict_statement 中返回模型以进行下一次预测。