无法将 TensorFlow Keras LSTM 模型保存为 SavedModel 格式

Tho*_*tin 6 python lstm keras tensorflow2.0

系统信息:

操作系统平台和发行版(例如 Linux Ubuntu 16.04):Windows 10

TensorFlow 从(源代码或二进制文件)安装:pip 安装

TensorFlow 版本(使用下面的命令):v2.0.0-rc2-26-g64c3d382ca 2.0.0

Python版本:3.7.1

错误:

无法将 TensorFlow Keras LSTM 模型保存为 SavedModel 格式以导出到 Google Cloud 存储桶。

错误信息:

ValueError:试图保存一个函数 b'__inference_lstm_2_layer_call_fn_36083',它引用了一个不是简单常量的符号 Tensor Tensor("dropout/mul_1:0", shape=(None, 1280), dtype=float32)。这不受支持。

代码:

import tensorflow as tf
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import tqdm
import datetime
from sklearn.preprocessing import LabelBinarizer 

model = tf.keras.Sequential([
    tf.keras.layers.Masking(mask_value=0.),
    tf.keras.layers.LSTM(512, dropout=0.5, recurrent_dropout=0.5),
    tf.keras.layers.Dense(256, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(len(LABELS), activation='softmax')
])

model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy', 'top_k_categorical_accuracy'])

test_file = 'C:/.../testlist01.txt'
train_file = 'C:/.../trainlist01.txt'

with open(test_file) as f:
    test_list = [row.strip() for row in list(f)]

with open(train_file) as f:
    train_list = [row.strip() for row in list(f)]
    train_list = [row.split(' ')[0] for row in train_list]


def make_generator(file_list):
    def generator():
        np.random.shuffle(file_list)
        for path in file_list:
            full_path = os.path.join(BASE_PATH, path).replace('.avi', '.npy')

            label = os.path.basename(os.path.dirname(path))
            features = np.load(full_path)

            padded_sequence = np.zeros((SEQUENCE_LENGTH, 1280))
            padded_sequence[0:len(features)] = np.array(features)

            transformed_label = encoder.transform([label])
            yield padded_sequence, transformed_label[0]
    return generator

train_dataset = tf.data.Dataset.from_generator(make_generator(train_list),
                 output_types=(tf.float32, tf.int16),
                 output_shapes=((SEQUENCE_LENGTH, 1280), (len(LABELS))))
train_dataset = train_dataset.batch(16).prefetch(tf.data.experimental.AUTOTUNE)

valid_dataset = tf.data.Dataset.from_generator(make_generator(test_list),
                 output_types=(tf.float32, tf.int16),
                 output_shapes=((SEQUENCE_LENGTH, 1280), (len(LABELS))))
valid_dataset = valid_dataset.batch(16).prefetch(tf.data.experimental.AUTOTUNE)

model.fit(train_dataset, epochs=17, validation_data=valid_dataset)

BASE_DIRECTORY = 'C:\\...\\saved_model\\LSTM\\1\\';
tf.saved_model.save(model, BASE_DIRECTORY)
Run Code Online (Sandbox Code Playgroud)

The*_*Hat 0

尝试使用 Keras API 保存它,而不是 SavedModel API。请参阅使用 Keras 保存和序列化模型:导出到 SavedModel

model.save('path_to_saved_model', save_format='tf')
Run Code Online (Sandbox Code Playgroud)

这应该将模型保存为 SavedModel 格式。

  • 这仍然会产生相同的错误: ValueError: Attempted to save a function b'__inference_lstm_2_layer_call_fn_20869' 它引用了一个符号张量 Tensor("dropout/mul_1:0", shape=(None, 1280), dtype=float32) 这不是一个简单的持续的。不支持此操作。 (2认同)