DariaKomarik commited on
Commit
f760bb4
·
verified ·
1 Parent(s): ba3618b

Upload train_last.py

Browse files
Files changed (1) hide show
  1. train_last.py +266 -0
train_last.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import seaborn as sns
5
+ from sklearn.model_selection import train_test_split
6
+ from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, roc_curve, auc, classification_report
7
+ import tensorflow as tf
8
+ from tensorflow.keras import Sequential
9
+ from tensorflow.keras.layers import Conv2D, BatchNormalization, Dropout, Flatten, Dense, Input
10
+ from tensorflow.keras.preprocessing.image import ImageDataGenerator
11
+ from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping
12
+ from tensorflow.keras.optimizers import SGD
13
+ from tensorflow.keras.utils import to_categorical
14
+
15
+ # Фиксация случайных seed для воспроизводимости
16
+ def set_seeds(seed=42):
17
+ np.random.seed(seed)
18
+ tf.random.set_seed(seed)
19
+ set_seeds(42)
20
+
21
+ # ------------------- 1. Загрузка и балансировка -------------------
22
+ df_esp = pd.read_csv('dataset_clean_esp.csv')
23
+ df_power = pd.read_csv('dataset_clean_transistor.csv')
24
+
25
+ df_esp['label'] = 'ESP32'
26
+ df_power['label'] = 'TRANSISTOR'
27
+
28
+ df = pd.concat([df_esp, df_power], ignore_index=True)
29
+ print("Распределение до балансировки:\n", df['label'].value_counts())
30
+
31
+ min_count = min(df['label'].value_counts())
32
+ df_balanced = pd.concat([
33
+ df[df['label'] == 'ESP32'].sample(min_count, random_state=42),
34
+ df[df['label'] == 'TRANSISTOR'].sample(min_count, random_state=42)
35
+ ])
36
+ print("После балансировки:\n", df_balanced['label'].value_counts())
37
+
38
+ # ------------------- 2. Признаки, фильтрация, нормализация -------------------
39
+ dist_cols = [f'z{i}' for i in range(64)]
40
+ df_balanced = df_balanced[(df_balanced[dist_cols] < 0.375).all(axis=1)]
41
+
42
+ X = df_balanced[dist_cols].values.reshape(-1, 8, 8, 1).astype('float32')
43
+ y = df_balanced['label'].values
44
+ print(f"X range: {X.min():.3f} - {X.max():.3f}")
45
+
46
+ # ------------------- 3. One-hot encoding -------------------
47
+ y_binary = (y == 'TRANSISTOR').astype(int)
48
+ y_cat = to_categorical(y_binary, num_classes=2)
49
+
50
+ # ------------------- 4. Разделение -------------------
51
+ X_train, X_temp, y_train, y_temp = train_test_split(X, y_cat, test_size=0.3, random_state=42, stratify=y_binary)
52
+ X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42, stratify=np.argmax(y_temp, axis=1))
53
+ print(f"Train: {X_train.shape}, Val: {X_val.shape}, Test: {X_test.shape}")
54
+
55
+ # ------------------- 5. Аугментация -------------------
56
+ datagen = ImageDataGenerator(
57
+ rotation_range=5,
58
+ width_shift_range=0.05,
59
+ height_shift_range=0.05,
60
+ horizontal_flip=True,
61
+ fill_mode='nearest'
62
+ )
63
+ datagen.fit(X_train)
64
+
65
+ # ------------------- 6. Модель (ВАША ОРИГИНАЛЬНАЯ) -------------------
66
+ model = Sequential([
67
+ Input(shape=(8,8,1)),
68
+ Conv2D(3, (3,3), padding='same', activation='relu'),
69
+ BatchNormalization(),
70
+ Dropout(0.2),
71
+ Conv2D(4, (3,3), padding='valid', activation='relu'),
72
+ BatchNormalization(),
73
+ Dropout(0.2),
74
+ Flatten(),
75
+ Dense(16, activation='relu'),
76
+ Dropout(0.3),
77
+ Dense(2, activation='softmax')
78
+ ])
79
+
80
+ model.compile(
81
+ optimizer=SGD(learning_rate=0.0005, momentum=0.95, nesterov=True),
82
+ loss='categorical_crossentropy',
83
+ metrics=['accuracy']
84
+ )
85
+ model.summary()
86
+
87
+ # ------------------- 7. Callbacks -------------------
88
+ reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=10, min_lr=1e-6, verbose=1)
89
+ early_stop = EarlyStopping(monitor='val_loss', patience=25, restore_best_weights=True, verbose=1)
90
+
91
+ # ------------------- 8. Обучение -------------------
92
+ history = model.fit(
93
+ datagen.flow(X_train, y_train, batch_size=32),
94
+ validation_data=(X_val, y_val),
95
+ epochs=100,
96
+ callbacks=[reduce_lr, early_stop],
97
+ verbose=1
98
+ )
99
+
100
+ # ------------------- 9. Оценка -------------------
101
+ test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)
102
+ print(f"\nTest accuracy: {test_acc:.4f}")
103
+
104
+ # ============================================================================
105
+ # 10. ГРАФИКИ (КАЖДЫЙ ОТДЕЛЬНО, ОРИГИНАЛЬНЫЕ МЕТРИКИ)
106
+ # ============================================================================
107
+
108
+ # График 1: Accuracy
109
+ plt.figure(figsize=(10, 6))
110
+ plt.plot(history.history['accuracy'], 'b-', linewidth=2, label='Train accuracy')
111
+ plt.plot(history.history['val_accuracy'], 'orange', linewidth=2, label='Validation accuracy')
112
+ plt.title('Model Accuracy', fontsize=16, fontweight='bold')
113
+ plt.xlabel('Epoch', fontsize=12)
114
+ plt.ylabel('Accuracy', fontsize=12)
115
+ plt.legend(loc='lower right', fontsize=11)
116
+ plt.grid(True, alpha=0.3)
117
+ plt.ylim(0, 1)
118
+ plt.tight_layout()
119
+ plt.savefig('accuracy_plot.png', dpi=150, bbox_inches='tight')
120
+ plt.show()
121
+
122
+ # График 2: Loss
123
+ plt.figure(figsize=(10, 6))
124
+ plt.plot(history.history['loss'], 'b-', linewidth=2, label='Train loss')
125
+ plt.plot(history.history['val_loss'], 'orange', linewidth=2, label='Validation loss')
126
+ plt.title('Model Loss', fontsize=16, fontweight='bold')
127
+ plt.xlabel('Epoch', fontsize=12)
128
+ plt.ylabel('Loss', fontsize=12)
129
+ plt.legend(loc='upper right', fontsize=11)
130
+ plt.grid(True, alpha=0.3)
131
+ plt.tight_layout()
132
+ plt.savefig('loss_plot.png', dpi=150, bbox_inches='tight')
133
+ plt.show()
134
+
135
+ # График 3: ROC Curve
136
+ y_pred_prob = model.predict(X_test)[:,1]
137
+ y_true = np.argmax(y_test, axis=1)
138
+ fpr, tpr, _ = roc_curve(y_true, y_pred_prob)
139
+ roc_auc = auc(fpr, tpr)
140
+
141
+ plt.figure(figsize=(10, 6))
142
+ plt.plot(fpr, tpr, 'g-', linewidth=2, label=f'ROC curve (AUC = {roc_auc:.3f})')
143
+ plt.plot([0, 1], [0, 1], 'r--', linewidth=1.5, label='Random classifier')
144
+ plt.title('ROC Curve', fontsize=16, fontweight='bold')
145
+ plt.xlabel('False Positive Rate', fontsize=12)
146
+ plt.ylabel('True Positive Rate', fontsize=12)
147
+ plt.legend(loc='lower right', fontsize=11)
148
+ plt.grid(True, alpha=0.3)
149
+ plt.fill_between(fpr, tpr, alpha=0.2, color='green')
150
+ plt.tight_layout()
151
+ plt.savefig('roc_curve.png', dpi=150, bbox_inches='tight')
152
+ plt.show()
153
+
154
+ # График 4: Confusion Matrix
155
+ y_pred = (y_pred_prob > 0.5).astype(int)
156
+ cm = confusion_matrix(y_true, y_pred)
157
+ disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['ESP32', 'TRANSISTOR'])
158
+ fig, ax = plt.subplots(figsize=(7, 6))
159
+ disp.plot(cmap='Blues', values_format='d', ax=ax)
160
+ plt.title('Confusion Matrix', fontsize=16, fontweight='bold', pad=15)
161
+ plt.tight_layout()
162
+ plt.savefig('confusion_matrix.png', dpi=150, bbox_inches='tight')
163
+ plt.show()
164
+
165
+ # ------------------- 11. Classification Report -------------------
166
+ print("\n" + "="*60)
167
+ print("CLASSIFICATION REPORT")
168
+ print("="*60)
169
+ print(classification_report(y_true, y_pred, target_names=['ESP32', 'TRANSISTOR']))
170
+
171
+ # ============================================================================
172
+ # 12. ТЕПЛОВЫЕ КАРТЫ (ГОРИЗОНТАЛЬНО: 2 ESP32 + 2 TRANSISTOR)
173
+ # ============================================================================
174
+ esp_idx = np.where(np.argmax(y_cat, axis=1) == 0)[0]
175
+ tr_idx = np.where(np.argmax(y_cat, axis=1) == 1)[0]
176
+
177
+ # Перемешиваем для разнообразия
178
+ np.random.seed(42)
179
+ esp_shuffled = np.random.permutation(esp_idx)
180
+ tr_shuffled = np.random.permutation(tr_idx)
181
+
182
+ n_esp = 2
183
+ n_tr = 2
184
+ n_heatmaps = 10
185
+
186
+ vmin_global, vmax_global = 0.0, 0.35
187
+
188
+ for hm in range(n_heatmaps):
189
+ start_esp = (hm * n_esp) % len(esp_shuffled)
190
+ start_tr = (hm * n_tr) % len(tr_shuffled)
191
+
192
+ current_esp_idx = esp_shuffled[start_esp:start_esp + n_esp]
193
+ current_tr_idx = tr_shuffled[start_tr:start_tr + n_tr]
194
+
195
+ # Добираем если не хватает
196
+ if len(current_esp_idx) < n_esp:
197
+ needed = n_esp - len(current_esp_idx)
198
+ current_esp_idx = np.concatenate([current_esp_idx, esp_shuffled[:needed]])
199
+ if len(current_tr_idx) < n_tr:
200
+ needed = n_tr - len(current_tr_idx)
201
+ current_tr_idx = np.concatenate([current_tr_idx, tr_shuffled[:needed]])
202
+
203
+ # ГОРИЗОНТАЛЬНЫЙ РИСУНОК: 1 строка, 4 столбца
204
+ fig, axes = plt.subplots(1, 4, figsize=(12, 4))
205
+ fig.suptitle('Depth Maps', fontsize=14, fontweight='bold', y=1.02)
206
+
207
+ # ESP32 пример 1
208
+ ax = axes[0]
209
+ sample = X[current_esp_idx[0]].reshape(8, 8)
210
+ im = ax.imshow(sample, cmap='plasma', vmin=vmin_global, vmax=vmax_global)
211
+ ax.set_title('ESP32 #1', fontsize=11, fontweight='bold')
212
+ ax.axis('off')
213
+
214
+ # ESP32 пример 2
215
+ ax = axes[1]
216
+ sample = X[current_esp_idx[1]].reshape(8, 8)
217
+ ax.imshow(sample, cmap='plasma', vmin=vmin_global, vmax=vmax_global)
218
+ ax.set_title('ESP32 #2', fontsize=11, fontweight='bold')
219
+ ax.axis('off')
220
+
221
+ # TRANSISTOR пример 1
222
+ ax = axes[2]
223
+ sample = X[current_tr_idx[0]].reshape(8, 8)
224
+ ax.imshow(sample, cmap='plasma', vmin=vmin_global, vmax=vmax_global)
225
+ ax.set_title('TRANSISTOR #1', fontsize=11, fontweight='bold')
226
+ ax.axis('off')
227
+
228
+ # TRANSISTOR пример 2
229
+ ax = axes[3]
230
+ sample = X[current_tr_idx[1]].reshape(8, 8)
231
+ ax.imshow(sample, cmap='plasma', vmin=vmin_global, vmax=vmax_global)
232
+ ax.set_title('TRANSISTOR #2', fontsize=11, fontweight='bold')
233
+ ax.axis('off')
234
+
235
+ # Colorbar справа
236
+ cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.7])
237
+ cbar = fig.colorbar(im, cax=cbar_ax)
238
+ cbar.set_label('Normalized distance', fontsize=10)
239
+
240
+ plt.tight_layout(rect=[0, 0, 0.9, 1])
241
+ plt.savefig(f'heatmap_set_{hm+1:02d}.png', dpi=150, bbox_inches='tight')
242
+ plt.close()
243
+ print(f"✅ Сохранена тепловая карта {hm+1}/{n_heatmaps}")
244
+
245
+ print(f"\n✅ Сохранено {n_heatmaps} тепловых карт (heatmap_set_01.png ... heatmap_set_10.png)")
246
+
247
+ # ------------------- 13. Сохранение модели -------------------
248
+ converter = tf.lite.TFLiteConverter.from_keras_model(model)
249
+ tflite_model = converter.convert()
250
+ with open('model_quantized.tflite', 'wb') as f:
251
+ f.write(tflite_model)
252
+ print("Модель сохранена как model_quantized.tflite")
253
+
254
+ model.save('model_final.h5')
255
+ print("Модель сохранена как model_final.h5")
256
+
257
+ # ------------------- 14. Итоговая статистика -------------------
258
+ print("\n" + "="*60)
259
+ print("FINAL TRAINING SUMMARY")
260
+ print("="*60)
261
+ print(f"Test accuracy: {test_acc:.4f} ({test_acc*100:.2f}%)")
262
+ print(f"ROC AUC: {roc_auc:.4f}")
263
+ print(f"Best validation accuracy: {max(history.history['val_accuracy']):.4f}")
264
+ print(f"Best validation loss: {min(history.history['val_loss']):.6f}")
265
+ print(f"Training epochs done: {len(history.history['accuracy'])}")
266
+ print("="*60)