【问题标题】:Multiclass classification report in KerasKeras 中的多类分类报告
【发布时间】:2022-01-11 12:47:33
【问题描述】:

所以,我手头有 4 个类别的分类问题。我已经建立了一个ANN如下:

import tensorflow as tf
from keras.layers import Flatten
ann=tf.keras.models.Sequential()
ann.add(tf.keras.layers.Dense(units=17,activation='relu')) 
ann.add(tf.keras.layers.Dense(units=17,activation='relu'))
ann.add(tf.keras.layers.Dense(units=17,activation='relu'))
ann.add(tf.keras.layers.Dense(units=17,activation='relu'))
ann.add(tf.keras.layers.Dense(units=4,activation='softmax')) #output
ann.add(Flatten())

ann.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics = 
['sparse_categorical_accuracy'])
ann.fit(scaled_xtrain,ytrain,batch_size=8, epochs=20,validation_split=0.2)


test_loss, test_acc = ann.evaluate(scaled_xtest, ytest)
train_loss, train_acc = ann.evaluate(scaled_xtrain, ytrain)
print('Test Accuracy: ', test_acc, '\nTest Loss: ', test_loss)
print('Train Accuracy: ', train_acc, '\nTrain Loss: ', train_loss)

我想查看以下格式的分类报告:

             precision    recall  f1-score   support

       0       0.81      0.76      0.78        88
       1       0.51      0.57      0.54        53
       2       0.62      0.59      0.60        71
       3       0.69      0.72      0.71        57

accuracy                           0.67       269
macro avg       0.66      0.66      0.66       269
weighted avg       0.67      0.67      0.67       269

但是当我写代码时:

from sklearn.metrics import confusion_matrix
ypred= ann.predict_classes(xtest)
ypred= (ypred >0.5)
matrix = confusion_matrix(ytest,ypred)

我收到以下错误:

TypeError                                 Traceback (most recent 
call last)
 <ipython-input-41-42c5ccb6a924> in <module>()
  2 ypred= ann.predict(xtest)
  3 ypred= (ypred >0.5)
  ----> 4 matrix = confusion_matrix(ytest.argmax(axis=0), 
  ypred.argmax(axis=0))

  4 frames
  /usr/local/lib/python3.7/dist- 
  packages/sklearn/utils/validation.py in _num_samples(x)
  267         if len(x.shape) == 0:
  268             raise TypeError(
  --> 269                 "Singleton array %r cannot be 
  considered a valid collection." % x
  270             )
  271         # Check that shape is returning an integer or 
  default to len

  TypeError: Singleton array 2 cannot be considered a valid 
  collection.

请帮忙!!

【问题讨论】:

  • 可以使用sklearn的分类报告
  • 嗨。我刚刚添加了我得到的错误

标签: python tensorflow keras


【解决方案1】:

对于您的问题,如果您想要分类报告,请尝试sklearn.metrics.classification_report。

y_pred_class = model.predict_classes(test_images) ## xtest => test image
y_pred = model.predict(test_images)               ## xtest => test image
y_test_class = np.argmax(test_labels, axis=1)     ## ytest => test image's label

print(classification_report(y_test_class, y_pred_class))
print(confusion_matrix(test_labels.argmax(axis=1), y_pred.argmax(axis=1)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 2015-07-26
    • 2021-08-17
    • 1970-01-01
    • 2021-05-28
    • 2018-08-04
    • 2017-05-25
    • 2018-03-08
    相关资源
    最近更新 更多