python - Python 中用于推文分类的循环神经网络 (LSTM) 中的错误
问题描述
我正在尝试通过 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
- Dense(64):用于解释 LSTM 输出的前馈神经网络
- Dense(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))
但我得到以下输出和错误:
正如您在屏幕截图中看到的,错误是:
ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()
你能帮我解决这个错误吗?
解决方案
根据 Keras 文档和这个问题,class_weights
期望有一个字典将整数类索引映射到由浮点数表示的权重。
我不确定该行model.any(cws)
应该做什么,但通常一个.any()
函数返回一个布尔值或布尔值数组。由于 class_weights 需要一个 dict,它会恐慌并抛出一个 ValueError。
我的猜测是,您将模型权重(构成模型的数字)与类别权重(您要预测的事物的相对重要性)混淆了。如果是这种情况,将model_weights
设置保留为默认值应该可以解决您的问题。
推荐阅读
- ms-access - 从差异表单加载事件代码访问复选框值(真/假)
- java - 这是在 pom.xml 中定义 Junit 版本的正确方法吗?
- c# - 使用属性抑制 Coverity 中的消息?
- .net - Apache Ignite .Net 在会话中存储 ComplexType
- javascript - () 符号在这个嵌套的 Record 中是什么意思?反应
- javascript - 使用javascript模糊画布?
- c# - 没有“父”数组标识符的不同类型的 XML 数组序列化
- angular - 在 Angular flex 布局中完成 100 个单元后,我还没有找到换行的方法
- erlang - 如何在erlang案例中的不同案例情况之间进行通信
- android - 以编程方式将边距设置为 ConstraintLayout