给我一个CNN图像识别的代码案例
时间: 2024-05-15 15:17:23 浏览: 74
cnn代码实例
以下是一个使用CNN进行图像识别的Python代码案例:
```python
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
# 下载并加载数据集
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
# 对数据进行预处理
train_images, test_images = train_images / 255.0, test_images / 255.0
# 定义模型
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.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
# 编译模型
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))
# 评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(test_acc)
```
该代码实现了一个简单的CNN模型,在CIFAR-10数据集上进行图像分类任务。运行结果会输出最终测试准确率。
阅读全文