image classification three layers CNN

本文介绍了一种使用卷积神经网络(CNN)进行图像分类的方法。通过构建一个多层CNN模型,并利用TensorFlow进行训练和验证,实现了对机场场景中不同类别图像的有效识别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tensorflow==2.1.0

tensorflow-gpu==2.1.0

opencv-python

matplotlib

 

# 导入模块
import glob
import os
import cv2
import tensorflow as tf
from tensorflow.keras import layers, optimizers, datasets, Sequential
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from matplotlib.pyplot import MultipleLocator

# 设置初始化环境
path = 'airportdeal11/'
w = 100
h = 100
c = 3

# 构建读取图片数据集函数
def read_img(path):
    cate = [path + x for x in os.listdir(path) if os.path.isdir(path + x)]
    imgs = []
    labels = []
    for idx, folder in enumerate(cate):
        for im in glob.glob(folder + '/*.jpg'):
            img = cv2.imread(im)
            img = cv2.resize(img, (w, h))
            imgs.append(img)
            labels.append(idx)
    return np.asarray(imgs, np.float32), np.asarray(labels, np.int32)


# 读取图片数据集
data, label = read_img(path)
print("shape of data:", data.shape)
print("shape of label:", label.shape)

# 划分训练集与测试集
seed = 785
np.random.seed(seed)
(x_train, x_val, y_train, y_val) = train_test_split(data, label, test_size=0.20, random_state=seed)
x_train = x_train / 255
x_val = x_val / 255

# 构建CNN神经网络
model = Sequential([
    layers.Conv2D(32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),
    layers.Dropout(0.25),

    layers.Conv2D(64, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
    layers.Conv2D(64, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),
    layers.Dropout(0.25),

    layers.Conv2D(128, kernel_size=[3, 3], padding="same", activation=tf.nn.relu),
    layers.MaxPool2D(pool_size=[2, 2], strides=2, padding='same'),
    layers.Dropout(0.25),

    layers.Flatten(),
    layers.Dense(512, activation=tf.nn.relu),
    layers.Dense(256, activation=tf.nn.relu),
    # layers.Dense(5, activation='softmax') # 2020-09-18 guangjinzheng
    layers.Dense(11, activation='softmax')
])

# 构建adam优化器
# opt = optimizers.Adam(lr=0.0001)
opt = optimizers.Adam(lr=0.00021)
model.compile(optimizer=opt,
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 设置训练模型的次数
# _epochs = 10
_epochs = 250

# 训练CNN图像识别模型
# history = model.fit(x_train, y_train, epochs=_epochs, validation_data=(x_val, y_val), batch_size=200, verbose=2)
history = model.fit(x_train, y_train, epochs=_epochs, validation_data=(x_val, y_val), batch_size=32, verbose=2)

model.summary()

def show_history(history, epochs):
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']
    loss = history.history['loss']
    val_loss = history.history['val_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)
    x_major_locator = MultipleLocator(_epochs/10)
    y_major_locator = MultipleLocator(0.05)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)
    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)
    x_major_locator = MultipleLocator(_epochs/10)
    y_major_locator = MultipleLocator(0.1)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)
    plt.xlim(0, _epochs)
    plt.ylim(0, 3)
    plt.grid()
    plt.show()

show_history(history, _epochs)

# model.save('model.h5')

# # 验证集图片命名格式为test(i)
# path_test = 'D:\deeplearning\datasets/test/'
# imgs = []
# for im in glob.glob(path_test + '/*.jpg'):
#     print('reading the images:%s' % (im))
#     img = cv2.imread(im)
#     img = cv2.resize(img, (w, h))
#     imgs.append(img)
# imgs = np.asarray(imgs, np.float32)
# print("shape of data:", imgs.shape)
# prediction = model.predict_classes(imgs)
# for i in range(np.size(prediction)):
#     print("第", i + 1, "朵花预测:" + flower_dict[prediction[i]])
#     img = plt.imread(path_test + "test" + str(i + 1) + ".jpg")
#     plt.imshow(img)
#     plt.show()

# 2020-09-19 guangjinzheng

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值