卷积神经网络可以实现两类图像识别分类功能的代码
时间: 2023-10-15 16:08:25 浏览: 75
【图像识别】基于卷积神经网络实现minist数据集分类附matlab代码 上传.zip
1. 图像分类
下面是一个简单的卷积神经网络,用于图像分类任务:
```python
import tensorflow as tf
# 定义卷积神经网络,包括卷积层、池化层和全连接层
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10)
])
# 编译模型
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# 加载数据集
mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 转换数据集格式
train_images = train_images.reshape((60000, 28, 28, 1))
train_images = train_images / 255.0
test_images = test_images.reshape((10000, 28, 28, 1))
test_images = test_images / 255.0
# 训练模型
model.fit(train_images, train_labels, epochs=5)
# 评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('Test accuracy:', test_acc)
```
2. 目标检测
下面是一个简单的卷积神经网络,用于目标检测任务:
```python
import tensorflow as tf
# 定义卷积神经网络,包括卷积层、池化层和全连接层
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(None, None, 3)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(4) # 四个坐标值分别表示目标框的左上角和右下角坐标
])
# 编译模型
model.compile(optimizer='adam',
loss='mse')
# 加载数据集
dataset = tf.data.Dataset.from_tensor_slices((train_images, train_labels))
# 定义数据预处理函数
def preprocess_image(image, labels):
# 对图像进行归一化和缩放
image = tf.cast(image, tf.float32) / 255.0
image = tf.image.resize(image, (224, 224))
return image, labels
# 对数据集进行预处理和打乱
dataset = dataset.map(preprocess_image).shuffle(buffer_size=1024)
# 训练模型
model.fit(dataset.batch(32), epochs=10)
# 评估模型
test_loss = model.evaluate(test_images, test_labels, verbose=2)
print('Test loss:', test_loss)
```
阅读全文