调用cnn模型训练mnist 数据集
时间: 2023-09-11 15:09:01 浏览: 93
fashion-mnist数据集
以下是使用Keras框架调用CNN模型训练MNIST数据集的代码示例:
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# Load MNIST dataset
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Preprocess data
x_train = x_train.astype("float32") / 255
x_test = x_test.astype("float32") / 255
x_train = tf.expand_dims(x_train, -1)
x_test = tf.expand_dims(x_test, -1)
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
# Define model architecture
model = keras.Sequential(
[
keras.Input(shape=(28, 28, 1)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(10, activation="softmax"),
]
)
# Compile model
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
# Train model
model.fit(x_train, y_train, batch_size=128, epochs=5, validation_split=0.1)
# Evaluate model
test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test accuracy:", test_acc)
```
这个模型包括两个卷积层和一个全连接层,其中包括一个dropout层以避免过拟合。训练过程中使用adam优化器和分类交叉熵损失函数。在训练5个epoch之后,我们可以得到大约0.99的测试准确率。
阅读全文