导入mnist。cvn
时间: 2023-09-14 19:14:20 浏览: 44
下面是导入MNIST数据集和使用CNN进行训练的示例代码:
```python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 加载MNIST数据集并进行预处理
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1) / 255.0
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1) / 255.0
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 定义CNN模型
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=5, batch_size=64, validation_data=(x_test, y_test))
```
这个例子中,我们首先加载了MNIST数据集并进行了预处理。接着定义了一个包含多个卷积层和池化层的CNN模型,并使用softmax作为输出层的激活函数。最后编译模型,使用交叉熵作为损失函数,使用Adam优化器进行优化,使用准确率作为评估指标。最后训练模型并在测试集上进行了评估。