要求改进代码,将训练集,验证集,测试集的路径在代码中清晰的写出.
时间: 2024-10-24 21:13:46 浏览: 22
yolov8实例分割训练和测试过程用到的所有代码文件
为了使代码更加清晰和易于维护,可以将训练集、验证集和测试集的路径定义为常量,并在需要的地方引用这些常量。以下是改进后的代码:
```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
# 定义路径常量
TRAIN_DATA_DIR = "C:\\Users\\24067\\Desktop\\peach_split\\train"
VAL_DATA_DIR = "C:\\Users\\24067\\Desktop\\peach_split\\val"
TEST_DATA_DIR = "C:\\Users\\24067\\Desktop\\peach_split\\test"
TRAIN_LABEL_PATH = "C:\\Users\\24067\\Desktop\\train_label.json"
VAL_LABEL_PATH = "C:\\Users\\24067\\Desktop\\val_label.json"
# 加载数据集
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)
# 加载训练数据
images, labels = load_data(TRAIN_DATA_DIR, TRAIN_LABEL_PATH)
# 标签映射
label_map = {'特级': 3, '一级': 2, '二级': 1, '三级': 0}
labels = np.array([label_map[label] for label in
阅读全文