写出cnn的python代码
时间: 2023-08-30 20:10:56 浏览: 106
当然,我很乐意为你提供CNN的Python代码。下面是一个简单的例子:
```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
# 定义CNN模型
model = models.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.Conv2D(64, (3, 3), activation='relu'),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(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))
```
希望可以帮到你!
阅读全文