Tensorflow:logits 和标签必须具有相同的第一维

Geo*_*ost 18 python keras tensorflow tensorflow-datasets tensorflow-estimator

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

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)
Run Code Online (Sandbox Code Playgroud)

我在标签和 logits 之间有一个形状大小错误:

InvalidArgumentError(回溯见上文):logits 和标签必须具有相同的第一维,得到 logits 形状 [3,2] 和标签形状 [1]

filenames_array 是一个 16 个字符串的数组

["file1.png", "file2.png", "file3.png", ...]
Run Code Online (Sandbox Code Playgroud)

和 labels_array 是一个 16 个整数的数组

[0,0,1,1,0,1,0,0,0,...]
Run Code Online (Sandbox Code Playgroud)

主要功能是:

# 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])
Run Code Online (Sandbox Code Playgroud)

我试图重塑 logits 没有成功:

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

我需要你的帮助,谢谢


编辑

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

input_layer = tf.reshape(features, [-1, 40, 40, 1])
Run Code Online (Sandbox Code Playgroud)

表示将动态计算 batch_size 维度的“-1”在此处具有值“3”。与我的错误相同的“3”:logits 和标签必须具有相同的第一维,得到 logits 形状 [3,2] 和标签形状 [1]

如果我将值强制为“1”,则会出现此新错误:

reshape 的输入是一个有 4800 个值的张量,但请求的形状有 1600

也许我的功能有问题?


编辑2:

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


编辑3

我更新了要点

logits = tf.layers.dense(inputs=dropout, units=1)
Run Code Online (Sandbox Code Playgroud)

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

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

如果我选择 batch_size = 3 我有这个错误: logits 和标签必须具有相同的第一维,得到 logits 形状 [9,1] 和标签形状 [3]

我试图重塑标签:

labels = tf.reshape(labels, [3, 1])
Run Code Online (Sandbox Code Playgroud)

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

    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]]
Run Code Online (Sandbox Code Playgroud)

但没有成功...

Mar*_*ani 49

问题出在您的目标形状上,并且与正确选择合适的损失函数有关。你有两种可能性:

1.可能性:如果你有一个一维整数编码的目标,你可以sparse_categorical_crossentropy用作损失函数

n_class = 3
n_features = 100
n_sample = 1000

X = np.random.randint(0,10, (n_sample,n_features))
y = np.random.randint(0,n_class, n_sample)

inp = Input((n_features,))
x = Dense(128, activation='relu')(inp)
out = Dense(n_class, activation='softmax')(x)

model = Model(inp, out)
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)
Run Code Online (Sandbox Code Playgroud)

2.可能性:如果您对目标进行单热编码以获得2D形状(n_samples,n_class),则可以使用categorical_crossentropy

n_class = 3
n_features = 100
n_sample = 1000

X = np.random.randint(0,10, (n_sample,n_features))
y = pd.get_dummies(np.random.randint(0,n_class, n_sample)).values

inp = Input((n_features,))
x = Dense(128, activation='relu')(inp)
out = Dense(n_class, activation='softmax')(x)

model = Model(inp, out)
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)
Run Code Online (Sandbox Code Playgroud)


小智 27

我解决了它从sparse_categorical_crossentropy改为categorical_crossentropy现在运行良好。

  • 这对我有帮助。我也不知道为什么。 (3认同)
  • 这里的解释:/sf/ask/3441282211/#62286888 (3认同)

小智 9

我第一次使用 tensorflow 时已经遇到了这个问题,我发现我的问题是忘记将属性class_mode='sparse'/添加class_mode='binary'到上传训练数据和验证数据的函数中:

所以尽量注意 class_mode 选项

image_gen_val = ImageDataGenerator(rescale=1./255)
val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,
                                                 directory=val_dir,
                                                 target_size=(IMG_SHAPE, IMG_SHAPE),
                                                 class_mode='sparse')
Run Code Online (Sandbox Code Playgroud)


thu*_*v89 7

我想我应该为不同标签表示的推荐方法提供更具说明性的答案以及对正在发生的事情的一些见解。

首先是一些背景。我们有 3 个数据点和 5 个可能的标签(0 索引)以下是您在 ML 问题中会遇到的不同类型的标签。

在此输入图像描述

代码 (tensorflow2

假设我们有以下虚拟数据和模型

import tensorflow as tf
import numpy as np

ohe_labels = np.array([[0, 0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]])
labels = np.argmax(ohe_labels, axis=-1)

x = np.random.normal(size=(3, 10))

model = tf.keras.models.Sequential(
    [
        tf.keras.layers.Dense(20, 'relu', input_shape=(10,)),
        tf.keras.layers.Dense(5, 'softmax')
    ]
)
Run Code Online (Sandbox Code Playgroud)
# This works!

model.compile(loss='categorical_crossentropy', optimizer='adam')
model.fit(x, ohe_labels)

# This also works!
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam')
model.fit(x, labels)

# This does NOT (Different error - ValueError: Shapes ... are incompatible)!
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.fit(x, labels)

# This does NOT (Gives the above error)!
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam')
model.fit(x, ohe_labels)
Run Code Online (Sandbox Code Playgroud)

什么时候触发这个错误?

该错误是在特殊情况下触发的。让我解释一个每个输入有一个标签的问题(解释也适用于多标签设置 - 但需要更多添加的细节)。第一个(批量)维度需要匹配,但是一旦labels被重塑为一维向量,如果第一个维度logits和长度labels不匹配,就会触发此错误。