gpt4 book ai didi

python - 如何确定 Keras 上的卷积神经网络预测的二进制类别?

转载 作者:行者123 更新时间:2023-11-30 08:39:35 25 4
gpt4 key购买 nike

我正在构建一个 CNN 来对 Keras 进行情感分析。一切都很完美,模型已经过训练并准备投入生产。

但是,当我尝试使用 model.predict() 方法来预测新的未标记数据时,它仅输出相关的概率。我尝试使用 np.argmax() 方法,但它总是输出 0,即使它应该是 1(在测试集上,我的模型达到了 80% 的准确率)。

这是我预处理数据的代码:

# Pre-processing data
x = df[df.Sentiment != 3].Headlines
y = df[df.Sentiment != 3].Sentiment

# Splitting training, validation, testing dataset
x_train, x_validation_and_test, y_train, y_validation_and_test = train_test_split(x, y, test_size=.3,
random_state=SEED)
x_validation, x_test, y_validation, y_test = train_test_split(x_validation_and_test, y_validation_and_test,
test_size=.5, random_state=SEED)

tokenizer = Tokenizer(num_words=NUM_WORDS)
tokenizer.fit_on_texts(x_train)

sequences = tokenizer.texts_to_sequences(x_train)
x_train_seq = pad_sequences(sequences, maxlen=MAXLEN)

sequences_val = tokenizer.texts_to_sequences(x_validation)
x_val_seq = pad_sequences(sequences_val, maxlen=MAXLEN)

sequences_test = tokenizer.texts_to_sequences(x_test)
x_test_seq = pad_sequences(sequences_test, maxlen=MAXLEN)

这是我的模型:

MAXLEN = 25
NUM_WORDS = 5000
VECTOR_DIMENSION = 100

tweet_input = Input(shape=(MAXLEN,), dtype='int32')

tweet_encoder = Embedding(NUM_WORDS, VECTOR_DIMENSION, input_length=MAXLEN)(tweet_input)

# Combinating n-gram to optimize results
bigram_branch = Conv1D(filters=100, kernel_size=2, padding='valid', activation="relu", strides=1)(tweet_encoder)
bigram_branch = GlobalMaxPooling1D()(bigram_branch)
trigram_branch = Conv1D(filters=100, kernel_size=3, padding='valid', activation="relu", strides=1)(tweet_encoder)
trigram_branch = GlobalMaxPooling1D()(trigram_branch)
fourgram_branch = Conv1D(filters=100, kernel_size=4, padding='valid', activation="relu", strides=1)(tweet_encoder)
fourgram_branch = GlobalMaxPooling1D()(fourgram_branch)
merged = concatenate([bigram_branch, trigram_branch, fourgram_branch], axis=1)

merged = Dense(256, activation="relu")(merged)
merged = Dropout(0.25)(merged)
output = Dense(1, activation="sigmoid")(merged)

optimizer = optimizers.adam(0.01)

model = Model(inputs=[tweet_input], outputs=[output])
model.compile(loss="binary_crossentropy", optimizer=optimizer, metrics=['accuracy'])
model.summary()

# Training the model
history = model.fit(x_train_seq, y_train, batch_size=32, epochs=5, validation_data=(x_val_seq, y_validation))

我还尝试将最终 Dense 层上的激活数量从 1 更改为 2,但出现错误:

Error when checking target: expected dense_12 to have shape (2,) but got array with shape (1,)

最佳答案

您正在进行二元分类。因此,您有一个由一个单元组成的密集层,其激活函数为 sigmoid 。 Sigmoid 函数输出 [0,1] 范围内的值,该值对应于给定样本属于正类(即第一类)的概率。低于 0.5 的所有内容都标记为 0(即负类),所有高于 0.5 的内容都标记为 1。因此,要找到预测的类别,您可以执行以下操作:

preds = model.predict(data)
class_one = preds > 0.5

class_one 的真实元素对应于标记为 1 的样本(即正类)。

奖励:要了解预测的准确性,您可以轻松地将 class_one 与真实标签进行比较:

acc = np.mean(class_one == true_labels)

请注意,我假设 true_labels 由零和一组成。

<小时/>

此外,如果您的模型是使用 Sequential 类定义的,那么您可以轻松使用 predict_classes 方法:

pred_labels = model.predict_classes(data)

但是,由于您正在使用 Keras 函数式 API 来构建模型(在我看来,这样做是一件非常好的事情),因此您不能使用 predict_classes 方法,因为它是错误的-为此类模型定义。

关于python - 如何确定 Keras 上的卷积神经网络预测的二进制类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52018645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com