TF / Keras error: InputLayer not a Checkpointable

TF / Keras error: InputLayer not a Checkpointable

我正在使用简单的猫狗数据集在 Google Colab 上试用新添加的 TPU 支持。

创建一个简单的 CNN 后,我尝试将模型导出到 TPU。但失败并出现错误

TypeError: Checkpointable._track_checkpointable() passed type <class 'keras.engine.topology.InputLayer'>, not a Checkpointable.

这是我在 Colab 上编写的代码。

model = models.Sequential()
model.add(layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 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.Flatten())
model.add(layers.Dropout(0.5))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.summary()

train_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(train_dir, target_size=(150,150), batch_size=20, class_mode='binary')

tpu_model = tf.contrib.tpu.keras_to_tpu_model(model, strategy=tf.contrib.tpu.TPUDistributionStrategy(tf.contrib.cluster_resolver.TPUClusterResolver(tpu="grpc://" + os.environ['COLAB_TPU_ADDR'])))

我的猜测是我在 train_generator 中做错了什么。但我不确定它是什么。任何帮助将不胜感激。

如果您使用或从 Keras 导入 layers 而不是 TensorFlow,如下所示:

from keras import layers,models
from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf

你会得到上面提到的错误:

TypeError: Checkpointable._track_checkpointable() passed type <class 'keras.engine.topology.InputLayer'>, not a Checkpointable.

因此,您可以直接从 TensorFlow 导入 layers,就像我下面的代码:

from tensorflow.keras import layers,models
from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf

或者你可以在这里看到我的完整代码: https://gist.github.com/ilmimris/8218e397dd35ab693404e95db32dc574