深度学习实战Python识别图像技术程序代码
时间: 2024-11-07 20:29:02 浏览: 45
python深度学习猫狗识别程序
5星 · 资源好评率100%
深度学习实战中,使用Python进行图像识别通常会涉及到卷积神经网络(Convolutional Neural Networks, CNN)。下面是一个简单的例子,使用Keras库来构建一个基本的图像分类模型:
```python
# 导入必要的库
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
# 加载MNIST数据集
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
# 数据预处理
train_images = train_images / 255.0
test_images = test_images / 255.0
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
# 构建CNN模型
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.2),
layers.Dense(10, activation='softmax')
])
# 编译模型
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(f"Test accuracy: {test_acc}")
#
阅读全文