074. 编写一个函数,实现简单的图像识别功能
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((