迁移学习和微调(tensorflow)

import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow import keras
import matplotlib.pyplot as plt
from tensorflow.keras import layers



#加载数据集tf_flowers
tfds.disable_progress_bar()

train_ds, validation_ds, test_ds = tfds.load(
    "tf_flowers",
    split=["train[:70%]", "train[75%:85%]", "train[85%:95%]"],
    as_supervised=True,  # Include labels
)

#我们将图像的大小调整为 160x160:
size = (160, 160)

train_ds = train_ds.map(lambda x, y: (tf.image.resize(x, size), y))
validation_ds = validation_ds.map(lambda x, y: (tf.image.resize(x, size), y))
test_ds = test_ds.map(lambda x, y: (tf.image.resize(x, size), y))

#此外,我们对数据进行批处理并使用缓存和预提取来优化加载速度。
batch_size = 32

train_ds = train_ds.cache().batch(batch_size).prefetch(buffer_size=10)
validation_ds = validation_ds.cache().batch(batch_size).prefetch(buffer_size=10)
test_ds = test_ds.cache().batch(batch_size).prefetch(buffer_size=10)

"""
当您没有较大的图像数据集时,通过将随机但现实的转换(例如随机水平翻转或小幅随机旋转)
应用于训练图像来人为引入样本多样性是一种良好的做法。
这有助于使模型暴露于训练数据的不同方面,同时减慢过拟合的速度。
"""

data_augmentation = keras.Sequential(

    [
        layers.experimental.preprocessing.RandomFlip("horizontal"),
        layers.experimental.preprocessing.RandomRotation(0.1),
    ]

)

base_model = keras.applications.MobileNetV2(
    weights="imagenet", # Load weights pre-trained on ImageNet.
    input_shape=(160, 160, 3),
    include_top=False,
) # Do not include the ImageNet classifier at the top.

# Freeze the base_model
base_model.trainable = False

# Create new model on top
inputs = keras.Input(shape=(160, 160, 3))
x = data_augmentation(inputs) # Apply random data augmentation
x = keras.applications.mobilenet_v2.preprocess_input(x)

# The base model contains batchnorm layers. We want to keep them in inference mode
# when we unfreeze the base model for fine-tuning, so we make sure that the
# base_model is running in inference mode here.

x = base_model(x, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dropout(0.3)(x) # Regularize with dropout
outputs = keras.layers.Dense(5)(x)

model = keras.Model(inputs, outputs)
model.summary()

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

#训练顶层
initial_epochs = 10
history = model.fit(train_ds, 
                    epochs=initial_epochs,
                    validation_data=validation_ds)

#评估模型
import matplotlib.pyplot as plt
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
%config InlineBackend.figure_format = 'retina'
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值