关于python:tensorflow feature_column 试图重塑特征

tensorflow feature_column tries to reshape features

我正在尝试使用自定义估计器为 MNIST 数据集实现网络。
这是我的输入函数:

1
2
3
4
5
6
7
8
9
def input_train_fn():
  train, test = tf.keras.datasets.mnist.load_data()
  mnist_x, mnist_y = train
  mnist_y = tf.cast(mnist_y, tf.int32)
  mnist_x = tf.cast(mnist_x, tf.int32)
  features = {'image': mnist_x}
  labels = mnist_y
  dataset = tf.data.Dataset.from_tensor_slices((features, labels))
  return dataset

这是我定义模型的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def my_model(features, labels, mode, params):
    # create net
    net = tf.feature_column.input_layer(features, params['feature_columns'])
    # create hidden layers
    for unit in params['hidden_units']:
        net = tf.layers.dense(net, unit, tf.nn.relu)
    # create output layer
    legits = tf.layers.dense(net, params['n_classes'], activation=None)
    # predict (if in predict mode)
    predicted_classes = tf.arg_max(legits, 1)
    if mode == tf.estimator.ModeKeys.PREDICT:
        predictions = {
            'class_ids': predicted_classes,
            'probabilities': tf.nn.softmax(legits),
            'logits': legits
        }
        return tf.estimator.EstimatorSpec(mode, predictions=predictions)
    # define loss function
    loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=legits)
    # evaluation metrics
    accuracy = tf.metrics.accuracy(labels=labels,
                                   predictions=predicted_classes,
                                   name='acc_op')
    metrics = {'accuracy': accuracy}
    tf.summary.scalar('accuracy', accuracy[1])
    if mode == tf.estimator.ModeKeys.EVAL:
        return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics)

    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
    train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)

这就是我调用 train 函数的方式:

1
2
3
4
5
6
7
8
feature_columns = [tf.feature_column.numeric_column('image', shape=[28, 28], dtype=tf.int32), ]
classifier = tf.estimator.Estimator(model_fn=my_model,
                       params={
                           'feature_columns': feature_columns,
                           'hidden_units': [10, 10],
                           'n_classes': 10,
                       }, model_dir='/model')
classifier.train(input_fn=input_train_fn, steps=10)

据我所知,我正在为 estimators 和 feature_columns 做所有事情,但我得到了错误:

ValueError: Cannot reshape a tensor with 784 elements to shape [28,784] (21952 elements) for 'input_layer/image/Reshape' (op: 'Reshape') with input shapes: [28,28], 2 and with input tensors computed as partial shapes: input1 = [28,784].

我有什么遗漏吗?
在此先感谢您的帮助。


首先,您需要批量生产。有关更多详细信息,请参阅 https://www.tensorflow.org/guide/datasets

1
2
3
4
...
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
dataset = dataset.batch(size)
  return dataset

然后重塑您的图像并投射到 float。 -1 用于 batch_size,它将在训练期间被替换。根据提供的数据类型,将标签转换为浮动是可选的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    net = tf.cast(tf.reshape(features, [-1, 28*28]), tf.float32)
    labels = tf.cast(labels, tf.int64)
    net = tf.layers.dense(net, 10, tf.nn.relu)
    legits = tf.layers.dense(net, 10, activation=None)
    predicted_classes = tf.arg_max(legits, 1)
    if mode == tf.estimator.ModeKeys.PREDICT:
        predictions = {
            'class_ids': predicted_classes,
            'probabilities': tf.nn.softmax(legits),
            'logits': legits
        }
        return tf.estimator.EstimatorSpec(mode, predictions=predictions)

    loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=legits)

    if mode == tf.estimator.ModeKeys.EVAL:
        return tf.estimator.EstimatorSpec(mode, loss=loss)

    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
    train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)

classifier = tf.estimator.Estimator(model_fn=my_model)

classifier.train(input_fn=lambda: input_train_fn(), steps=10)