保存 Keras 模型并将其重新用于迁移学习
Save Keras Model and Reuse It For Transfer Learning
我在 Keras 中为 CNN 构建模型。我想保存这个模型并将这个经过训练的模型作为预训练模型重新用于迁移学习。我不明白什么是保存模型以将其重新用于迁移学习的正确方法。再次说明如何在 Keras 中加载我的预训练模型,以便我可以在加载之前的模型后添加一些层。
这是我搭建的模型
model_cnn = Sequential() # initilaizing the Sequential nature for CNN model
# Adding the embedding layer which will take in maximum of 450 words as input and provide a 32 dimensional output of those words which belong in the top_words dictionary
model_cnn.add(Embedding(vocab_size, embedding_size, input_length=max_len))
model_cnn.add(Conv1D(32, 3, padding='same', activation='relu'))
model_cnn.add(Conv1D(64, 3, padding='same', activation='relu'))
model_cnn.add(MaxPooling1D())
model_cnn.add(Flatten())
model_cnn.add(Dense(250, activation='relu'))
model_cnn.add(Dense(2, activation='softmax'))
# optimizer = keras.optimizers.Adam(lr=0.001)
model_cnn.compile(
loss='categorical_crossentropy',
optimizer=sgd,
metrics=['acc',Precision(),Recall(),]
)
history_cnn = model_cnn.fit(
X_train, y_train,
validation_data=(X_val, y_val),
batch_size = 64,
epochs=epochs,
verbose=1
)
推荐的模型保存方式,保存格式为SavedModel:
dir = "target_directory"
model_cnn.save(dir) # it will save a .pb file with assets and variables folders
然后就可以加载了:
model_cnn = tf.keras.models.load_model(dir)
现在,您可以添加一些图层并制作另一个模型。例如:
input = tf.keras.Input(shape=(128,128,3))
x = model_cnn(input)
x = tf.keras.layers.Dense(1, activation='sigmoid')(x)
new_model = tf.keras.models.Model(inputs=input, outputs=x)
我在 Keras 中为 CNN 构建模型。我想保存这个模型并将这个经过训练的模型作为预训练模型重新用于迁移学习。我不明白什么是保存模型以将其重新用于迁移学习的正确方法。再次说明如何在 Keras 中加载我的预训练模型,以便我可以在加载之前的模型后添加一些层。
这是我搭建的模型
model_cnn = Sequential() # initilaizing the Sequential nature for CNN model
# Adding the embedding layer which will take in maximum of 450 words as input and provide a 32 dimensional output of those words which belong in the top_words dictionary
model_cnn.add(Embedding(vocab_size, embedding_size, input_length=max_len))
model_cnn.add(Conv1D(32, 3, padding='same', activation='relu'))
model_cnn.add(Conv1D(64, 3, padding='same', activation='relu'))
model_cnn.add(MaxPooling1D())
model_cnn.add(Flatten())
model_cnn.add(Dense(250, activation='relu'))
model_cnn.add(Dense(2, activation='softmax'))
# optimizer = keras.optimizers.Adam(lr=0.001)
model_cnn.compile(
loss='categorical_crossentropy',
optimizer=sgd,
metrics=['acc',Precision(),Recall(),]
)
history_cnn = model_cnn.fit(
X_train, y_train,
validation_data=(X_val, y_val),
batch_size = 64,
epochs=epochs,
verbose=1
)
推荐的模型保存方式,保存格式为SavedModel:
dir = "target_directory"
model_cnn.save(dir) # it will save a .pb file with assets and variables folders
然后就可以加载了:
model_cnn = tf.keras.models.load_model(dir)
现在,您可以添加一些图层并制作另一个模型。例如:
input = tf.keras.Input(shape=(128,128,3))
x = model_cnn(input)
x = tf.keras.layers.Dense(1, activation='sigmoid')(x)
new_model = tf.keras.models.Model(inputs=input, outputs=x)