【tensorflow】使用CNN模型对cifar10数据集进行简单分类

github在此

一.创建名字为tensorflow的虚拟环境

conda create -n tensorflow python=3.7

我命名为tensorflow,python版本的3.7,numpy版本为1.16

(正常情况下下载的tensorflow是2.2以上的版本)
【注】安装1.14版本的tensorflow,csdn参考在此.

二.导入tensorflow库,并下载准备cifar数据

1.新建一个py文件
2.在py文件最前面加上Copyright

#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

3.导入tensorflow库,keras,matplotlib

import tensorflow as tf

from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

4.下载并准备cifar10数据集

(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0

三.可视化前25张图片,验证数据集

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
               'dog', 'frog', 'horse', 'ship', 'truck']

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    # The CIFAR labels happen to be arrays, 
    # which is why you need the extra index
    plt.xlabel(class_names[train_labels[i][0]])
plt.show()

Mac上的matplot

四.创建卷积基

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))

查看模型结构的信息

model.summary()

四.创建全连接层

model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))

查看整个模型结构

model.summary()

四.训练模型

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels))

五.测试模型并可视化

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

在这里插入图片描述
结果
在这里插入图片描述

五.保存模型数据,重加载模型

保存keras模型

model.save( '/Users/liuyi/Desktop/cifar10/cifar10_data/my_test_model.ckpt')

重新实例化模型
#keras.models.load_model(filepath)
#or h5结构

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

五.对单张图片进行预测

i=3
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer','dog', 'frog', 'horse', 'ship', 'truck']
from keras.preprocessing import image
img = test_images[i]
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict(images, batch_size=32)
print(classes)
y_test_pred = np.argmax(classes, axis=1)
print(y_test_pred,class_names[y_test_pred[0]])

对test_images[3]进行预测的结果:
在这里插入图片描述

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解答这个问题。首先,我们需要了解一下CNN模型的基本结构和CIFAR-10数据集的基本信息。 CNN模型是一种用于图像识别和分类的深度学习模型,它可以有效地捕捉图像中的局部特征。CIFAR-10数据集是一个包含10个类别、每个类别有6000个32x32彩色图像的数据集,其中50000个用于训练,10000个用于测试。 现在,我们可以开始构建CNN模型CIFAR-10数据进行分类。以下是一个简单CNN模型的代码示例: ``` import tensorflow as tf from tensorflow.keras import layers # 定义模型 model = tf.keras.Sequential([ layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(10) ]) # 编译模型 model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # 训练模型 model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels)) ``` 在上面的代码示例中,我们使用了`Sequential`模型来定义CNN模型。该模型包含了三个卷积层和两个全连接层。每个卷积层都使用了ReLU激活函数和最大池化操作,以便有效地捕捉图像中的特征。最后一层是一个具有10个节点的密集层,用于将卷积层的输出映射到10个类别上。 在编译模型时,我们使用了Adam优化器和稀疏分类交叉熵损失函数。我们还使用了准确率作为评估指标。 最后,我们使用`fit`方法来训练模型,并在测试集上进行验证。在此过程中,模型将自动调整权重和偏置,以便最小化损失函数并提高准确率。 当然,这只是一个简单的示例,实际上,我们可以通过调整模型的结构和参数来进一步提高模型的性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值