首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何输入Tensorflow估计器的正确形状?

如何输入Tensorflow估计器的正确形状?
EN

Stack Overflow用户
提问于 2019-01-04 20:34:49
回答 1查看 770关注 0票数 0

我正在尝试构建一个在SageMaker上使用的Tensorflow估计器。主要功能是对估计器进行训练和评估。尽管我尽了最大的努力,但我还是遇到了以下错误:

ValueError:层输入的输入0与图层不兼容:期望的ndim=3,找到的ndim=2。收到的完整形状: 50,41。

代码语言:javascript
复制
def keras_model_fn(hyperparameters):
    """keras_model_fn receives hyperparameters from the training job and returns a compiled keras model.
    The model will be transformed into a TensorFlow Estimator before training and it will be saved in a 
    TensorFlow Serving SavedModel at the end of training.

    Args:
        hyperparameters: The hyperparameters passed to the SageMaker TrainingJob that runs your TensorFlow 
                         training script.
    Returns: A compiled Keras model
    """
    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.LSTM(32, name='inputs', input_shape=( None, 41)))
    model.add(tf.keras.layers.Dense(11, activation='softmax', name='dense'))
    model.compile(loss='categorical_crossentropy',
                  optimizer='rmsprop',
                  metrics=['accuracy'])

    return model


def train_input_fn(training_dir=None, hyperparameters=None):
    # invokes _input_fn with training dataset
    dataset = tf.data.Dataset.from_tensors(({INPUT_TENSOR_NAME: x_train}, y_train))
    dataset = dataset.repeat()
    return dataset.make_one_shot_iterator().get_next()

def eval_input_fn(training_dir=None, hyperparameters=None):
    # invokes _input_fn with evaluation dataset

    dataset =  tf.data.Dataset.from_tensors(({INPUT_TENSOR_NAME: x_test}, y_test))
    return dataset.make_one_shot_iterator().get_next()

if __name__ == '__main__':
    print(x_train.shape, y_train.shape)
    tf.logging.set_verbosity(tf.logging.INFO)
    model = keras_model_fn(0)
    estimator = tf.keras.estimator.model_to_estimator(keras_model=model)
    train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=1000)
    eval_spec = tf.estimator.EvalSpec(input_fn=eval_input_fn)
    tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)

我的输入和输出形状如下:

(52388、50、41) (52388、11)

EN

回答 1

Stack Overflow用户

发布于 2019-01-05 09:57:06

from_tensors将输入张量转换为单大张量。例如,如果运行以下示例:

代码语言:javascript
复制
import tensorflow as tf

tf.enable_eager_execution()

dataset2 = tf.data.Dataset.from_tensors(
    (tf.random_uniform([52388, 50, 41], maxval=10, dtype=tf.int32),
     tf.random_uniform([52388, 11], maxval=10, dtype=tf.int32)))

for i, item in enumerate(dataset2):
    print('element: ' + str(i), item[0], item[1])

您注意到,我们只迭代数据集一次,而我们希望迭代它52388次!

现在假设我们要把这个大张量提供给我们的模型。Tensorflow将转换为[None, 1]None是我们的批处理大小。另一方面,您使用[None, 41]指定模型的输入,这意味着模型期望有一个形状为[None, None, 41]的输入。因此,这种不一致会导致错误。

怎么修呢?

使用from_tensor_slices

仍然给我尺寸误差,如何修复它?定义LSTM的输入维度:

代码语言:javascript
复制
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.LSTM(32, name='inputs', input_shape=(50, 41)))
model.add(tf.keras.layers.Dense(11, activation='softmax', name='dense'))
model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])
model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54045667

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档