image classification dogs and cats cnn

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值