Python通过CNN进行分类代码
时间: 2024-01-02 12:04:15 浏览: 60
以下是一个使用CNN进行图像分类的Python代码示例,该示例使用了Keras库和MNIST数据集:
```python
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import np_utils
# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 将输入数据reshape为4D张量,即[样本数, 长度, 宽度, 通道数]
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32')
# 归一化输入数据
X_train /= 255
X_test /= 255
# 将输出标签进行one-hot编码
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# 定义模型结构
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=1)
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
这段代码中,我们首先加载MNIST数据集并将其reshape为4D张量,然后归一化输入数据,将输出标签进行one-hot编码。接着,我们定义了一个包含两个卷积层和两个全连接层的CNN模型,并编译该模型。最后,我们使用训练数据训练模型,并使用测试数据评估该模型的性能。
阅读全文