cifar10分类及可视化
时间: 2023-09-26 20:13:34 浏览: 14
CIFAR-10是一个包含10个类别的图像数据集,每个类别有6000张32x32像素的彩色图像。这些类别分别为:飞机、汽车、鸟类、猫、鹿、狗、青蛙、马、船和卡车。
下面是cifar10的分类及可视化代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import cifar10
from keras.utils import np_utils
# 加载数据
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
# 数据预处理
X_train = X_train.astype('float32') / 255.0
X_test = X_test.astype('float32') / 255.0
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
# 可视化前10张图像
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(X_train[i])
plt.axis('off')
plt.show()
# 构建模型并训练
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=X_train.shape[1:]))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same', activation='relu'))
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(512, 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=64, epochs=10, validation_data=(X_test, y_test))
# 可视化模型预测结果
y_pred = model.predict(X_test)
y_pred_classes = np.argmax(y_pred, axis=1)
y_true = np.argmax(y_test, axis=1)
fig, axes = plt.subplots(5, 5, figsize=(12, 12))
axes = axes.ravel()
for i in np.arange(0, 25):
axes[i].imshow(X_test[i])
axes[i].set_title("True: %s \nPredict: %s" % (y_true[i], y_pred_classes[i]))
axes[i].axis('off')
plt.subplots_adjust(wspace=1)
plt.show()
```
这段代码会加载cifar10数据集,并对其进行预处理,在可视化中展示前10张图像。然后,我们构建了一个卷积神经网络模型,并在训练过程中使用了验证数据集。最后,我们使用模型对测试集中的图像进行预测,并在可视化中展示了预测结果。
阅读全文