074. 编写一个函数,实现简单的图像识别功能
在 Python 中,可以使用深度学习库(如 TensorFlow 或 PyTorch)来实现简单的图像识别功能。以下我们将使用 TensorFlow 和 Keras 来实现一个简单的图像识别模型,以识别手写数字(MNIST 数据集)为例。
安装依赖库
在开始之前,请确保你已经安装了 tensorflow
库。如果没有安装,可以通过以下命令安装:
pip install tensorflow
示例代码
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
def simple_image_recognition():
# 加载 MNIST 数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 数据预处理
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# 构建简单的卷积神经网络模型
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
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, activation='softmax'))
# 编译模型
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(train_images, train_labels, epochs=5, batch_size=64)
# 评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"测试集准确率: {test_acc:.4f}")
return model
# 示例用法
if __name__ == "__main__":
model = simple_image_recognition()
代码说明
数据加载与预处理:
-
使用
mnist.load_data()
加载 MNIST 数据集。 -
将图像数据重塑为
(28, 28, 1)
的形状,并归一化到[0, 1]
。 -
将标签转换为 one-hot 编码。
模型构建:
-
使用
Sequential
构建模型。 -
添加卷积层(
Conv2D
)和最大池化层(MaxPooling2D
)。 -
添加全连接层(
Dense
)和输出层(使用softmax
激活函数)。
模型编译:
- 使用
adam
优化器和categorical_crossentropy
损失函数。
模型训练与评估:
-
使用
fit
方法训练模型。 -
使用
evaluate
方法评估模型性能。
示例输出
Epoch 1/5
938/938 [==============================] - 10s 10ms/step - loss: 0.2538 - accuracy: 0.9248
Epoch 2/5
938/938 [==============================] - 9s 10ms/step - loss: 0.0987 - accuracy: 0.9678
Epoch 3/5
938/938 [==============================] - 9s 10ms/step - loss: 0.0675 - accuracy: 0.9789
Epoch 4/5
938/938 [==============================] - 9s 10ms/step - loss: 0.0567 - accuracy: 0.9823
Epoch 5/5
938/938 [==============================] - 9s 10ms/step - loss: 0.0489 - accuracy: 0.9856
313/313 [==============================] - 2s 6ms/step - loss: 0.0789 - accuracy: 0.9824
测试集准确率: 0.9824
扩展功能
如果你需要更复杂的图像识别功能,可以考虑以下内容:
数据增强:
from tensorflow.keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(
rotation_range=10,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=0.1,
zoom_range=0.1,
horizontal_flip=True,
fill_mode='nearest'
)
datagen.fit(train_images)
预训练模型:使用预训练的模型(如 VGG16、ResNet 等)进行迁移学习。
from tensorflow.keras.applications import VGG16
base_model = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
多分类问题:如果需要处理多分类问题,可以调整输出层的神经元数量和激活函数。
模型保存与加载:
model.save('my_model.h5')
from tensorflow.keras.models import load_model
loaded_model = load_model('my_model.h5')
视频讲解
BiliBili: 视睿网络-哔哩哔哩视频 (bilibili.com)