图像分类CIFAR-10学习
# -*- coding: utf-8 -*-
"""CIFAR10 官网案例.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1-0eKHTgI1VMPU4CfDQGwqq1HSG4KKj1j
"""
import tensorflow as tf
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense
import matplotlib.pyplot as plt
from math import sqrt
# 1 加载数据集
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train.shape
y_train.shape
x_test.shape
y_test.shape
# 类别名称
labels = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
# 2 显示部分数据集(36张图片)
def show_images(dataset, size=0):
plt.figure(figsize=(10,8)) # 画布大小
plt.suptitle("Image Samples")
for i in range(size):
plt.subplot(int(sqrt(size)), int(sqrt(size)), i+1) # 图片显示位置
plt.imshow(dataset[i]) # 显示图片
plt.xticks([]) # 关闭横纵坐标轴值显示
plt.yticks([])
plt.xlabel(labels[y_train[i][0]]) # 横轴标签
plt.show()
show_images(x_train, size=25)
# 3 数据集归一化
x_train = x_train / 255.0
x_test = x_test / 255.0
# 4 搭建模型
model = Sequential() # 创建序列模型
model.add(Conv2D(32, (3,3), activation='relu', input_shape=(32, 32, 3))) # 设置32个神经元,卷积核大小3x3,input_shape
#32个神经元 卷积核的大小(3,3) 激活函数
model.add(MaxPool2D((2,2))) # 池化层
#32/2 将featureMap缩小
model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPool2D((2,2))) # 池化层
model.add(Conv2D(64, (3,3), activation='relu'))
model.add(Flatten()) # 3D变成1D
model.add(Dense(128, activation='relu'))
#全连接层
model.add(Dense(10))
#分类有10个类型
# 5 模型编译
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
#优化器"adam""std",损失函数,评估函数
#Sparse会把标签集转换成向量
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
"""categorical_crossentropy 与 SparseCategoricalCrossentropy 区别:
两者都是多分类交叉熵损失函数,区别在于sparse(稀疏),在于对target编码的要求。
1.categorical_crossentropy要求target为onehot编码。
2.sparse_categorical_crossentropy要求target为非onehot编码,函数内部进行onehot编码实现。
"""
# 6 模型训练
history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
# 7 显示训练accuracy和验证accuracy
plt.figure(figsize=(10,8))
plt.plot(history.history['accuracy'], label='Train acc')
plt.plot(history.history['val_accuracy'], label='Val acc')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.title('Train and Val Acc')
plt.show()
# 8 模型验证
result = model.evaluate(x_test, y_test)
print("test loss : ", result[0])
print("test acc : ", result[1])