Py学习  »  Python

Python中用于推特分类的递归神经网络(LSTM)中的一个错误

Amir • 3 年前 • 1531 次点击  

我正试图通过LSTM改进结果。在我的项目中,我为RNN做了以下工作:

下面是一个用于训练模型的快速方法:

    def threshold_search(y_true, y_proba, average = None):
        best_threshold = 0
        best_score = 0
        for threshold in [i * 0.01 for i in range(100)]:
            score = f1_score(y_true=y_true, y_pred=y_proba > threshold, average=average)
            if score > best_score:
                best_threshold = threshold
                best_score = score
        search_result = {'threshold': best_threshold, 'f1': best_score}
        return search_result
    def train(model, 
              X_train, y_train, X_test, y_test, 
              checkpoint_path='model.hdf5', 
              epcohs = 25, 
              batch_size = DEFAULT_BATCH_SIZE, 
              class_weights = None, 
              fit_verbose=2,
              print_summary = True
             ):
        m = model()
        if print_summary:
            print(m.summary())
        m.fit(
            X_train, 
            y_train, 
            #this is bad practice using test data for validation, in a real case would use a seperate validation set
            validation_data=(X_test, y_test),
            epochs=epcohs, 
            batch_size=batch_size,
            class_weight=class_weights,
             #saves the most accurate model, usually you would save the one with the lowest loss
            callbacks= [
                ModelCheckpoint(checkpoint_path, monitor='val_acc', verbose=1, save_best_only=True),
                EarlyStopping(patience = 2)
            ],
            verbose=fit_verbose
        ) 
        print("\n\n****************************\n\n")
        print('Loading Best Model...')
        m.load_weights(checkpoint_path)
        predictions = m.predict(X_test, verbose=1)
        print('Validation Loss:', log_loss(y_test, predictions))
        print('Test Accuracy', (predictions.argmax(axis = 1) == y_test.argmax(axis = 1)).mean())
        print('F1 Score:', f1_score(y_test.argmax(axis = 1), predictions.argmax(axis = 1), average='weighted'))
        plot_confusion_matrix(y_test.argmax(axis = 1), predictions.argmax(axis = 1), classes=encoder.classes_)
        plt.show()    
        return m #returns best performing model

然后我使用了LSTM的简单实现。其中各层如下所示:

  • 嵌入:词向量矩阵,每个向量存储 这个词的“意义”。这些技能可以在飞行中训练,也可以通过现有技能进行训练 预训练向量。
  • LSTM:RNN,允许“构建” 随着时间的推移
  • 稠密(64):用于 解释LSTM输出
  • 稠密(3):这是模型的输出, 每个类对应3个节点。softmax输出将确保 每个输出的值之和=1.0。
def model_1():
    model = Sequential()
    model.add(Embedding(input_dim = (len(tokenizer.word_counts) + 1), output_dim = 128, input_length = MAX_SEQ_LEN))
    model.add(LSTM(128))
    model.add(Dense(64, activation='relu'))
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

m1 = train(model_1, 
           train_text_vec,
           y_train,
           test_text_vec,
           y_test,
           checkpoint_path='model_1.h5',
           class_weights= model.any(cws))

但我得到了以下输出和错误:

Screenshot of the error

正如您在屏幕截图中看到的,错误是:

ValueError:包含多个元素的数组的真值为 模棱两可的使用a.any()或a.all()

你能帮我解决这个错误吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129186
 
1531 次点击  
文章 [ 1 ]  |  最新文章 3 年前