python图像分类代码
时间: 2023-07-22 10:22:21 浏览: 37
以下是一个基于 Python 和 TensorFlow 的图像分类代码示例:
```python
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 加载数据集
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
# 数据归一化
train_images = train_images / 255.0
test_images = test_images / 255.0
# 定义模型
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
# 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(train_images, train_labels, epochs=10)
# 评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
# 预测结果
predictions = model.predict(test_images)
# 显示预测结果和实际标签
for i in range(10):
plt.imshow(test_images[i], cmap=plt.cm.binary)
plt.title("Predicted: " + str(np.argmax(predictions[i])) + ", Actual: " + str(test_labels[i]))
plt.show()
```
这个例子使用 MNIST 数据集,它包含了手写数字的图像,目标是对这些图像进行分类。在模型的定义中,我们使用了一个包含两个隐藏层的神经网络,其中每个隐藏层都有 128 个神经元,输出层有 10 个神经元,对应着数字 0 到 9。最后,我们使用 evaluate() 函数评估模型在测试集上的表现,并使用 predict() 函数对测试集中的图像进行分类预测。