application_vnd.jupyter.stderr_output_2.png text_plain_output_1.png
from tensorflow.keras import layers,models

from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping

import matplotlib.pyplot as plt

import tensorflow as tf

from tensorflow import keras
from tensorflow.keras import layers, models
import numpy as np
import matplotlib.pyplot as plt
import os, PIL, pathlib
data_dir = '../input/kafeidou/49-data'
data_dir = pathlib.Path(data_dir)

image_count = len(list(data_dir.glob('*/*.png')))

batch_size = 32
img_height = 224
img_width = 224

"""
关于image_dataset_from_directory()的详细介绍可以参考文章：https://mtyjkh.blog.csdn.net/article/details/117018789
"""
train_ds = tf.keras.preprocessing.image_dataset_from_directory(data_dir, validation_split=0.2, subset='training', seed=123, image_size=(img_height, img_width), batch_size=batch_size)

"""
关于image_dataset_from_directory()的详细介绍可以参考文章：https://mtyjkh.blog.csdn.net/article/details/117018789
"""
val_ds = tf.keras.preprocessing.image_dataset_from_directory(data_dir, validation_split=0.2, subset='validation', seed=123, image_size=(img_height, img_width), batch_size=batch_size)

class_names = train_ds.class_names

plt.figure(figsize=(10, 4))  # 图形的宽为10高为5

for images, labels in train_ds.take(1):
    for i in range(10):
        
        ax = plt.subplot(2, 5, i + 1)  

        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(class_names[labels[i]])
        
        plt.axis("off")

AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

normalization_layer = layers.experimental.preprocessing.Rescaling(1.0 / 255)
train_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
val_ds = val_ds.map(lambda x, y: (normalization_layer(x), y))

from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
epochs = 50
callbacks = [ModelCheckpoint('vgg16_best.h5', monitor='val_accuracy', verbose=1, save_best_only=True, save_weights_only=True), EarlyStopping(monitor='val_accuracy', min_delta=0.001, patience=10, verbose=1)]
def plt_history(history):
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    epochs_range = range(len(loss))
def compile_model(model):
    initial_learning_rate = 0.0001
    lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(initial_learning_rate, decay_steps=30, decay_rate=0.92, staircase=True)
    opt = tf.keras.optimizers.Adam(learning_rate=initial_learning_rate)
    model.compile(optimizer=opt, loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])

model = tf.keras.applications.VGG16(weights='imagenet', input_shape=(224, 224, 3), include_top=False)
output = model.output
output = tf.keras.layers.Flatten()(output)
output = tf.keras.layers.Dense(1024, activation='relu', name='dese-1024')(output)
output = tf.keras.layers.Dense(512, activation='relu', name='dese-512')(output)
output = tf.keras.layers.Dense(len(class_names), activation='softmax', name='softmax-result')(output)
model = tf.keras.models.Model(model.input, output, name='VGG16')
model.summary()

compile_model(model)
history = model.fit(train_ds, validation_data=val_ds, epochs=epochs, callbacks=callbacks)