本文介绍了Tensorflow:logit和标签必须具有相同的第一维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是tensoflow的新手,我想改编MNIST教程 https://www.tensorflow. org/tutorials/layers 和我自己的数据(40x40的图像).这是我的模型函数:

I am new in tensoflow and I want to adapt the MNIST tutorial https://www.tensorflow.org/tutorials/layers with my own data (images of 40x40).This is my model function :

def cnn_model_fn(features, labels, mode):
        # Input Layer
        input_layer = tf.reshape(features, [-1, 40, 40, 1])

        # Convolutional Layer #1
        conv1 = tf.layers.conv2d(
                inputs=input_layer,
                filters=32,
                kernel_size=[5, 5],
                #  To specify that the output tensor should have the same width and height values as the input tensor
                # value can be "same" ou "valid"
                padding="same",
                activation=tf.nn.relu)

        # Pooling Layer #1
        pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

        # Convolutional Layer #2 and Pooling Layer #2
        conv2 = tf.layers.conv2d(
                inputs=pool1,
                filters=64,
                kernel_size=[5, 5],
                padding="same",
                activation=tf.nn.relu)
        pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)

        # Dense Layer
        pool2_flat = tf.reshape(pool2, [-1, 10 * 10 * 64])
        dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
        dropout = tf.layers.dropout(
                inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN)

        # Logits Layer
        logits = tf.layers.dense(inputs=dropout, units=2)

        predictions = {
            # Generate predictions (for PREDICT and EVAL mode)
            "classes":       tf.argmax(input=logits, axis=1),
            # Add `softmax_tensor` to the graph. It is used for PREDICT and by the
            # `logging_hook`.
            "probabilities": tf.nn.softmax(logits, name="softmax_tensor")
        }

        if mode == tf.estimator.ModeKeys.PREDICT:
            return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

        # Calculate Loss (for both TRAIN and EVAL modes)
        loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)

        # Configure the Training Op (for TRAIN mode)
        if mode == tf.estimator.ModeKeys.TRAIN:
            optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
            train_op = optimizer.minimize(
                    loss=loss,
                    global_step=tf.train.get_global_step())
            return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)

        # Add evaluation metrics (for EVAL mode)
        eval_metric_ops = {
            "accuracy": tf.metrics.accuracy(
                    labels=labels, predictions=predictions["classes"])}
        return tf.estimator.EstimatorSpec(
                mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)

我在标签和logit之间有形状尺寸错误:

I have a shape size error between labels and logits :

InvalidArgumentError(请参见上面的回溯):logits和标签的第一维必须相同,logits形状为[3,2],标签形状为[1]

filenames_array是由16个字符串组成的数组

filenames_array is an array of 16 string

["file1.png", "file2.png", "file3.png", ...]

and labels_array是一个由16个整数组成的数组

and labels_array is an array of 16 integer

[0,0,1,1,0,1,0,0,0,...]

主要功能是:

# Create the Estimator
mnist_classifier = tf.estimator.Estimator(model_fn=cnn_model_fn, model_dir="/tmp/test_convnet_model")

# Train the model
cust_train_input_fn = lambda: train_input_fn_custom(
        filenames_array=filenames, labels_array=labels, batch_size=1)

mnist_classifier.train(
        input_fn=cust_train_input_fn,
        steps=20000,
        hooks=[logging_hook])

我试图重塑logit,但没有成功:

I tried to reshape logits without success :

logits = tf.reshape(logits,[1,2])

logits = tf.reshape(logits, [1, 2])

我需要您的帮助,谢谢

编辑

经过更多时间的搜索,在模型函数的第一行

After more time to search, in the first line of my model function

input_layer = tf.reshape(features, [-1, 40, 40, 1])

表示将动态计算batch_size尺寸的"-1"在这里具有值"3".与我的错误相同的"3":日志和标签的第一个尺寸必须相同,其日志形状为[3,2],标签的形状为[1]

the "-1" that signifies that the batch_size dimension will be dynamically calculated have here the value "3". The same "3" as in my error : logits and labels must have the same first dimension, got logits shape [3,2] and labels shape [1]

如果我将值强制设置为"1",则会出现此新错误:

If I force the value to "1" I have this new error :

要重塑的输入是具有4800个值的张量,但请求的形状有1600

我的功能可能有问题吗?

Maybe a problem with my features ?

完整的代码在这里: https://gist.github.com/geoffreyp/cc8e97aab1bff4d39e10001118c6322e

EDIT3

我用

logits = tf.layers.dense(inputs=dropout, units=1)

https://gist.github.com/geoffreyp/cc8e97aab1bff4d39e10001118c6322e

但是我不完全理解您关于批量大小的答案,这里的批量大小如何为3,而我选择的批量大小为1?

But I don't completely understand your answer about the batch size, how the batch size can be 3 here whereas I choose a batch size of 1 ?

如果我选择batch_size = 3,则会出现此错误:日志和标签的第一维必须相同,日志的形状为[9,1],标签的形状为[3]

If I choose a batch_size = 3 I have this error :logits and labels must have the same first dimension, got logits shape [9,1] and labels shape [3]

我试图重塑标签:

labels = tf.reshape(labels, [3, 1])

我更新了功能和标签结构:

and I updated features and labels structure :

    filenames_train = [['blackcorner-data/1.png', 'blackcorner-data/2.png', 'blackcorner-data/3.png',
                   'blackcorner-data/4.png', 'blackcorner-data/n1.png'],
                   ['blackcorner-data/n2.png',
                   'blackcorner-data/n3.png', 'blackcorner-data/n4.png',
                   'blackcorner-data/11.png', 'blackcorner-data/21.png'],
                   ['blackcorner-data/31.png',
                   'blackcorner-data/41.png', 'blackcorner-data/n11.png', 'blackcorner-data/n21.png',
                   'blackcorner-data/n31.png']
                   ]

labels = [[0, 0, 0, 0, 1], [1, 1, 1, 0, 0], [0, 0, 1, 1, 1]]

但没有成功...

推荐答案

我解决了它从"sparse_categorical_crossentropy"更改为"categorical_crossentropy"的问题,现在运行正常.

I resolved it changing from "sparse_categorical_crossentropy" to "categorical_crossentropy" and is now running fine.

不知道这是否对某人有用.

Don't know if this could be helpful for someone.

我是新来的,所以请客气:)

I'm new to this so please be kind :)

这篇关于Tensorflow:logit和标签必须具有相同的第一维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 03:10