python多分类混淆矩阵代码_python – 如何为tensorflow中的分类创建混淆矩阵

我有CNN模型,它有4个输出节点,我试图计算混淆矩阵,这样我就可以知道各个类的准确性.我能够计算出整体的准确性.

在链接here中,Igor Valantic给出了一个可以计算混淆矩阵变量的函数.

它在correct_prediction = tf.nn.in_top_k(logits,labels,1,name =“correct_answers”)给出了一个错误,错误是TypeError:attr’T’的DataType float32不在允许值列表中:int32,int64

我已经尝试过将类型转换为int32内部函数提到的def评估(logits,labels),它在计算correct_prediction =时给出了另一个错误:…作为TypeError:’InTopK’Op的输入’预测’的类型为int32,与预期类型不匹配float32

如何计算这种混淆矩阵?

sess = tf.Session()

model = dimensions() # CNN input weights are calculated

data_train, data_test, label_train, label_test = load_data(files_test2,folder)

data_train, data_test, = reshapedata(data_train, data_test, model)

# input output placeholders

x = tf.placeholder(tf.float32, [model.BATCH_SIZE, model.input_width,model.input_height,model.input_depth]) # last column = 1

y_ = tf.placeholder(tf.float32, [model.BATCH_SIZE, model.No_Classes])

p_keep_conv = tf.placeholder("float")

#

y = mycnn(x,model, p_keep_conv)

# loss

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))

# train step

train_step = tf.train.AdamOptimizer(1e-3).minimize(cost)

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

true_positives, false_positives, true_negatives, false_negatives = evaluation(y,y_)

lossfun = np.zeros(STEPS)

sess.run(tf.global_variables_initializer())

for i in range(STEPS):

image_batch, label_batch = batchdata(data_train, label_train, model.BATCH_SIZE)

epoch_loss = 0

for j in range(model.BATCH_SIZE):

sess.run(train_step, feed_dict={x: image_batch, y_: label_batch, p_keep_conv:1.0})

c = sess.run( cost, feed_dict={x: image_batch, y_: label_batch, p_keep_conv: 1.0})

epoch_loss += c

lossfun[i] = epoch_loss

print('Epoch',i,'completed out of',STEPS,'loss:',epoch_loss )

TP,FP,TN,FN = sess.run([true_positives, false_positives, true_negatives, false_negatives], feed_dict={x: image_batch, y_: label_batch, p_keep_conv:1.0})

这是我的代码片段

解决方法:

你可以简单地使用Tensorflow的confusion matrix.我假设y是你的预测,你可能有也可能没有num_classes(这是可选的)

y_ = placeholder_for_labels # for eg: [1, 2, 4]

y = mycnn(...) # for eg: [2, 2, 4]

confusion = tf.confusion_matrix(labels=y_, predictions=y, num_classes=num_classes)

如果你打印(混乱),你得到

[[0 0 0 0 0]

[0 0 1 0 0]

[0 0 1 0 0]

[0 0 0 0 0]

[0 0 0 0 1]]

如果print(混淆)没有打印混淆矩阵,则使用print(confusion.eval(session = sess)).这里是sess是TensorFlow会话的名称.

标签:python,tensorflow,confusion-matrix

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值