File size: 4,435 Bytes
009af1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

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")