简体   繁体   English

Plot 混淆矩阵使用 tensorflow 对 CNN 分类

[英]Plot confusion matrix using tensorflow on CNN classification

I'm trying to plot a confusion matrix to analyse my train and test and I'm having difficulties to print/plot the matrix.我正在尝试 plot 混淆矩阵来分析我的训练和测试,但我在打印/绘制矩阵时遇到了困难。 I'm using convolutional neural networks with Tensorflow for classification, and I have 3 labels to classify.我正在使用带有 Tensorflow 的卷积神经网络进行分类,并且我有 3 个标签要分类。

That's how I'm trying to print it:这就是我试图打印它的方式:

    true_class = tf.argmax(y, 1)
    predicted_class = tf.argmax(prediction, 1)
    confusion = tf.confusion_matrix(true_class, predicted_class, 3)

    print(confusion)

But the print returns me the following result:但打印返回我以下结果:

Tensor("confusion_matrix/SparseTensorDenseAdd:0", shape=(3, 3), dtype=int32)

Then I searched for people with the same problem and I tried doing this:然后我搜索了有同样问题的人,我试着这样做:

    true_class = tf.argmax(y, 1)
    predicted_class = tf.argmax(prediction, 1)
    confusion = tf.confusion_matrix(true_class, predicted_class, 3)

    print('Confusion Matrix: \n\n', tf.Tensor.eval(confusion,feed_dict=None, session=sess))

And it gives me the following error:它给了我以下错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float
         [[{{node Placeholder}}]]

My code:我的代码:

def convolutional_neural_network(x):
    number = calc()

    weights = {'W_conv1': tf.Variable(tf.random_normal([3, 3, 3, 1, 32])),
               'W_conv2': tf.Variable(tf.random_normal([3, 3, 3, 32, 64])),
               'W_fc': tf.Variable(tf.random_normal([number, 1024])),
               'out': tf.Variable(tf.random_normal([1024, n_classes]))}

    biases = {'b_conv1': tf.Variable(tf.random_normal([32])),
              'b_conv2': tf.Variable(tf.random_normal([64])),
              'b_fc': tf.Variable(tf.random_normal([1024])),
              'out': tf.Variable(tf.random_normal([n_classes]))}

    x = tf.reshape(x, shape=[-1, IMG_SIZE_PX, IMG_SIZE_PX, SLICE_COUNT, 1])

    conv1 = tf.nn.relu(conv3d(x, weights['W_conv1']) + biases['b_conv1'])
    conv1 = maxpool3d(conv1)

    conv2 = tf.nn.relu(conv3d(conv1, weights['W_conv2']) + biases['b_conv2'])
    conv2 = maxpool3d(conv2)

    fc = tf.reshape(conv2, [-1, number])
    fc = tf.nn.relu(tf.matmul(fc, weights['W_fc']) + biases['b_fc'])
    fc = tf.nn.dropout(fc, keep_rate)

    output = tf.matmul(fc, weights['out']) + biases['out']

    return output


def train_neural_network(x):
    much_data = np.load('muchdata-50-50-30-pre.npy', allow_pickle=True)
    train_data = much_data[400:410]
    validation_data = much_data[390:399]

    prediction = convolutional_neural_network(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(
        logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 1
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for data in train_data:
                X = data[0]
                Y = data[1]
                _, c = sess.run([optimizer, cost], feed_dict={x: X, y: Y})
                epoch_loss += c

            print('Epoch', epoch + 1, '/', hm_epochs, '. Loss:', epoch_loss)

        true_class = tf.argmax(y, 1)
        predicted_class = tf.argmax(prediction, 1)
        confusion = tf.confusion_matrix(true_class, predicted_class, 3)

        print('Confusion Matrix: \n\n', tf.Tensor.eval(confusion,feed_dict=None, session=sess))

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))

        saver = tf.train.Saver()

        saver.save(sess, '../api/modelo')

        print('Accuracy:', accuracy.eval(
            {x: [i[0] for i in validation_data], y: [i[1] for i in validation_data]}))

If anyone can help me figure out what's happening, I'll be very grateful.如果有人能帮我弄清楚发生了什么,我将不胜感激。 I'm new to this topic and I'm really struggling.我是这个话题的新手,我真的很挣扎。

Thank you so much!太感谢了!

You need to feed values to the placeholders in feed_dict .您需要将值提供给feed_dict中的占位符。 Can you try replacing the following line of your code,您可以尝试替换以下代码行吗?

print('Confusion Matrix: \n\n', tf.Tensor.eval(confusion,feed_dict=None, session=sess))

with the following, where your_X and your_Y are your test input and labels which we need to plot the confusion matrix on.使用以下内容,其中your_Xyour_Y是您的测试输入和标签,我们需要 plot 混淆矩阵。

print(sess.run(confusion, feed_dict={x:your_X, y:your_Y}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM