按照文件的内容修改代码
时间: 2024-10-24 08:12:57 浏览: 18
好的,我将根据您提供的路径信息对代码进行修改,使其更清晰地显示训练集、验证集和测试集的路径。
```python
import os
import json
import numpy as np
import pandas as pd
from PIL import Image
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from sklearn.metrics import f1_score, accuracy_score
# 加载数据集
def load_data(data_dir, label_path):
# 读取标签文件
with open(label_path, 'r') as f:
labels_list = json.load(f)
# 将标签文件转换为字典格式
labels = {item['文件名']: item['标签'] for item in labels_list if '文件名' in item and '标签' in item}
images = []
targets = []
# 遍历所有图像文件并加载图像
for file_name, label in labels.items():
img_path = os.path.join(data_dir, file_name)
if not os.path.exists(img_path):
continue
img = Image.open(img_path).resize((128, 128)) # 调整图像大小
img_array = np.array(img) / 255.0 # 归一化图像像素值
images.append(img_array)
targets.append(label)
if len(images) == 0:
raise ValueError("No valid images found.")
return np.array(images), np.array(targets)
# 数据目录和标签路径
train_data_dir = "C:\\Users\\24067\\Desktop\\peach_split\\train"
train_label_path = "C:\\Users\\24067\\Desktop\\train_label.json"
val_data_dir = "C:\\Users\\24067\\Desktop\\peach_split\\val"
val_label_path = "C:\\Users\\24067\\Desktop\\val_label.json"
test_data_dir = "C:\\Users\\24067\\Desktop\\peach_split\\test"
test_label_path = "C:\\Users\\24067\\Desktop\\train_label.json"
# 加载训练数据
train_images, train_labels = load_data(train_data_dir, train_label_path)
# 加载验证数据
val_images, val_labels = load_data(val_data_dir, val_label_path)
# 标签映射
label_map = {'特级': 3, '一级': 2, '二级': 1, '三级': 0}
train_labels = np.array([label_map[label] for label in train_labels])
val_labels = np.array([label_map[label] for label in val_labels])
# 创建模型
def create_model(input_shape=(128, 128, 3)):
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape), # 第一个卷积层
MaxPooling2D((2, 2)), # 最大池化层
Conv2D(64, (3, 3), activation='relu'), # 第二个卷积层
MaxPooling2D((2, 2)), # 最大池化层
Conv2D(128, (3, 3), activation='relu'), # 第三个卷积层
MaxPooling2D((2, 2)), # 最大池化层
Flatten(), # 展平层
Dense(128, activation='relu'), # 全连接层
Dropout(0.5), # Dropout层
Dense(4, activation='softmax') # 输出层
])
return model
# 实例化模型
model = create_model()
# 编译模型
model.compile(optimizer=Adam(learning_rate=0.001),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 图像增强
datagen = ImageDataGenerator(
rotation_range=20, # 随机旋转角度
width_shift_range=0.2, # 水平偏移范围
height_shift_range=0.2, # 垂直偏移范围
horizontal_flip=True, # 水平翻转
vertical_flip=True # 垂直翻转
)
# 训练模型
history = model.fit(datagen.flow(train_images, train_labels, batch_size=32),
epochs=300,
validation_data=(val_images, val_labels))
# 评估模型
def evaluate_model(model, X, y):
predictions = model.predict(X)
predicted_labels = np.argmax(predictions, axis=1)
accuracy = accuracy_score(y, predicted_labels)
阅读全文