CNN进行分类预测的python代码
时间: 2023-09-11 16:09:49 浏览: 86
以下是一个使用CNN进行图像分类预测的Python代码示例:
首先,导入必要的库:
```python
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
```
然后,加载数据集并进行预处理:
```python
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
train_images, test_images = train_images / 255.0, test_images / 255.0
```
接下来,定义模型:
```python
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))
```
然后,编译模型:
```python
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
```
接着,训练模型:
```python
history = model.fit(train_images, train_labels, epochs=10,
validation_data=(test_images, test_labels))
```
最后,使用模型进行预测:
```python
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
predictions = model.predict(test_images)
for i in range(10):
plt.imshow(test_images[i], cmap=plt.cm.binary)
plt.title(f"Prediction: {class_names[tf.argmax(predictions[i])]}")
plt.show()
```
注意,这只是一个简单的示例,实际应用中需要根据具体情况进行调整和优化。
阅读全文