TensorFlow2.0 多分类案例CIFAR10

先附上所有代码:

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

(x_train,y_train),(x_test,y_test) = cifar10.load_data()

labels = ['airplane','autmobile','bird','cat','dear','dog','frog','horse','ship','truck']

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=36)

x_train = x_train/255.0
x_test = x_test/255.0

model = Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(32,32,3)))
model.add(MaxPool2D(2,2)) #池化层
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))

model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['accuracy'])
history = model.fit(x_train,y_train,epochs=10,validation_data=(x_test,y_test))

1:加载数据集

(x_train,y_train),(x_test,y_test) = cifar10.load_data()

从库中导入数据并进行划分

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=36)

显示图片如下:

TensorFlow2.0 多分类案例CIFAR10_第1张图片

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个神经元,卷积核大小为3*3,input_shape输入图片大小三通道。
model.add(MaxPool2D(2,2)) #池化层
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))

5:模型编译和训练

model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['accuracy'])
history = model.fit(x_train,y_train,epochs=10,validation_data=(x_test,y_test))

categorical_crossentropy与SparseCategoricalCrossentropy区别:

两者都是多分类交叉熵损失函数,区别再与sparse(稀疏),在于对target编码的要求。

1:第一个要求target为onehot编码。

2:第二个要求为非onehot编码,函数内部进行onehot实现。

你可能感兴趣的:(TensorFlow2.0 多分类案例CIFAR10)