本文介绍了TensorFlow估计器的类数不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将tensorflow估计器用于MNIST数据集.出于某种原因,它一直说我的n_classes设置为1,即使它是10!

I tried using tensorflow estimator for the MNIST dataset. For some reason it keep saying my n_classes is set to 1 even though it is at 10!

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)


feature_columns = [tf.feature_column.numeric_column("x", shape=[784])]

# Build 3 layer DNN with 10, 20, 10 units respectively.
classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
                                        hidden_units=[500, 500, 500],
                                        n_classes=10,
                                        model_dir="/tmp/MT")
for i in range(100000):
    xdata, ydata = mnist.train.next_batch(500)
    train_input_fn = tf.estimator.inputs.numpy_input_fn(
        x={"x":xdata},
        y=ydata,
        num_epochs=None,
        shuffle=True)
    classifier.train(input_fn=train_input_fn, steps=2000)

# Define the test inputs
test_input_fn = tf.estimator.inputs.numpy_input_fn(
    x= {"x":mnist.test.images},
    y= mnist.test.labels,
    num_epochs=1,
    shuffle=False)

# Evaluate accuracy.
accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"]

print("\nTest Accuracy: {0:f}\n".format(accuracy_score))

错误:

ValueError: Mismatched label shape. Classifier configured with n_classes=1.  Received 10. Suggested Fix: check your n_classes argument to the estimator and/or the shape of your label.

Process finished with exit code 1

推荐答案

这是一个很好的问题. tf.estimator.DNNClassifier 正在使用 tf.losses.sparse_softmax_cross_entropy 丢失,换句话说,它期望使用 ordinal 编码,而不是 one (在文档中找不到,只有源代码):

That's a good question. tf.estimator.DNNClassifier is using tf.losses.sparse_softmax_cross_entropy loss, in other words it expects ordinal encoding, instead of one-hot (can't find it in the doc, only the source code):

您应该使用one_hot=False读取数据,并将标签转换为int32以使其正常工作:

You should read the data with one_hot=False and also cast the labels to int32 to make it work:

y=ydata.astype(np.int32)

这篇关于TensorFlow估计器的类数不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 19:36