使用 TensorFlow的植物识别的验证集代码
时间: 2024-01-03 22:04:25 浏览: 34
以下是使用TensorFlow的植物识别的验证集代码,包括图像预处理、模型加载和验证集测试:
```python
import tensorflow as tf
import numpy as np
from PIL import Image
import os
# 定义输入图像大小和通道数
IMG_WIDTH, IMG_HEIGHT = 224, 224
CHANNELS = 3
# 加载模型
model = tf.keras.models.load_model('plant_classifier.h5')
# 定义类别标签
class_names = ['daisy', 'dandelion', 'rose', 'sunflower', 'tulip']
# 定义图像预处理函数
def preprocess_image(image_path):
img = Image.open(image_path)
img = img.resize((IMG_WIDTH, IMG_HEIGHT))
img_array = np.array(img) / 255.0
img_array = img_array.reshape((1, IMG_WIDTH, IMG_HEIGHT, CHANNELS))
return img_array
# 定义验证函数
def validate_images(image_dir):
num_correct = 0
num_total = 0
# 遍历所有图像文件并进行验证
for file_name in os.listdir(image_dir):
if not file_name.endswith('.jpg'):
continue
file_path = os.path.join(image_dir, file_name)
img_array = preprocess_image(file_path)
# 对图像进行预测并检查是否正确
prediction = model.predict(img_array)[0]
predicted_class = np.argmax(prediction)
true_class = class_names.index(file_name.split('_')[0])
if predicted_class == true_class:
num_correct += 1
num_total += 1
# 输出准确率
accuracy = num_correct / num_total
print(f'Accuracy: {accuracy:.2%} ({num_correct}/{num_total})')
# 测试验证集
validate_images('validation_set')
```
上述代码将加载之前训练好的模型,然后遍历验证集文件夹中的每个图像文件进行验证。对于每个图像文件,它将使用 `preprocess_image` 函数进行预处理,然后使用模型进行预测。如果预测结果与真实类别相同,则计入正确的预测数量。最后,输出准确率。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)