python - Keras: .predict returns percentages instead of classes
问题描述
I am building a model with 3 classes: [0,1,2]
After training, the .predict
function returns a list of percentages instead.
I was checking the keras documentation but could not figure out, what I did wrong.
.predict_classes
is not working anymore, and I did not have this problem with previous classifiers. I already tried different activation functions (relu, sigmoid etc.)
If I understand correctly, the number inDense(3...)
defines the amount of classes.
outputs1=Dense(3,activation='softmax')(att_out)
model1=Model(inputs1,outputs1)
model1.summary()
model1.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=['accuracy'])
model1.fit(x=text_pad,y=train_y,batch_size=batch_size,epochs=epochs,verbose=1,shuffle=True)
y_pred = model1.predict(test_text_matrix)
Output example:
[[0.34014237 0.33570153 0.32415614]
[0.34014237 0.33570153 0.32415614]
[0.34014237 0.33570153 0.32415614]
[0.34014237 0.33570153 0.32415614]
[0.34014237 0.33570153 0.32415614]]
Output I want:
[1,2,0,0,0,1,2,0]
Thank you for any ideas.
解决方案
您没有做错任何事情,predict
始终返回模型的输出,对于分类器而言,这始终是每类的概率。
predict_classes
仅适用于Sequential
模型,不适用于功能模型。
但是有一个简单的解决方案,您只需要argmax
在最后一个维度上取,您将获得类索引:
y_probs = model1.predict(test_text_matrix)
y_pred = np.argmax(y_probs, axis=-1)
推荐阅读
- python - 为什么 spacy 不能区分以下代码中的两个同形异义词?
- php - foreach 循环中的 PHP 未设置对象,$key 是名称而不是迭代次数
- android - 约束布局宽度 0
- python - 如何在 tf.layers.max_pooling2d Tensorflow 中处理 0 批量大小?
- c++ - char 数组的操作如何导致堆栈溢出?
- angular - 循环依赖中带有警告的角度路由服务
- html - CSS 动画结束后显示 Div
- pytorch - 如何在 HPC 中使用 DistributedDataParallel() 和 init_process_group()?
- java - Jython 未加载 fxml 文件
- python - 在python中异步同一函数的多个实例