- 本文为365天深度学习训练营 中的学习记录博客
- 参考文章:365天深度学习训练营-第5周:运动鞋品牌识别(训练营内部成员可读)
- 原作者:K同学啊
from tensorflow import keras
from tensorflow.keras import layers,models
import os, PIL, pathlib
import matplotlib.pyplot as plt
import tensorflow as tf
data_dir = "D://jupyter notebook/46-data/"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*/*.jpg')))
print("图片总数为:",image_count)
图片总数为: 578
roses = list(data_dir.glob('train/nike/*.jpg'))
PIL.Image.open(str(roses[0]))
batch_size = 32
img_height = 224
img_width = 224
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
"D://jupyter notebook/46-data/train",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
Found 502 files belonging to 2 classes.
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
"D://jupyter notebook/46-data/test",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
Found 76 files belonging to 2 classes.
class_names = train_ds.class_names
print(class_names)
['adidas', 'nike']
plt.figure(figsize=(20, 10))
for images, labels in train_ds.take(1):
for i in range(20):
ax = plt.subplot(5, 10, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
(32, 224, 224, 3)
(32,)
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
model = models.Sequential([
layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
layers.Conv2D(16, (3, 3), activation='relu', input_shape=(img_height, img_width, 3)),
layers.AveragePooling2D((2, 2)),
layers.Conv2D(32, (3, 3), activation='relu'),
layers.AveragePooling2D((2, 2)),
layers.Dropout(0.3),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.Dropout(0.3),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(len(class_names))
])
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
rescaling (Rescaling) (None, 224, 224, 3) 0
conv2d (Conv2D) (None, 222, 222, 16) 448
average_pooling2d (AverageP (None, 111, 111, 16) 0
ooling2D)
conv2d_1 (Conv2D) (None, 109, 109, 32) 4640
average_pooling2d_1 (Averag (None, 54, 54, 32) 0
ePooling2D)
dropout (Dropout) (None, 54, 54, 32) 0
conv2d_2 (Conv2D) (None, 52, 52, 64) 18496
dropout_1 (Dropout) (None, 52, 52, 64) 0
flatten (Flatten) (None, 173056) 0
dense (Dense) (None, 128) 22151296
dense_1 (Dense) (None, 2) 258
=================================================================
Total params: 22,175,138
Trainable params: 22,175,138
Non-trainable params: 0
_________________________________________________________________
initial_learning_rate = 0.1
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate,
decay_steps=10,
decay_rate=0.92,
staircase=True)
optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)
model.compile(optimizer=optimizer,
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
epochs = 50
checkpointer = ModelCheckpoint('best_model.h5',
monitor='val_accuracy',
verbose=1,
save_best_only=True,
save_weights_only=True)
earlystopper = EarlyStopping(monitor='val_accuracy',
min_delta=0.001,
patience=20,
verbose=1)
history = model.fit(train_ds,
validation_data=val_ds,
epochs=epochs,
callbacks=[checkpointer, earlystopper])
Epoch 1/50
16/16 [==============================] - ETA: 0s - loss: 157536.0000 - accuracy: 0.5299
Epoch 1: val_accuracy improved from -inf to 0.51316, saving model to best_model.h5
16/16 [==============================] - 23s 1s/step - loss: 157536.0000 - accuracy: 0.5299 - val_loss: 1.0883 - val_accuracy: 0.5132
Epoch 2/50
16/16 [==============================] - ETA: 0s - loss: 1.4099 - accuracy: 0.5120
Epoch 2: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 807ms/step - loss: 1.4099 - accuracy: 0.5120 - val_loss: 0.7797 - val_accuracy: 0.5000
Epoch 3/50
16/16 [==============================] - ETA: 0s - loss: 0.7208 - accuracy: 0.5000
Epoch 3: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 805ms/step - loss: 0.7208 - accuracy: 0.5000 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 4/50
16/16 [==============================] - ETA: 0s - loss: 0.6935 - accuracy: 0.5000
Epoch 4: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 818ms/step - loss: 0.6935 - accuracy: 0.5000 - val_loss: 0.6952 - val_accuracy: 0.5000
Epoch 5/50
16/16 [==============================] - ETA: 0s - loss: 0.6964 - accuracy: 0.4721
Epoch 5: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 809ms/step - loss: 0.6964 - accuracy: 0.4721 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 6/50
16/16 [==============================] - ETA: 0s - loss: 0.6935 - accuracy: 0.4442
Epoch 6: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 849ms/step - loss: 0.6935 - accuracy: 0.4442 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 7/50
16/16 [==============================] - ETA: 0s - loss: 0.6937 - accuracy: 0.5000
Epoch 7: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 831ms/step - loss: 0.6937 - accuracy: 0.5000 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 8/50
16/16 [==============================] - ETA: 0s - loss: 0.6936 - accuracy: 0.4920
Epoch 8: val_accuracy did not improve from 0.51316
16/16 [==============================] - 14s 869ms/step - loss: 0.6936 - accuracy: 0.4920 - val_loss: 0.6935 - val_accuracy: 0.5000
Epoch 9/50
16/16 [==============================] - ETA: 0s - loss: 0.6938 - accuracy: 0.5000
Epoch 9: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 824ms/step - loss: 0.6938 - accuracy: 0.5000 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 10/50
16/16 [==============================] - ETA: 0s - loss: 0.6934 - accuracy: 0.5000
Epoch 10: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 816ms/step - loss: 0.6934 - accuracy: 0.5000 - val_loss: 0.6931 - val_accuracy: 0.5000
Epoch 11/50
16/16 [==============================] - ETA: 0s - loss: 0.6934 - accuracy: 0.4801
Epoch 11: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 819ms/step - loss: 0.6934 - accuracy: 0.4801 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 12/50
16/16 [==============================] - ETA: 0s - loss: 0.6934 - accuracy: 0.4801
Epoch 12: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 821ms/step - loss: 0.6934 - accuracy: 0.4801 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 13/50
16/16 [==============================] - ETA: 0s - loss: 0.6945 - accuracy: 0.5000
Epoch 13: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 816ms/step - loss: 0.6945 - accuracy: 0.5000 - val_loss: 0.6935 - val_accuracy: 0.5000
Epoch 14/50
16/16 [==============================] - ETA: 0s - loss: 0.6933 - accuracy: 0.4841
Epoch 14: val_accuracy did not improve from 0.51316
16/16 [==============================] - 14s 839ms/step - loss: 0.6933 - accuracy: 0.4841 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 15/50
16/16 [==============================] - ETA: 0s - loss: 0.6935 - accuracy: 0.5000
Epoch 15: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 821ms/step - loss: 0.6935 - accuracy: 0.5000 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 16/50
16/16 [==============================] - ETA: 0s - loss: 0.6932 - accuracy: 0.5000
Epoch 16: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 805ms/step - loss: 0.6932 - accuracy: 0.5000 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 17/50
16/16 [==============================] - ETA: 0s - loss: 0.6933 - accuracy: 0.5000
Epoch 17: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 828ms/step - loss: 0.6933 - accuracy: 0.5000 - val_loss: 0.6931 - val_accuracy: 0.5000
Epoch 18/50
16/16 [==============================] - ETA: 0s - loss: 0.6932 - accuracy: 0.4960
Epoch 18: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 814ms/step - loss: 0.6932 - accuracy: 0.4960 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 19/50
16/16 [==============================] - ETA: 0s - loss: 0.6933 - accuracy: 0.5000
Epoch 19: val_accuracy did not improve from 0.51316
16/16 [==============================] - 14s 904ms/step - loss: 0.6933 - accuracy: 0.5000 - val_loss: 0.6931 - val_accuracy: 0.5000
Epoch 20/50
16/16 [==============================] - ETA: 0s - loss: 0.6935 - accuracy: 0.5000
Epoch 20: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 819ms/step - loss: 0.6935 - accuracy: 0.5000 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 21/50
16/16 [==============================] - ETA: 0s - loss: 0.6932 - accuracy: 0.5000
Epoch 21: val_accuracy did not improve from 0.51316
16/16 [==============================] - 13s 820ms/step - loss: 0.6932 - accuracy: 0.5000 - val_loss: 0.6932 - val_accuracy: 0.5000
Epoch 21: early stopping
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))
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
model.load_weights('best_model.h5')
from PIL import Image
import numpy as np
img = Image.open("D://jupyter notebook/46-data/test/nike/1.jpg")
num_img = np.asarray(img)
image = tf.image.resize(num_img, [img_height, img_width])
img_array = tf.expand_dims(image, 0)
predictions = model.predict(img_array)
print("预测结果为:",class_names[np.argmax(predictions)])
1/1 [==============================] - 0s 311ms/step
预测结果为: nike