使用tensorflow2.x实现CNN模型(BaseLine)

背景:最近在学习使用tensorflow2.x版本的API,自己手动实现了CNN模型,采用的是cifar10的数据集,写一篇博客,供自己回忆,供他人参考。

BaseLine的流程: 1、获得数据集 2、创建模型 3、优化模型 4、模型训练 5、模型的保存与恢复 6、模型可视化
import tensorflow as tf
from matplotlib import pyplot as plt
from tensorflow.keras.layers import Conv2D, Activation, MaxPool2D, Flatten, Dense
from tensorflow.keras import Model
import os


# 获得数据集
cifar10 = tf.keras.datasets.cifar10
# 得到X与y
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train, x_test = x_train / 255.0, x_test/255.0

# 第一个数据的显示
# plt.imshow(x_train[2])
# plt.show()

# 创建模型 
class BaseLine(Model):
    # 构造方法
    def __init__(self):
        super(BaseLine, self).__init__()
        # 卷积
        self.c1 = Conv2D(
            # 卷积核的个数
            filters=6,
            # 卷积窗口的大小
            kernel_size = (5, 5),
            # 步长
            strides=1,
            # 是否填充
            padding=same
        )

        # 激活
        self.a1 = Activation(relu)

        # 池化
        self.p1 = MaxPool2D(
            # 池化的窗口
            pool_size=(2,2),
            # 步长
            strides=2,
            # 是否填充
            padding=same
        )
        # 拉平
        self.flatten = Flatten()

        # 全链接
        self.f1 = Dense(128, activation=relu)
        self.f2 = Dense(10, activation=softmax)

        pass
    
    # 前向传播的方法
    def call(self, x):
        # 卷积
        x = self.c1(x)
        # 激活
        x = self.a1(x)
        # 池化
        x = self.p1(x)
        # 拉平
        x = self.flatten(x)
        # 全连接1
        x = self.f1(x)
        # 全连接2
        y = self.f2(x)
        return y
    pass


# 创建模型
model = BaseLine()

# 优化模型
model.compile(
    optimizer=adam,
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
    metrics=[sparse_categorical_accuracy]
)

# 模型的保存
checkpoint_path = ./checkpoint/BaseLine/BaseLine.ckpt
cp_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_path,
    save_weights_only=True,
    verbose=1
)
# 模型的恢复
if os.path.exists(checkpoint_path+".index"):
    print("模型恢复")
    model.load_weights(checkpoint_path)


# 模型的训练
history = model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), callbacks=[cp_callback])

# 模型的参数输出
model.summary()
print(model.trainable_variables)
file = open(./checkpoint/BaseLine/weights.txt, w)
for v in model.trainable_variables:
    file.write(str(v.name) + 
)
    file.write(str(v.shape) + 
)
    file.write(str(v.numpy()) + 
)
file.close()

# 绘制准确率
# 拿到训练集上的准确率
acc = history.history[sparse_categorical_accuracy]
# 拿到测试集合上的准确率
val_acc = history.history[val_sparse_categorical_accuracy]
# 拿到训练集上的loss损失
loss = history.history[loss]
# 拿到训练集上的loss损失
val_loss = history.history[val_loss]

print(acc)
print(val_acc)
print(loss, val_loss)

# 绘制准确率的图
plt.subplot(1, 2, 1)
plt.plot(acc, label=Training Accuracy)
plt.plot(val_acc, label=Validation_Accuracy)
plt.legend()
plt.title(Accuracy)

# 绘制损失的图片
plt.subplot(1, 2, 2)
plt.plot(loss, label=Training loss)
plt.plot(val_loss, label=Validation_loss)
plt.legend()
plt.title(Loss)

plt.show()
经验分享 程序员 微信小程序 职场和发展