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

时间:2019-11-05 22:24:03

标签: python keras lstm tensorflow2.0

系统信息:

OS平台和发行版(例如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:尝试保存引用不是简单常数的符号Tensor Tensor(“ dropout / mul_1:0”,shape =(None,1280),dtype = float32)的函数b'__ inference_lstm_2_layer_call_fn_36083'。不支持。

代码:

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)

4 个答案:

答案 0 :(得分:2)

除了“戴帽子的家伙”的答案:

.h5 部分足以告诉keras将其存储为keras模型保存。

model.save('path_to_saved_model/model.h5') 

应该可以解决问题。

答案 1 :(得分:0)

尝试使用Keras API(而不是SavedModel API)进行保存。参见Save and serialize models with Keras: Export to SavedModel

model.save('path_to_saved_model', save_format='tf')

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

答案 2 :(得分:0)

我认为有一个错误,您需要将tf.saved_model.savemodel.save(.., save_format='tf')函数的dropout设置为0

答案 3 :(得分:0)

这似乎是TensorFlow 2.0和2.1的错误,将TensorFlow升级到v2.2后,它可以正常工作。