简体   繁体   中英

Getting InvalidArgumentError in softmax_cross_entropy_with_logits

I'm pretty new to tensorflow and trying to do some experiments with the Iris dataset. I created following model function (MWE):

def model_fn(features, labels, mode):
    net = tf.feature_column.input_layer(features, [tf.feature_column.numeric_column(key=key) for key in FEATURE_NAMES])

    logits = tf.layers.dense(inputs=net, units=3)

    loss = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)

    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)

Unfortunately I get the following error:

InvalidArgumentError: Input to reshape is a tensor with 256 values, but the requested shape has 1
 [[Node: Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](softmax_cross_entropy_with_logits_sg, Reshape/shape)]]

Seems to be some problem with the shapes of the tensors. However both logits and labels have an equal shape of (256, 3) - as it is required by the documentation . Also both tensors have type float32.


Just for the sake of completeness, here is the input function for the estimator:

import pandas as pd
import tensorflow as tf
import numpy as np

IRIS_DATA = "data/iris.csv"

FEATURE_NAMES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
CLASS_NAME = ["class"]

COLUMNS = FEATURE_NAMES + CLASS_NAME

# read dataset
iris = pd.read_csv(IRIS_DATA, header=None, names=COLUMNS)

# encode classes
iris["class"] = iris["class"].astype('category').cat.codes

# train test split
np.random.seed(1)
msk = np.random.rand(len(iris)) < 0.8
train = iris[msk]
test = iris[~msk]

def iris_input_fn(batch_size=256, mode="TRAIN"):
    def prepare_input(data=None):

        #do mean normaization across all samples
        mu = np.mean(data)
        sigma = np.std(data)

        data = data - mu
        data = data / sigma
        is_nan = np.isnan(data)
        is_inf = np.isinf(data)
        if np.any(is_nan) or np.any(is_inf):
            print('data is not well-formed : is_nan {n}, is_inf: {i}'.format(n= np.any(is_nan), i=np.any(is_inf)))


        data = transform_data(data)
        return data

    def transform_data(data):
        data = data.astype(np.float32)
        return data


    def load_data():
        global train

        trn_all_data=train.iloc[:,:-1]
        trn_all_labels=train.iloc[:,-1]


        return (trn_all_data.astype(np.float32),
                                              trn_all_labels.astype(np.int32))

    data, labels = load_data()
    data = prepare_input(data)

    labels = tf.one_hot(labels, depth=3)

    labels = tf.cast(labels, tf.float32)
    dataset = tf.data.Dataset.from_tensor_slices((data.to_dict(orient="list"), labels))

    dataset = dataset.shuffle(1000).repeat().batch(batch_size)

    return dataset.make_one_shot_iterator().get_next()

Dataset from UCI repo

Solved the problem by replacing the loss function from nn module:

loss = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)

by the loss function of losses module

loss = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits)

or by

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits))

loss which is fed to the minimize method of GradientDescentOptimizer needed to be a scalar. A single value for the whole batch.

Problem was, I computed the softmax cross entropy for each element in the batch, which resulted in a tensor containing 256 (batch size) cross entropy values, and tried to feed this in the minimize method. Therefore the error message

Input to reshape is a tensor with 256 values, but the requested shape has 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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