Để xử lý bộ dữ liệu hình ảnh Pokémon một cách hiệu quả, quy trình sau đây được áp dụng:
- Tải dữ liệu và Tiền xử lý Bước đầu tiên là tạo danh sách đường dẫn ảnh và nhãn tương ứng:
def process_dataset(base_dir, csv_name, class_mapping):
image_paths = []
for class_name in class_mapping:
image_paths.extend(glob.glob(os.path.join(base_dir, class_name, '*.png')))
image_paths.extend(glob.glob(os.path.join(base_dir, class_name, '*.jpg')))
random.shuffle(image_paths)
with open(os.path.join(base_dir, csv_name), 'w') as f:
writer = csv.writer(f)
for path in image_paths:
class_id = class_mapping[os.path.basename(os.path.dirname(path))]
writer.writerow([path, class_id])
# Đọc dữ liệu từ file CSV
paths, labels = [], []
with open(os.path.join(base_dir, csv_name)) as f:
for row in csv.reader(f):
paths.append(row[0])
labels.append(int(row[1]))
return paths, labels
Sử dụng hàm này để chia tập dữ liệu thành tập huấn luyện, validation và test:
def split_dataset(paths, labels, split_ratios=[0.6, 0.2, 0.2]):
split_points = [int(len(paths) * ratio) for ratio in split_ratios]
return [
paths[split_points[0]:split_points[1]],
paths[split_points[1]:],
labels[:split_points[0]],
labels[split_points[0]:split_points[1]],
labels[split_points[1]:]
]
- Tiền xử lý ảnh và Tăng cường Dữ liệu Hàm tiền xử lý kết hợp các kỹ thuật sau:
def transform_image(image_path, label):
image = tf.io.read_file(image_path)
image = tf.image.decode_jpeg(image, channels=3)
image = tf.image.resize(image, [256, 256])
# Tăng cường dữ liệu
image = tf.image.random_flip_left_right(image)
image = tf.image.random_crop(image, [224, 224, 3])
# Chuyển đổi về [0,1] và chuẩn hóa
image = tf.cast(image, tf.float32) / 255.0
image = (image - [0.49, 0.44, 0.41]) / [0.23, 0.22, 0.23]
return image, tf.one_hot(label, depth=5)
- Xây dựng Pipeline Dữ liệu
Sử dụng
tf.datađể tạo pipeline hiệu quả:
# Tạo tập huấn luyện
train_paths, train_labels = process_dataset('pokemon', 'dataset.csv', class_map)
train_paths, val_paths, train_labels, val_labels = split_dataset(train_paths, train_labels)
train_ds = tf.data.Dataset.from_tensor_slices((train_paths, train_labels))
train_ds = train_ds.shuffle(1000).map(transform_image).batch(64)
- Học Chuyển tiếp với VGG19 Áp dụng học chuyển tiếp để xử lý tập dữ liệu nhỏ:
base_model = tf.keras.applications.VGG19(
weights='imagenet',
include_top=False,
pooling='avg'
)
base_model.trainable = False
model = tf.keras.Sequential([
base_model,
tf.keras.layers.Dense(5, activation='softmax')
])
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-4),
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=['accuracy']
)
early_stop = tf.keras.callbacks.EarlyStopping(
monitor='val_accuracy',
min_delta=0.001,
patience=5
)
model.fit(
train_ds,
validation_data=val_ds,
epochs=100,
callbacks=[early_stop]
)
- Kết hợp với Mạng nhỏ Khi dữ liệu hạn chế, kết hợp mạng nhỏ với học chuyển tiếp:
def create_small_model():
base = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(224, 224, 3)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Conv2D(64, 3, activation='relu'),
tf.keras.layers.GlobalAveragePooling2D()
])
return tf.keras.Sequential([
base,
tf.keras.layers.Dense(5, activation='softmax')
])