<reponame>KinChow/Classifier-cat-dog
# 猫狗分类器
# Keras
# 准确率在90%左右

import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from tensorflow.keras.preprocessing.image import array_to_img, img_to_array, load_img, ImageDataGenerator
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.applications.inception_v3 import InceptionV3

local_weights_file = '../Model/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'
pre_trained_model = InceptionV3(
    input_shape=(150, 150, 3), include_top=False, weights=None)
pre_trained_model.load_weights(local_weights_file)

for layer in pre_trained_model.layers:
    layer.trainable = False

last_layer = pre_trained_model.get_layer('mixed7')
print('last layer output shape:', last_layer.output_shape)
last_output = last_layer.output

# Flatten the output layer to 1 dimension
x = layers.Flatten()(last_output)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = layers.Dense(1024, activation='relu')(x)
# Add a dropout rate of 0.2
x = layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = layers.Dense(1, activation='sigmoid')(x)

# Configure and compile the model
model = Model(pre_trained_model.input, x)
model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(lr=0.0001),
              metrics=['acc'])

# 猫和狗训练数据和验证数据的目录
base_dir = '../Data'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')

# 猫的训练数据目录
train_cats_dir = os.path.join(train_dir, 'cats')

# 狗的训练数据目录
train_dogs_dir = os.path.join(train_dir, 'dogs')

# 猫的验证数据目录
validation_cats_dir = os.path.join(validation_dir, 'cats')

# 狗的验证数据目录
validation_dogs_dir = os.path.join(validation_dir, 'dogs')

# 猫的训练数据文件
train_cat_fnames = os.listdir(train_cats_dir)

# 狗的训练数据文件
train_dog_fnames = os.listdir(train_dogs_dir)

# 图像预处理
# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(
    rescale=1./255,
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,)

test_datagen = ImageDataGenerator(rescale=1./255)

# Flow training images in batches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
        train_dir,  # This is the source directory for training images
        target_size=(150, 150),  # All images will be resized to 150x150
        batch_size=20,
        # Since we use binary_crossentropy loss, we need binary labels
        class_mode='binary')

# Flow validation images in batches of 20 using test_datagen generator
validation_generator = test_datagen.flow_from_directory(
        validation_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='binary')

history = model.fit_generator(
      train_generator,
      steps_per_epoch=100,
      epochs=2,
      validation_data=validation_generator,
      validation_steps=50,
      verbose=2)

from tensorflow.keras.optimizers import SGD

unfreeze = False

# Unfreeze all models after "mixed6"
for layer in pre_trained_model.layers:
  if unfreeze:
    layer.trainable = True
  if layer.name == 'mixed6':
    unfreeze = True

# As an optimizer, here we will use SGD
# with a very low learning rate (0.00001)
model.compile(loss='binary_crossentropy',
              optimizer=SGD(
                  lr=0.00001,
                  momentum=0.9),
              metrics=['acc'])

history = model.fit_generator(
      train_generator,
      steps_per_epoch=100,
      epochs=50,
      validation_data=validation_generator,
      validation_steps=50,
      verbose=2)

# Retrieve a list of accuracy results on training and test data
# sets for each training epoch
acc = history.history['acc']
val_acc = history.history['val_acc']

# Retrieve a list of list results on training and test data
# sets for each training epoch
loss = history.history['loss']
val_loss = history.history['val_loss']

# Get number of epochs
epochs = range(len(acc))

# Plot training and validation accuracy per epoch
acc_plot = plt.figure(figsize=(9, 6))
plt.plot(epochs, acc, label="Train accuracy")
plt.plot(epochs, val_acc, label="Validation accuracy")
plt.title('Training and validation accuracy')
plt.ylabel('Training Progress (Accuracy values)', fontsize=12)
plt.xlabel('Training Epoch', fontsize=12)
plt.legend(loc='best')
plt.show()

# Plot training and validation loss per epoch
loss_plot = plt.figure(figsize=(9, 6))
plt.plot(epochs, loss, label="Train loss")
plt.plot(epochs, val_loss, label="Validation loss")
plt.title('Training and validation loss')
plt.legend(loc='best')
plt.ylabel('Training Progress (Loss values)', fontsize=12)
plt.xlabel('Training Epoch', fontsize=12)
plt.show()
# 猫狗分类器
# Keras
# 准确率在90%左右

import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from tensorflow.keras.preprocessing.image import array_to_img, img_to_array, load_img, ImageDataGenerator
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.applications.inception_v3 import InceptionV3

local_weights_file = '../Model/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5'
pre_trained_model = InceptionV3(
    input_shape=(150, 150, 3), include_top=False, weights=None)
pre_trained_model.load_weights(local_weights_file)

for layer in pre_trained_model.layers:
    layer.trainable = False

