【发布时间】:2019-01-31 18:31:37
【问题描述】:
我正在构建一个 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,)
【问题讨论】:
-
欢迎来到 Stack Overflow!输出是单个激活,因此它似乎是单个二元类的概率。只需取一个操作点阈值(例如 0.5),如果概率相等或更大,则预测 true。事实上,这个网站上很可能还有一个对您有用的问题,但目前可能很难找到。
标签: python machine-learning keras deep-learning text-classification