Keras 总是预测相同的输出

Keras always predicting the same output

Keras 总是会为我给 hm 的每个输入预测相同的 class。目前有四个 classes。 新闻、天气、体育和经济。

训练集由很多不同的文本组成,其中 class 与其主题相同。 class化为新闻和体育的文本比天气和经济的文本多得多。

我原以为该模型会偏向体育和新闻,但它完全偏向天气,每个输入都被class确定为天气,至少有 80% 的置信度。

只是为了增加我的困惑:在训练时,注释器将达到 95% 到 100% 的准确率分数(原文如此!)。我想我在这里做了一些非常愚蠢的事情,但我不知道它是什么。

这就是我对 classifier 的称呼。它在 Windows 电脑上的 python 3 上运行。

with open('model.json') as json_data:
model_JSON = json.load(json_data)

model_JSON = json.dumps(model_JSON) 
model = model_from_json(model_JSON)

model.load_weights('weights.h5')

text = str(text.decode())   
encoded = one_hot(text, max_words, split=" ")

tokenizer = Tokenizer(num_words=max_words)
matrix = tokenizer.sequences_to_matrix([encoded], mode='binary')

result = model.predict(matrix)

legende = ["News", "Wetter", "Sport", "Wirtschaft"]
print(str(legende))
print(str(result))

cat = numpy.argmax(result)  
return str(legende[cat]).encode()

这就是我训练 classifier 的方式。我省略了从数据库中获取数据的部分。这是在 Linux 虚拟机上完成的。 我已经尝试改变周围的损失和激活,但没有任何反应。 此外,我目前正在尝试使用更多的时代,但到目前为止,这也没有帮助。

max_words = 10000
batch_size=32
epochs=15

rows = cursor.fetchall()

X = []
Y = []

# Einlesen der Rows
for row in rows:
    X.append(row[5])
    Y.append(row[1])

num_classes = len(set(Y))
Y = one_hot("$".join(Y), num_classes, split="$")


for i in range(len(X)):
    X[i] = one_hot(str(X[i]), max_words, split=" ")

split = round(len(X) * 0.2)     

x_test = np.asarray(X[0:int(split)])
y_test = np.asarray(Y[0:int(split)])

x_train = np.asarray(X[int(split):len(X)])
y_train = np.asarray(Y[int(split):len(X)])

print('x_test shape', x_test.shape)
print('y_test shape', y_test.shape)

print(num_classes, 'classes')

#vektorisieren
tokenizer = Tokenizer(num_words=max_words)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')

#klassenvektor zu binärer klassenmatrix
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

#model erstellen
model = Sequential()

model.add(Dense(512, input_shape=(max_words,)))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
    optimizer='adam',
    metrics=['accuracy'])


history = model.fit(x_train, y_train,
    batch_size=batch_size,
    epochs=epochs,
    verbose=1,
    validation_split=0.1
    )

score = model.evaluate(x_test, y_test,
    batch_size=batch_size, 
    verbose=1
    )

print('Test score', score[0])
print('Test accuracy', score[1])

#write model to json
print("writing model to json")
model_json = model.to_json()
with open("model.json", 'w') as json_file:
    json_file.write(model_json)

#save weights as hdf5
print("saving weights to hdf5")
model.save_weights("weights.h5")

感谢 @Daniel Möller 给我的提示,我发现了问题所在。他的建议是查看训练集中每个 Class 的实例数量。

在我的例子中,我发现用 One_Hot 散列你的 类 并不聪明,因为它有时会用相同的数字编码多个 类。对我来说 One_Hot 几乎所有东西都编码为 1。这样 Keras 学会了只预测 1。