python图像分类代码
时间: 2023-07-22 17:41:55 浏览: 58
以下是一个简单的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
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
# 加载数据
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 将数据转换为float类型并归一化
X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32') / 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(Conv2D(64, (3, 3), activation='relu'))
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.reshape(-1, 28, 28, 1), y_train,
batch_size=32,
epochs=10,
verbose=1,
validation_data=(X_test.reshape(-1, 28, 28, 1), y_test))
# 评估模型
score = model.evaluate(X_test.reshape(-1, 28, 28, 1), y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
```
这个模型使用了两个卷积层来提取图像特征,然后通过全连接层进行分类。在训练期间,使用了Dropout来防止过拟合。最后,使用测试数据评估了模型的性能。
阅读全文