python - 如何使用 tf.keras 从保存的模型访问层

标签 python tensorflow keras tensorflow2.0 tf.keras

tensorflow 2.0

Python 3.7

我使用 tf.keras 训练并保存了这样的模型

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, models 
from tensorflow.keras.datasets import mnist

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels))

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

model.save("saved_model_pretrained/")

我想加载模型,以便在另一个像这样的项目中从中提取图层

image_model = tf.keras.models.load_model('pathToFolder')

我正在尝试获得这样的图层:

layer_indices = []
for index, layer in enumerate(image_model.layers):
    layers_indices.append(index)

但是我收到此错误

future: <Task finished coro=<server_task.<locals>.server_work() done, defined at ...\...\xx.py:249> exception=AttributeError("'_UserObject' object has no attribute 'layers'")>
Traceback (most recent call last):
  File "...\...\xx.py", line 280, in server_work
    image_model, layers_indices = init(model_choice, layers_to_see)
  File "...\...\xx.py", line 148, in init
    for index, layer in enumerate(image_model.layers):
AttributeError: '_UserObject' object has no attribute 'layers'

非常感谢任何帮助

最佳答案

首先,您应该正确保存模型!使用以下语法将模型保存/加载为 (.h5) 文件 - 保存模型的常用格式:

model.save("model.h5")
image_model = tf.keras.models.load_model('model.h5')

然后你的image_model中就会有layers。在您的情况下,image_model.layers 会生成:

[<tensorflow.python.keras.layers.convolutional.Conv2D at 0x1d81b325898>,
 <tensorflow.python.keras.layers.pooling.MaxPooling2D at 0x1d81b325f98>,
 <tensorflow.python.keras.layers.convolutional.Conv2D at 0x1d82b06b2e8>,
 <tensorflow.python.keras.layers.pooling.MaxPooling2D at 0x1d82c1dbe10>,
 <tensorflow.python.keras.layers.convolutional.Conv2D at 0x1d82c17d2e8>,
 <tensorflow.python.keras.layers.core.Flatten at 0x1d82c17df98>,
 <tensorflow.python.keras.layers.core.Dense at 0x1d82c2c8320>,
 <tensorflow.python.keras.layers.core.Dense at 0x1d82b016048>]

还有

layers_indices = []
for index, layer in enumerate(image_model.layers):
    layers_indices.append(index)
layers_indices

产生:

[0, 1, 2, 3, 4, 5, 6, 7]

关于python - 如何使用 tf.keras 从保存的模型访问层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64376223/

相关文章:

python - TensorFlow 2.0 : tf. GradientTape() 返回无结果

python - django-zappa : Error loading psycopg2 module: libpq. so.5:无法打开共享对象文件:没有这样的文件或目录

python - Tensorflow - 使用时间线进行分析 - 了解限制系统的因素

python - 类型错误 : Variable to save is not a Variable

python - 由于 NaN 掩码, model.get_weights() 在训练后返回 NaN 数组

python - 如何获取 Selenium 中元素的父元素?

python - Django:使用自定义多对多模型保存 ModelForm

python - 使用 Scipy minimize 进行 Keras BFGS 训练

image-processing - 卷积神经网络中深度的解读

python - 如何防止丢失 : nan while I'm fitting my keras model?