簡體   English   中英

如何為Tensorflow估算器輸入正確的形狀?

[英]How to input the correct shape for a Tensorflow Estimator?

我正在嘗試構建一個Tensorflow估計器以在SageMaker上使用。 主要功能訓練和評估估計器。 盡管盡了最大的努力,我仍然遇到以下錯誤:

ValueError:圖層輸入的輸入0與圖層不兼容:預期ndim = 3,找到的ndim = 2。 收到的完整形狀:[50,41]

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)

from_tensors將輸入張量轉換為單個大張量。 例如,如果運行以下示例:

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的輸入尺寸:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM