import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import EfficientNetB0 from tensorflow.keras.applications.efficientnet import preprocess_input from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam import os import numpy as np import matplotlib.pyplot as plt # Đường dẫn đến thư mục chứa dữ liệu hoa DATA_DIR = 'flower_classification/flowers' # Kích thước ảnh đầu vào cho mô hình IMG_SIZE = (224, 224) BATCH_SIZE = 32 EPOCHS = 15 # Tăng số epoch nếu cần # QUAN TRỌNG: EfficientNetB0 có lớp tiền xử lý riêng, không nên dùng rescale=1./255 thủ công train_datagen = ImageDataGenerator( preprocessing_function=preprocess_input, # Sử dụng hàm tiền xử lý của EfficientNet rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest', validation_split=0.2 ) validation_datagen = ImageDataGenerator( preprocessing_function=preprocess_input, validation_split=0.2 ) # Load dữ liệu từ thư mục train_generator = train_datagen.flow_from_directory( DATA_DIR, target_size=IMG_SIZE, batch_size=BATCH_SIZE, class_mode='categorical', subset='training' ) validation_generator = validation_datagen.flow_from_directory( DATA_DIR, target_size=IMG_SIZE, batch_size=BATCH_SIZE, class_mode='categorical', subset='validation' ) # Lựa chọn mô hình nền EfficientNetB0 base_model = EfficientNetB0(weights='imagenet', include_top=False, input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3)) # QUAN TRỌNG: Đóng băng các lớp nhưng giữ BatchNormalization ở chế độ Inference (đặc biệt cho EfficientNet) base_model.trainable = False # Thêm các lớp tùy chỉnh để phân loại 5 loại hoa x = base_model.output x = GlobalAveragePooling2D()(x) # giảm chiều (flatten thông minh) x = Dropout(0.3)(x) # Thêm Dropout để chống Overfitting x = Dense(512, activation='relu')(x) # học feature mới predictions = Dense(train_generator.num_classes, activation='softmax')(x) # phân loại model = Model(inputs=base_model.input, outputs=predictions) # Compile mô hình với learning rate phù hợp cho Transfer Learning model.compile(optimizer=Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy']) print("--- Bắt đầu huấn luyện Phase 1 (Chỉ huấn luyện các lớp mới) ---") history = model.fit( train_generator, epochs=10, validation_data=validation_generator ) # --- Fine-tuning --- print("--- Bắt đầu huấn luyện Phase 2 (Fine-tuning một số lớp của EfficientNet) ---") # Giải phóng 20 lớp cuối cùng để fine-tune base_model.trainable = True for layer in base_model.layers[:-20]: layer.trainable = False # Compile lại với learning rate cực thấp để tránh phá hỏng các trọng số đã học model.compile(optimizer=Adam(learning_rate=0.0001), loss='categorical_crossentropy', metrics=['accuracy']) history_fine_tune = model.fit( train_generator, epochs=10, validation_data=validation_generator ) # Lưu mô hình cuối cùng MODEL_NAME = 'EfficientNetB0_flower_recognition_dl_model_fine_tuned.h5' model.save(MODEL_NAME) print(f"Huấn luyện hoàn tất! Mô hình đã được lưu vào {MODEL_NAME}") # Lưu tên lớp conv cuối cùng cho Grad-CAM ( EfficientNetB0 là 'top_activation' ) with open('last_conv_layer_name.txt', 'w') as f: f.write('top_activation') # Vẽ biểu đồ lịch sử huấn luyện plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.plot(history.history['accuracy'] + history_fine_tune.history['accuracy'], label='Train Acc') plt.plot(history.history['val_accuracy'] + history_fine_tune.history['val_accuracy'], label='Val Acc') plt.title('Accuracy') plt.legend() plt.subplot(1, 2, 2) plt.plot(history.history['loss'] + history_fine_tune.history['loss'], label='Train Loss') plt.plot(history.history['val_loss'] + history_fine_tune.history['val_loss'], label='Val Loss') plt.title('Loss') plt.legend() plt.savefig('training_history.png') print("Biểu đồ lịch sử huấn luyện đã được lưu vào training_history.png")