last_layer = pre_trained_model.get_layer('mixed7')
print('last layer output shape:', last_layer.output_shape)
last_output = last_layer.output

# Flatten the output layer to 1 dimension
x = layers.Flatten()(last_output)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = layers.Dense(1024, activation='relu')(x)
# Add a dropout rate of 0.2
x = layers.Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = layers.Dense(1, activation='sigmoid')(x)

# Configure and compile the model
model = Model(pre_trained_model.input, x)
model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(lr=0.0001),
              metrics=['acc'])

# 猫和狗训练数据和验证数据的目录
base_dir = '../Data'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')

# 猫的训练数据目录
train_cats_dir = os.path.join(train_dir, 'cats')

# 狗的训练数据目录
train_dogs_dir = os.path.join(train_dir, 'dogs')

# 猫的验证数据目录
validation_cats_dir = os.path.join(validation_dir, 'cats')

# 狗的验证数据目录
validation_dogs_dir = os.path.join(validation_dir, 'dogs')

# 猫的训练数据文件
train_cat_fnames = os.listdir(train_cats_dir)

# 狗的训练数据文件
train_dog_fnames = os.listdir(train_dogs_dir)

# 图像预处理
# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(
    rescale=1./255,
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,)

test_datagen = ImageDataGenerator(rescale=1./255)

# Flow training images in batches of 20 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
        train_dir,  # This is the source directory for training images
        target_size=(150, 150),  # All images will be resized to 150x150
        batch_size=20,
        # Since we use binary_crossentropy loss, we need binary labels
        class_mode='binary')

# Flow validation images in batches of 20 using test_datagen generator
validation_generator = test_datagen.flow_from_directory(
        validation_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='binary')

history = model.fit_generator(
      train_generator,
      steps_per_epoch=100,
      epochs=2,
      validation_data=validation_generator,
      validation_steps=50,
      verbose=2)

from tensorflow.keras.optimizers import SGD

unfreeze = False

# Unfreeze all models after "mixed6"
for layer in pre_trained_model.layers:
  if unfreeze:
    layer.trainable = True
  if layer.name == 'mixed6':
    unfreeze = True

# As an optimizer, here we will use SGD
# with a very low learning rate (0.00001)
model.compile(loss='binary_crossentropy',
              optimizer=SGD(
                  lr=0.00001,
                  momentum=0.9),
              metrics=['acc'])

history = model.fit_generator(
      train_generator,
      steps_per_epoch=100,
      epochs=50,
      validation_data=validation_generator,
      validation_steps=50,
      verbose=2)

# Retrieve a list of accuracy results on training and test data
# sets for each training epoch
acc = history.history['acc']
val_acc = history.history['val_acc']

# Retrieve a list of list results on training and test data
# sets for each training epoch
loss = history.history['loss']
val_loss = history.history['val_loss']

# Get number of epochs
epochs = range(len(acc))

# Plot training and validation accuracy per epoch
acc_plot = plt.figure(figsize=(9, 6))
plt.plot(epochs, acc, label="Train accuracy")
plt.plot(epochs, val_acc, label="Validation accuracy")
plt.title('Training and validation accuracy')
plt.ylabel('Training Progress (Accuracy values)', fontsize=12)
plt.xlabel('Training Epoch', fontsize=12)
plt.legend(loc='best')
plt.show()

# Plot training and validation loss per epoch
loss_plot = plt.figure(figsize=(9, 6))
plt.plot(epochs, loss, label="Train loss")
plt.plot(epochs, val_loss, label="Validation loss")
plt.title('Training and validation loss')
plt.legend(loc='best')
plt.ylabel('Training Progress (Loss values)', fontsize=12)
plt.xlabel('Training Epoch', fontsize=12)
plt.show()
# 猫狗分类器 # Keras # 准确率在90%左右 # Flatten the output layer to 1 dimension # Add a fully connected layer with 1,024 hidden units and ReLU activation # Add a dropout rate of 0.2 # Add a final sigmoid layer for classification # Configure and compile the model # 猫和狗训练数据和验证数据的目录 # 猫的训练数据目录 # 狗的训练数据目录 # 猫的验证数据目录 # 狗的验证数据目录 # 猫的训练数据文件 # 狗的训练数据文件 # 图像预处理 # All images will be rescaled by 1./255 # Flow training images in batches of 20 using train_datagen generator # This is the source directory for training images # All images will be resized to 150x150 # Since we use binary_crossentropy loss, we need binary labels # Flow validation images in batches of 20 using test_datagen generator # Unfreeze all models after "mixed6" # As an optimizer, here we will use SGD # with a very low learning rate (0.00001) # Retrieve a list of accuracy results on training and test data # sets for each training epoch # Retrieve a list of list results on training and test data # sets for each training epoch # Get number of epochs # Plot training and validation accuracy per epoch # Plot training and validation loss per epoch