CNN卷积神经网络代码加实战训练python实现
时间: 2024-11-15 21:27:38 浏览: 27
CNN (Convolutional Neural Network) 卷积神经网络是一种深度学习模型,常用于图像识别、计算机视觉等领域,因为它们能够自动从输入数据中提取特征。在Python中,最常用的库如TensorFlow或PyTorch可以方便地实现CNN。
下面是一个简单的使用Keras库(它基于TensorFlow)创建和训练CNN的基本步骤:
```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, test_images = train_images / 255.0, test_images / 255.0
# 将图像调整为4D张量(适合卷积操作)
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
# 创建模型
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.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10)) # 输出层,10表示MNIST有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(f"Test accuracy: {test_acc}")
```
在这个例子中,我们首先加载并预处理数据,然后创建一个包含两个卷积层、池化层和全连接层的简单CNN架构。接下来,编译模型,指定优化器和损失函数,最后训练模型并在测试集上验证其性能。
阅读全文
相关推荐


















