starpreeda commited on
Commit
e335787
·
verified ·
1 Parent(s): 59fe8ed

Upload train_efficientnetb0_finetuned.py

Browse files
Files changed (1) hide show
  1. train_efficientnetb0_finetuned.py +131 -0
train_efficientnetb0_finetuned.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ from tensorflow.keras.applications import EfficientNetB0
3
+ from tensorflow.keras.applications.efficientnet import preprocess_input
4
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
5
+ from tensorflow.keras.models import Model
6
+ from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout, BatchNormalization
7
+ from tensorflow.keras.optimizers import Adam
8
+ from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping
9
+ import numpy as np
10
+
11
+ TRAIN_DIR = r'C:\Python_CV\mritest\Training'
12
+ TEST_DIR = r'C:\Python_CV\mritest\Testing'
13
+ IMG_SIZE = (224, 224)
14
+ BATCH_SIZE = 16 # ลด Batch Size ลงเพื่อเพิ่ม Generalization
15
+
16
+ # 1. Data Augmentation แบบเข้มข้น
17
+ train_datagen = ImageDataGenerator(
18
+ preprocessing_function=preprocess_input,
19
+ rotation_range=15,
20
+ width_shift_range=0.1,
21
+ height_shift_range=0.1,
22
+ shear_range=0.1,
23
+ zoom_range=0.15,
24
+ horizontal_flip=True,
25
+ fill_mode='nearest'
26
+ )
27
+
28
+ test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
29
+
30
+ train_gen = train_datagen.flow_from_directory(
31
+ TRAIN_DIR, target_size=IMG_SIZE, batch_size=BATCH_SIZE, class_mode='categorical', shuffle=True
32
+ )
33
+
34
+ test_gen = test_datagen.flow_from_directory(
35
+ TEST_DIR, target_size=IMG_SIZE, batch_size=BATCH_SIZE, class_mode='categorical', shuffle=False
36
+ )
37
+
38
+ # 2. สร้างโครงสร้างโมเดล
39
+ base_model = EfficientNetB0(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
40
+
41
+ # Unfreeze 40 ชั้นสุดท้ายของ EfficientNetB0 เพื่อ Fine-Tune
42
+ base_model.trainable = True
43
+ for layer in base_model.layers[:-40]:
44
+ layer.trainable = False
45
+
46
+ x = base_model.output
47
+ x = GlobalAveragePooling2D()(x)
48
+ x = BatchNormalization()(x)
49
+ x = Dense(256, activation='relu')(x)
50
+ x = Dropout(0.4)(x) # ลด Overfitting
51
+ outputs = Dense(4, activation='softmax')(x)
52
+
53
+ model = Model(inputs=base_model.input, outputs=outputs)
54
+
55
+ # 3. คอมไพล์โมเดลด้วย Learning Rate ต่ำสำหรับ Fine-tuning
56
+ model.compile(
57
+ optimizer=Adam(learning_rate=1e-4),
58
+ loss='categorical_crossentropy',
59
+ metrics=['accuracy']
60
+ )
61
+
62
+ # 4. Callbacks ปรับ Learning Rate อัตโนมัติเมื่อ Accuracy เริ่มนิ่ง
63
+ callbacks = [
64
+ ReduceLROnPlateau(monitor='val_accuracy', factor=0.3, patience=3, verbose=1, min_lr=1e-6),
65
+ EarlyStopping(monitor='val_accuracy', patience=7, restore_best_weights=True)
66
+ ]
67
+
68
+ # 5. เทรนโมเดล
69
+ print("Starting Fine-Tuning Training...")
70
+ history = model.fit(
71
+ train_gen,
72
+ epochs=25,
73
+ validation_data=test_gen,
74
+ callbacks=callbacks
75
+ )
76
+
77
+ # 6. ประเมินผลความแม่นยำ
78
+ test_loss, test_acc = model.evaluate(test_gen)
79
+ print(f"\n>>> Final Test Accuracy: {test_acc * 100:.2f}% <<<")
80
+
81
+ # บันทึกโมเดลไว้ในโฟลเดอร์โครงการ
82
+ model.save(r'C:\Python_CV\mritest\efficientnetb0_finetuned_brain_mri.keras')
83
+ print("เซฟโมเดลแบบ .keras เรียบร้อยแล้ว!")
84
+
85
+ from sklearn.metrics import classification_report, confusion_matrix
86
+ import matplotlib.pyplot as plt
87
+ import seaborn as sns
88
+ import numpy as np
89
+
90
+ # 1. พยากรณ์ผลบนชุด Testing Data
91
+ test_gen.reset()
92
+ y_pred_prob = model.predict(test_gen, verbose=1)
93
+ y_pred = np.argmax(y_pred_prob, axis=1)
94
+ y_true = test_gen.classes
95
+ class_labels = list(test_gen.class_indices.keys())
96
+
97
+ # 2. พิมพ์รายงาน Classification Report (Precision, Recall, F1-score)
98
+ print("\n================ Classification Report ================")
99
+ print(classification_report(y_true, y_pred, target_names=class_labels))
100
+
101
+ # 3. วาดกราฟ Confusion Matrix
102
+ cm = confusion_matrix(y_true, y_pred)
103
+ plt.figure(figsize=(8, 6))
104
+ sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
105
+ xticklabels=class_labels, yticklabels=class_labels)
106
+ plt.title('Fine-Tuned EfficientNetB0 - Confusion Matrix')
107
+ plt.xlabel('Predicted Label')
108
+ plt.ylabel('True Label')
109
+ plt.show()
110
+
111
+ # พล็อต กราฟ Loss & Accuracy
112
+ acc = history.history['accuracy']
113
+ val_acc = history.history['val_accuracy']
114
+ loss = history.history['loss']
115
+ val_loss = history.history['val_loss']
116
+ epochs_range = range(len(acc))
117
+
118
+ plt.figure(figsize=(12, 5))
119
+ plt.subplot(1, 2, 1)
120
+ plt.plot(epochs_range, acc, label='Training Accuracy')
121
+ plt.plot(epochs_range, val_acc, label='Validation/Test Accuracy')
122
+ plt.legend(loc='lower right')
123
+ plt.title('Training and Validation Accuracy')
124
+
125
+ plt.subplot(1, 2, 2)
126
+ plt.plot(epochs_range, loss, label='Training Loss')
127
+ plt.plot(epochs_range, val_loss, label='Validation/Test Loss')
128
+ plt.legend(loc='upper right')
129
+ plt.title('Training and Validation Loss')
130
+ plt.show()
131
+