卷积神经网络实现CIFAR-10图片分类

复制代码
import tensorflow as tf
from tensorflow.keras import datasets ,layers ,models
import matplotlib.pyplot as plt
# load and normalize the data
(x_train, y_train), (x_test, y_test) = datasets.cifar10.load_data()
num_classes = 10
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255

# CNN
model=tf.keras.Sequential()
# unit 1
model.add(layers.Conv2D(16, (3, 3), padding='same',activation=tf.nn.relu, input_shape=x_train.shape[1:]))
model.add(layers.Conv2D(16, (3, 3), padding='same',activation=tf.nn.relu))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))

# unit 2
model.add(layers.Conv2D(32, (3, 3), padding='same',activation=tf.nn.relu))
model.add(layers.Conv2D(32, (3, 3), padding='same',activation=tf.nn.relu))
model.add(layers.MaxPooling2D(pool_size=(2, 2)))
model.add(layers.Dropout(rate=0.1))

# unit 3
model.add(layers.Flatten())
model.add(layers.Dense(128,activation='relu'))
model.add(layers.Dense(num_classes,activation='softmax'))

model.summary()


# train the model using ADAM
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
# fit
history=model.fit(x_train, y_train, batch_size=64, epochs=5, validation_split=0.2)

# 训练结果可视化
loss = history.history["loss"]
val_loss = history.history["val_loss"]
acc = history.history["sparse_categorical_accuracy"]
val_acc = history.history["val_sparse_categorical_accuracy"]
plt.subplot(1,2,1)
plt.plot(loss,label = "Training Loss")
plt.plot(val_loss,label = "Validation Loss")
plt.title("Trainning and Validation Loss")
plt.legend()
plt.subplot(1,2,2)
plt.plot(acc,label = "Training Acc")
plt.plot(val_acc,label = "Validation Acc")
plt.title("Training and Validation Acc")
plt.legend()

# evaluate
model.evaluate(x_test, y_test,verbose=2)
复制代码

 

posted @   山海自有归期  阅读(87)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示