1.下载数据cifar-10数据集:
import tensorflow as tf
cifar10 = tf.keras.datasets.cifar10
(x_train,y_train),(x_test,y_test) = cifar10.load_data()
2.然后我们查看一下下载的数据:
print('training data shape:',x_train.shape)
print('training labels shape:',y_train.shape)
print('test data shape:',x_test.shape)
print('test labels shape:',y_test.shape)
3.打开其中一张图片看看:
from matplotlib import pyplot as plt
plt.imshow(x_train[8])
4.定义分类数:
#定义数据字典
label_dict = {0:"airplane",1:"automoblie",2:"bird",3:"cat",4:"deer",5:"dog",6:"frog",7:"horse",
8:"ship",9:"truck"}
5.对图像进行归一化,标准化:
#数据标准化
x_train = x_train.astype('float32')/255.0
x_test = x_test.astype('float32')/255.0
6.初始化一个keras模型:
#建立Sequential线性堆叠模型
model = tf.keras.models.Sequential()
7.建立第一层网络(卷积层+Dropout+maxpooling):
#第一个卷积层
model.add(tf.keras.layers.Conv2D(filters= 32,kernel_size = (3,3),
input_shape = (32,32,3),
activation = 'relu',
padding = 'same'))
#Dropout防止过拟和
model.add(tf.keras.layers.Dropout(rate=0.3))
#第一个池化层
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))
8.第二层网络:
#第二个卷积层
model.add(tf.keras.layers.Conv2D(filters= 64,kernel_size = (3,3),
activation = 'relu',
padding = 'same'))
#Dropout防止过拟和
model.add(tf.keras.layers.Dropout(rate=0.3))
#第一个池化层
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2)))
#平坦层
model.add(tf.keras.layers.Flatten())
#添加输出层
model.add(tf.keras.layers.Dense(10,activation = 'softmax'))
9.查看一下我们的网络结构:
model.summary()
10.设置训练参数(轮数和训练样本数):
#设置训练参数
train_epochs = 2 #训练轮数
batch_size = 100 #单次训练样本数(批次大小)
11.设置模型算法(adam优化器+loss损失函数+精确度)
#定义训练模型
model.compile(optimer = 'adam',#优化器
loss= 'sparse_categorical_crossentropy',#损失函数
metrics = ['accuracy'])#评估模型的方式
12.开始训练模型:
#训练模型
train_history = model.fit(x_train,y_train,
validation_split=0.2,
epochs = train_epochs,
batch_size = batch_size,
verbose = 2)
13.查看模型训练情况:
test_loss,test_acc = model.evaluate(x_test,y_test,verbose=2)
print('Test accuracy:',test_acc)
14.使用训练好的模型进行预测:
#进行预测
preds = model.predict_classes(x_test)
15.查看预测结果:
preds
16.可视化预测结果:
#可视化预测结果
def plot_images_labels_prediction(images,
labels,
preds,
index,
num=5):
fig = plt.gcf()#获取图表
fig.set_size_inches(12,6)
if num>10:
num=10
for i in range(0,num):
ax = plt.subplot(2,5,i+1)
ax.imshow(images[index])
title = str(i)+','+label_dict[labels[index][0]]
if len(preds) >0:
title += '=>' +label_dict[preds[index]]
ax.set_title(title,fontsize=10)
index +=1
plt.show()
17.查看前10个预测结果:
plot_images_labels_prediction(x_test,y_test,preds,0,10)
18.保存模型:
#保存模型
model_filename = 'D:/2/models/cifarCNNModel.h5'
model.save_weights(model_filename)
print("已保存模型权重!")
有用点赞!!