深度学习之利用训练好的模型进行学习, 迁移学习(六)

解释

  • 迁移学习是应用非常广泛的学习方式,目的在于运用相似的学习权重和模型进行二次训练
  • 站在巨人的肩膀上进行学习,学习的更快
  • 正常需要3天-10天的学习时间,运用迁移学习可能只需要几个小时或1天

TF的使用

from keras.applications.resnet import ResNet50
pre_model = ResNet50(include_top=False, input_shape=(64, 64, 3))

  • include_top 代表是否运用全连接层
  • input_shape 代表输入的大小, 不同网络有限制,可以参考官网说明

将前面的卷积层给停用

  • 数据较少不建议使用自己训练的
  • 数据较多可以使用部分训练
  • 数据大的时候可以自己重新训练模型
for layers in pre_model.layers:
    layers.trainable = False 

开始训练

  • 构建全连接层
x = keras.layers.Flatten()(pre_model.output)
x = keras.layers.Dense(1024, activation="relu")(x)
x = keras.layers.Dropout(0.2)(x)
# 输出层
x = keras.layers.Dense(1, activation='sigmoid')(x)


import tensorflow as tf

inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
  • 说明:Model构建时,只需要知道输入和输出的结果,中间会自动关联,所以只要两个参数
    在这里插入图片描述
# 构建模型
model = keras.Model(pre_model.input, x)
  • 训练
history = model.fit_generator(train_img_gen, validation_data= valid_img_gen, epochs=10)

callback的使用

自定义callback

  • 继承Callback类
class MyCallback(tf.keras.callbacks.Callback):
  def on_train_end(self, logs=None):
    global training_finished
    training_finished = True
   
model.fit(tf.constant([[1.0]]), tf.constant([[1.0]]),
          callbacks=[MyCallback()])

运用官网的

callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3)
  • 在loss 三次后没有下降进行训练终止

猜你喜欢

转载自blog.csdn.net/monk96/article/details/125776774