卷积神经网络CNN完整代码
时间: 2024-06-10 09:03:22 浏览: 167
卷积神经网络(Convolutional Neural Network, CNN)是一种深度学习模型,主要用于图像处理和计算机视觉任务。由于篇幅限制,我将给出一个简单的Python(使用Keras库)实现CNN的高层次概述,并提供关键部分的代码。完整的CNN代码通常会包含数据预处理、模型定义、编译、训练和评估等步骤。
**1. 导入所需的库:**
```python
import tensorflow as tf
from tensorflow.keras import layers
```
**2. 数据预处理:**(假设你已经有了数据集并已划分成训练集和验证集)
```python
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
```
**3. 定义CNN模型:**
```python
model = tf.keras.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(), # 展平二维数组为一维
layers.Dense(128, activation='relu'),
layers.Dropout(0.5), # 防止过拟合
layers.Dense(10, activation='softmax') # 输出层,10个类别
])
```
**4. 编译模型:**
```python
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
```
**5. 训练模型:**
```python
history = model.fit(x_train, y_train, epochs=10,
validation_data=(x_test, y_test))
```
**6. 评估模型:**
```python
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f"Test accuracy: {test_acc}")
```
阅读全文