使用卷积神经网络对mnist数据集进行分类
时间: 2023-11-14 09:16:07 浏览: 92
好的,下面是使用卷积神经网络对MNIST数据集进行分类的步骤:
1. 导入必要的库
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
```
2. 导入并预处理数据集
```python
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
```
3. 构建卷积神经网络模型
```python
model = keras.Sequential(
[
layers.Conv2D(32, kernel_size=(3, 3), activation="relu", input_shape=(28, 28, 1)),
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"),
]
)
```
4. 编译模型
```python
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
```
5. 训练模型
```python
model.fit(x_train, y_train, batch_size=128, epochs=15, validation_split=0.1)
```
6. 在测试集上评估模型
```python
test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test accuracy:", test_acc)
```
完整的代码如下:
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# 导入并预处理数据集
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
# 构建卷积神经网络模型
model = keras.Sequential(
[
layers.Conv2D(32, kernel_size=(3, 3), activation="relu", input_shape=(28, 28, 1)),
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"),
]
)
# 编译模型
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
# 训练模型
model.fit(x_train, y_train, batch_size=128, epochs=15, validation_split=0.1)
# 在测试集上评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print("Test accuracy:", test_acc)
```
希望能对你有所帮助!
阅读全文