抽取ImageNet数据集进行数据增强 评估新鲜及腐烂水果,苹果香蕉橘子 (6神经元)
加载预训练模型(vgg16)ImageNet -》冻结基本模型 -》向预训练模型添加层对齐输入输出 -》编译模型(训练多类别)-》扩充数据 改进数据集 -》加载训练 -》解冻并微调 - 》评估
from tensorflow import keras
base_model = keras.applications.VGG16(
weights='imagenet',
input_shape=(224, 224, 3),
include_top=False)
# Create inputs with correct shape
inputs = keras.Input(shape = (224,224,3))
x = base_model(inputs, training=False)
# Add pooling layer or flatten layer
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dense(512, activation='relu')(x)
# Add final dense layer
outputs = keras.layers.Dense(6, activation = 'softmax')(x)
# Combine inputs and outputs to create model
model = keras.Model(inputs,outputs)
model.summary()
model.compile(loss = keras.losses.CategoricalCrossentropy(),
metrics = keras.metrics.CategoricalAccuracy())
from tensorflow.keras.preprocessing.image import ImageDataGenerator
datagen_train = ImageDataGenerator(samplewise_center=True,
rotation_range=10,
zoom_range=0.1,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
vertical_flip=True)
datagen_valid = ImageDataGenerator(samplewise_center=True)
"
# load and iterate training dataset
train_it = datagen_train.flow_from_directory(
"data/fruits/train/",
target_size=(224,224),
color_mode="rgb",
class_mode="categorical",
)
# load and iterate validation dataset
valid_it = datagen_valid.flow_from_directory(
"data/fruits/valid/",
target_size=(224,224),
color_mode="rgb",
class_mode="categorical",
)
loss = FIXME , metrics = FIXME
# Unfreeze the base model
base_model.trainable = True
# Compile the model with a low learning rate
model.compile(optimizer=keras.optimizers.RMSprop(learning_rate = 1e-5),
loss=keras.losses.CategoricalCrossentropy(),
metrics=[keras.metrics.CategoricalAccuracy()])
5
model.fit(train_it,
validation_data=valid_it,
steps_per_epoch=train_it.samples/train_it.batch_size,
validation_steps=valid_it.samples/valid_it.batch_size,
epochs=5)
from run_assessment import run_assessment
run_assessment(model, valid_it)