**计算混淆矩阵出现报错 **
@tf.function
def val_step(val_images, val_labels):
global output1
output1 = model(val_images, training=False)
loss = loss_object(val_labels, output1)
val_loss(loss)
val_accuracy(val_labels, output1)
best_val_acc = 0.
for epoch in range(epochs):
train_loss.reset_states() # clear history info
train_accuracy.reset_states() # clear history info
val_loss.reset_states() # clear history info
val_accuracy.reset_states() # clear history info
# train
train_bar = tqdm(train_ds, file=sys.stdout)
for images, labels in train_bar:
# update learning rate
optimizer.learning_rate = next(scheduler)
train_step(images, labels)
# print train process
train_bar.desc = "train epoch[{}/{}] loss:{:.3f}, acc:{:.3f}, lr:{:.5f}".format(
epoch + 1,
epochs,
train_loss.result(),
train_accuracy.result(),
optimizer.learning_rate.numpy()
)
# validate
val_bar = tqdm(val_ds, file=sys.stdout)#tqdm是进度条
for images, labels in val_bar:
val_step(images, labels)
# 计算混淆矩阵
cm = confusion_matrix(labels, output1)
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plot_confusion_matrix(cm)
print('每一类准确率:{}'.format(np.diagonal(cm)))
with open('confusion_matrix.csv', 'w+') as f:
for i in cm:
f.write(','.join(list(map(str, i))))
f.write('\n')
# print val process
val_bar.desc = "valid epoch[{}/{}] loss:{:.3f}, acc:{:.3f}".format(epoch + 1,
epochs,
val_loss.result(),
val_accuracy.result())
Traceback (most recent call last):
File "D:/ConvNeXT/train.py", line 238, in <module>
main()
File "D:/ConvNeXT/train.py", line 143, in main
cm = confusion_matrix(labels, output1)
File "C:\Users\Miaomiao\AppData\Roaming\Python\Python36\site-packages\sklearn\utils\validation.py", line 63, in inner_f
return f(*args, **kwargs)
File "C:\Users\Miaomiao\AppData\Roaming\Python\Python36\site-packages\sklearn\metrics\_classification.py", line 299, in confusion_matrix
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
File "C:\Users\Miaomiao\AppData\Roaming\Python\Python36\site-packages\sklearn\metrics\_classification.py", line 85, in _check_targets
type_pred = type_of_target(y_pred)
File "C:\Users\Miaomiao\AppData\Roaming\Python\Python36\site-packages\sklearn\utils\multiclass.py", line 261, in type_of_target
if is_multilabel(y):
File "C:\Users\Miaomiao\AppData\Roaming\Python\Python36\site-packages\sklearn\utils\multiclass.py", line 147, in is_multilabel
y = np.asarray(y)
File "D:\anconda\envs\tf-2.4.0\lib\site-packages\numpy\core\_asarray.py", line 83, in asarray
return array(a, dtype, copy=False, order=order)
File "D:\anconda\envs\tf-2.4.0\lib\site-packages\tensorflow\python\framework\ops.py", line 855, in __array__
" a NumPy call, which is not supported".format(self.name))
NotImplementedError: Cannot convert a symbolic Tensor (conv_ne_xt/head/BiasAdd:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported
Process finished with exit code 1
尝试过更改numpy版本
可以实现矩阵效果