【问题标题】:TensorFlow estimator number of classes does not changeTensorFlow 估计器的类数不变
【发布时间】:2018-06-15 07:18:44
【问题描述】:

我尝试对 MNIST 数据集使用 tensorflow 估计器。出于某种原因,它一直说我的n_classes 设置为 1,即使它是 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

【问题讨论】:

    标签: python tensorflow machine-learning deep-learning mnist


    【解决方案1】:

    这是个好问题。 tf.estimator.DNNClassifier 正在使用 tf.losses.sparse_softmax_cross_entropy 损失,换句话说,它需要 ordinal 编码,而不是 one-hot (在文档中找不到它,只有 @987654323 @):

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

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

    y=ydata.astype(np.int32)
    

    【讨论】:

    • 谢谢!有效! :) 但将来我可能需要为其他项目使用一种热编码。 DNNRegressor 会成功吗?
    • regressor 正在做回归任务,恐怕没用。我认为一种选择是使用纯张量流,您可以在其中轻松定义自己的损失。请参阅此示例 - github.com/aymericdamien/TensorFlow-Examples/blob/master/…
    猜你喜欢
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2019-01-04
    相关资源
    最近更新 更多