【问题标题】:tensorflow feature_column tries to reshape featurestensorflow feature_column 尝试重塑特征
【发布时间】:2019-03-09 20:12:29
【问题描述】:

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

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

这是我定义模型的方式:

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 函数的方式:

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)

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

ValueError: 不能用 784 个元素对张量进行整形,以便为“input_layer/image/Reshape”(操作:“Reshape”)整形 [28,784](21952 个元素),输入形状为:[28,28]、2 和输入张量计算为部分形状:input1 = [28,784]。

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

【问题讨论】:

  • 为什么在数据集 api 旁边使用特征列?
  • @Sharky tensorflows 教程在tensorflow.org/guide/custom_estimators 中执行此操作,我不应该使用特征列吗?
  • 不带图片。 # create net 这里发生了什么?
  • @Sharky 我正在定义我的网络层,第一个是输入层,这就是错误发生的地方,我没有放其余代码,因为它似乎无关紧要。但紧随其后的是两个密集层。那么如何定义没有特征列的输入层呢?我见过的每个例子都有这些。
  • 添加您的型号代码

标签: python tensorflow mnist tensorflow-estimator


【解决方案1】:

首先,您需要批量生产。更多详情见https://www.tensorflow.org/guide/datasets

...
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
dataset = dataset.batch(size)
  return dataset

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

    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)

【讨论】:

  • 解决了它,尽管我还在第一行将 features 更改为 feature['image'] (供未来的读者使用)。非常感谢。
猜你喜欢
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 2021-09-23
  • 1970-01-01
相关资源
最近更新 更多