欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cifar10图像分类--卷积神经网络

程序员文章站 2022-07-07 22:54:04
...

链接:https://pan.baidu.com/s/1Nxty7ntGSUUA18oa_-ORSQ
提取码:in9m
cifar10数据集百度云链接

从本地加载图片

import os
import numpy as np
import pickle as p

def load_CIFAR_batch(filename):
    with open(filename,'rb')as f:
        data_dict = p.load(f,encoding='bytes')
        images = data_dict[b'data']
        labels =data_dict[b'labels']
        
        images = images.reshape(10000,3,32,32)
        images = images.transpose(0,2,3,1)
        labels = np.array(labels)
        return images,labels

def load_CIFAR_data(data_dir):
    images_train=[]
    labels_train=[]
    for i in range(5):
        f = os.path.join(data_dir,'data_batch_%d'%(i+1))
        print('loading',f)
        images_batch,label_batch = load_CIFAR_batch(f)
        
        images_train.append(images_batch)
        labels_train.append(label_batch)
        
        Xtrain = np.concatenate(images_train)
        Ytrain = np.concatenate(labels_train)
        del images_batch,label_batch
    Xtest,Ytest = load_CIFAR_batch(os.path.join(data_dir,'test_batch'))
    print('finished loadding CIFAR-10 data')
    return Xtrain,Ytrain,Xtest,Ytest
data_dir = 'D:\cat_dog\cifar-10-python\cifar-10-batches-py'
train_images, train_labels, test_images, test_labels = load_CIFAR_data(data_dir)

cifar10图像分类--卷积神经网络

train_images, test_images = train_images / 255.0, test_images / 255.0
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

展示图片

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer','dog', 'frog', 'horse', 'ship', 'truck']

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    # The CIFAR labels happen to be arrays, 
    # which is why you need the extra index
    plt.xlabel(class_names[train_labels[i]])
plt.show()

建个模型

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# 显示模型信息
model.summary()
model.add(layers.Flatten()) # 3维 转为 1维
model.add(layers.Dense(64, activation='relu'))  # **函数relu
model.add(layers.Dense(10, activation='softmax'))  # **函数softmax CIFAR有10个类别输出,所以softmax这里参数设置为10
# 再看看模型情况
model.summary()

cifar10图像分类--卷积神经网络

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

# 创建一个保存模型权重的回调
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                 save_weights_only=True,
                                                 verbose=2)

history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels),
                   callbacks=[cp_callback])

cifar10图像分类--卷积神经网络
结果看起来还不错

绘制精确度

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

cifar10图像分类--卷积神经网络

不加卷积和池化的神经网络

cifar10图像分类--卷积神经网络
cifar10图像分类--卷积神经网络
结果是比较差的。

拓展

用CNN分类minist

可以取得更高的精度,加载完数据后需要给最后一维增加一个通道。

增加卷积和池化层

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (2, 2), activation='relu'))

model.add(layers.Flatten()) # 3维 转为 1维
model.add(layers.Dense(64, activation='relu'))  # **函数relu
model.add(layers.Dense(10, activation='softmax'))  # **函数softmax CIFAR有10个类别输出,所以softmax这里参数设置为10
# 再看看模型情况
model.summary()

cifar10图像分类--卷积神经网络
模型的参数变得更少了
那么结果如何呢

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels),
                   )

cifar10图像分类--卷积神经网络
准确度没有提升多少

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

cifar10图像分类--卷积神经网络