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)
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()
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])
结果看起来还不错
绘制精确度
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)
不加卷积和池化的神经网络
结果是比较差的。
拓展
用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()
模型的参数变得更少了
那么结果如何呢
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),
)
准确度没有提升多少
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)
上一篇: HDU2955(Robberies)
下一篇: 最长不下降子序列(上升同理)
推荐阅读
-
Python数据挖掘(烟火图像分类:传统机器学习建模方法与卷积神经网络性能比较)
-
TensorFlow2利用猫狗数据集(cats_and_dogs_filtered.zip)实现卷积神经网络完成分类任务
-
Keras : 利用卷积神经网络CNN对图像进行分类,以mnist数据集为例建立模型并预测
-
基于Tensorflow针对cifar数据集运用卷积神经网络解决100类图片的分类问题。
-
cifar10图像分类
-
cifar10图像分类--卷积神经网络
-
cnn卷积神经网络对cifar数据集实现10分类
-
4用于cifar10的卷积神经网络-4.4/4.5cifar10数据集读取和数据增强扩充(上/下)
-
Python深度学习pytorch神经网络图像卷积运算详解
-
Python卷积神经网络图片分类框架详解分析