TensorFlow 估计器的类数没有变化

2024-02-12

我尝试对 MNIST 数据集使用张量流估计器。由于某种原因它一直说我的n_classes即使它是 10,也被设置为 1!

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))

Error:

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 https://www.tensorflow.org/api_docs/python/tf/estimator/DNNClassifier正在使用tf.losses.sparse_softmax_cross_entropy https://www.tensorflow.org/api_docs/python/tf/losses/sparse_softmax_cross_entropy损失,换句话说,它期望ordinal编码,而不是one-hot(在文档中找不到它,只能源代码 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/estimator/canned/head.py#L459):

labels一定是稠密的Tensor与形状匹配logits,即[D0, D1, ... DN, 1]. If label_vocabulary given, labels必须是一个字符串Tensor与词汇表中的值。如果label_vocabulary没有给出,labels必须是整数Tensor具有指定类索引的值。

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

y=ydata.astype(np.int32)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TensorFlow 估计器的类数没有变化 的相关文章

随机推荐