您的当前位置:首页正文

image classification dogs and cats cnn

2024-11-30 来源:个人技术集锦
import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator

path = 'D:/deeplearning/datasets/dogsandcats/'
batchsizes = 32
epochs = 15

# read data
train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
training_set = train_datagen.flow_from_directory('{}training_set'.format(path),
                                                 target_size=(64, 64),
                                                 batch_size=batchsizes,
                                                 class_mode='binary')
test_datagen = ImageDataGenerator(rescale=1./255)
test_set = test_datagen.flow_from_directory('{}test_set'.format(path),
                                            target_size=(64, 64),
                                            batch_size=batchsizes,
                                            class_mode='binary')
print('{}'.format(test_set.class_indices))
# cnn
cnn = tf.keras.models.Sequential()
cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=[64, 64, 3]))
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'))
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))
cnn.add(tf.keras.layers.Flatten())
cnn.add(tf.keras.layers.Dense(units=128, activation='relu'))
cnn.add(tf.keras.layers.Dense(units=1, activation='sigmoid'))
cnn.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

history = cnn.fit(x=training_set, validation_data=test_set, epochs=epochs)

# show
def pltshow(loss,val_loss,acc,val_acc):
    # epochs = len(loss)
    epochs_range = range(epochs)

    plt.figure(figsize=(8, 8))
    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.xlabel('Epoch', fontsize=14)
    plt.ylabel('Accuracy', fontsize=14)
    ax = plt.gca()
    # ax.xaxis.set_major_locator(MultipleLocator(5))
    ax.yaxis.set_major_locator(MultipleLocator(0.05))
    plt.xlim(0, epochs)
    plt.ylim(0, 1)
    plt.grid()

    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.xlabel('Epoch', fontsize=14)
    plt.ylabel('Loss', fontsize=14)
    ax = plt.gca()
    # ax.xaxis.set_major_locator(MultipleLocator(5))
    ax.yaxis.set_major_locator(MultipleLocator(0.1))
    plt.xlim(0, epochs)
    plt.ylim(0, 1)
    plt.grid()
    plt.show()

acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
pltshow(loss, val_loss, acc, val_acc)

import numpy as np
from keras.preprocessing import image
from PIL import Image

pathx = 'D:/deeplearning/datasets/dogsandcats/test_set/dogs/dog.4006.jpg'
pathx = 'D:/deeplearning/datasets/dogsandcats/test_set/cats/cat.4001.jpg'
im = Image.open(pathx)
im.show()

test_image = image.load_img(pathx) 
test_image = image.load_img(pathx, target_size=(64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)

result = cnn.predict_classes(test_image)
print('{}'.format(test_set.class_indices))
print(result)

# 2020-09-26 guangjinzheng

 

显示全文