DariaKomarik's picture
Update train_last.py
d5c0b6d verified
Raw
History Blame Contribute Delete
10.5 kB
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, roc_curve, auc, classification_report
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, BatchNormalization, Dropout, Flatten, Dense, Input
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
# Фиксация случайных seed для воспроизводимости
def set_seeds(seed=42):
np.random.seed(seed)
tf.random.set_seed(seed)
set_seeds(42)
# ------------------- 1. Загрузка и балансировка -------------------
df_esp = pd.read_csv('dataset_clean_esp.csv')
df_power = pd.read_csv('dataset_clean_transistor.csv')
df_esp['label'] = 'ESP32'
df_power['label'] = 'TRANSISTOR'
df = pd.concat([df_esp, df_power], ignore_index=True)
print("Распределение до балансировки:\n", df['label'].value_counts())
min_count = min(df['label'].value_counts())
df_balanced = pd.concat([
df[df['label'] == 'ESP32'].sample(min_count, random_state=42),
df[df['label'] == 'TRANSISTOR'].sample(min_count, random_state=42)
])
print("После балансировки:\n", df_balanced['label'].value_counts())
# ------------------- 2. Признаки, фильтрация, нормализация -------------------
dist_cols = [f'z{i}' for i in range(64)]
df_balanced = df_balanced[(df_balanced[dist_cols] < 0.375).all(axis=1)]
X = df_balanced[dist_cols].values.reshape(-1, 8, 8, 1).astype('float32')
y = df_balanced['label'].values
print(f"X range: {X.min():.3f} - {X.max():.3f}")
# ------------------- 3. One-hot encoding -------------------
y_binary = (y == 'TRANSISTOR').astype(int)
y_cat = to_categorical(y_binary, num_classes=2)
# ------------------- 4. Разделение -------------------
X_train, X_temp, y_train, y_temp = train_test_split(X, y_cat, test_size=0.3, random_state=42, stratify=y_binary)
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))
print(f"Train: {X_train.shape}, Val: {X_val.shape}, Test: {X_test.shape}")
# ------------------- 5. Аугментация -------------------
datagen = ImageDataGenerator(
rotation_range=5,
width_shift_range=0.05,
height_shift_range=0.05,
horizontal_flip=True,
fill_mode='nearest'
)
datagen.fit(X_train)
# ------------------- 6. Модель -------------------
model = Sequential([
Input(shape=(8,8,1)),
Conv2D(3, (3,3), padding='same', activation='relu'),
BatchNormalization(),
Dropout(0.2),
Conv2D(4, (3,3), padding='valid', activation='relu'),
BatchNormalization(),
Dropout(0.2),
Flatten(),
Dense(16, activation='relu'),
Dropout(0.3),
Dense(2, activation='softmax')
])
model.compile(
optimizer=SGD(learning_rate=0.0005, momentum=0.95, nesterov=True),
loss='categorical_crossentropy',
metrics=['accuracy']
)
model.summary()
# ------------------- 7. Callbacks -------------------
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=10, min_lr=1e-6, verbose=1)
early_stop = EarlyStopping(monitor='val_loss', patience=25, restore_best_weights=True, verbose=1)
# ------------------- 8. Обучение -------------------
history = model.fit(
datagen.flow(X_train, y_train, batch_size=32),
validation_data=(X_val, y_val),
epochs=100,
callbacks=[reduce_lr, early_stop],
verbose=1
)
# ------------------- 9. Оценка -------------------
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)
print(f"\nTest accuracy: {test_acc:.4f}")
# ============================================================================
# 10. ГРАФИКИ (КАЖДЫЙ ОТДЕЛЬНО, МЕТРИКИ)
# ============================================================================
# График 1: Accuracy
plt.figure(figsize=(10, 6))
plt.plot(history.history['accuracy'], 'b-', linewidth=2, label='Train accuracy')
plt.plot(history.history['val_accuracy'], 'orange', linewidth=2, label='Validation accuracy')
plt.title('Model Accuracy', fontsize=16, fontweight='bold')
plt.xlabel('Epoch', fontsize=12)
plt.ylabel('Accuracy', fontsize=12)
plt.legend(loc='lower right', fontsize=11)
plt.grid(True, alpha=0.3)
plt.ylim(0, 1)
plt.tight_layout()
plt.savefig('accuracy_plot.png', dpi=150, bbox_inches='tight')
plt.show()
# График 2: Loss
plt.figure(figsize=(10, 6))
plt.plot(history.history['loss'], 'b-', linewidth=2, label='Train loss')
plt.plot(history.history['val_loss'], 'orange', linewidth=2, label='Validation loss')
plt.title('Model Loss', fontsize=16, fontweight='bold')
plt.xlabel('Epoch', fontsize=12)
plt.ylabel('Loss', fontsize=12)
plt.legend(loc='upper right', fontsize=11)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('loss_plot.png', dpi=150, bbox_inches='tight')
plt.show()
# График 3: ROC Curve
y_pred_prob = model.predict(X_test)[:,1]
y_true = np.argmax(y_test, axis=1)
fpr, tpr, _ = roc_curve(y_true, y_pred_prob)
roc_auc = auc(fpr, tpr)
plt.figure(figsize=(10, 6))
plt.plot(fpr, tpr, 'g-', linewidth=2, label=f'ROC curve (AUC = {roc_auc:.3f})')
plt.plot([0, 1], [0, 1], 'r--', linewidth=1.5, label='Random classifier')
plt.title('ROC Curve', fontsize=16, fontweight='bold')
plt.xlabel('False Positive Rate', fontsize=12)
plt.ylabel('True Positive Rate', fontsize=12)
plt.legend(loc='lower right', fontsize=11)
plt.grid(True, alpha=0.3)
plt.fill_between(fpr, tpr, alpha=0.2, color='green')
plt.tight_layout()
plt.savefig('roc_curve.png', dpi=150, bbox_inches='tight')
plt.show()
# График 4: Confusion Matrix
y_pred = (y_pred_prob > 0.5).astype(int)
cm = confusion_matrix(y_true, y_pred)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['ESP32', 'TRANSISTOR'])
fig, ax = plt.subplots(figsize=(7, 6))
disp.plot(cmap='Blues', values_format='d', ax=ax)
plt.title('Confusion Matrix', fontsize=16, fontweight='bold', pad=15)
plt.tight_layout()
plt.savefig('confusion_matrix.png', dpi=150, bbox_inches='tight')
plt.show()
# ------------------- 11. Classification Report -------------------
print("\n" + "="*60)
print("CLASSIFICATION REPORT")
print("="*60)
print(classification_report(y_true, y_pred, target_names=['ESP32', 'TRANSISTOR']))
# ============================================================================
# 12. ТЕПЛОВЫЕ КАРТЫ (ГОРИЗОНТАЛЬНО: 2 ESP32 + 2 TRANSISTOR)
# ============================================================================
esp_idx = np.where(np.argmax(y_cat, axis=1) == 0)[0]
tr_idx = np.where(np.argmax(y_cat, axis=1) == 1)[0]
# Перемешиваем для разнообразия
np.random.seed(42)
esp_shuffled = np.random.permutation(esp_idx)
tr_shuffled = np.random.permutation(tr_idx)
n_esp = 2
n_tr = 2
n_heatmaps = 10
vmin_global, vmax_global = 0.0, 0.35
for hm in range(n_heatmaps):
start_esp = (hm * n_esp) % len(esp_shuffled)
start_tr = (hm * n_tr) % len(tr_shuffled)
current_esp_idx = esp_shuffled[start_esp:start_esp + n_esp]
current_tr_idx = tr_shuffled[start_tr:start_tr + n_tr]
# Добираем если не хватает
if len(current_esp_idx) < n_esp:
needed = n_esp - len(current_esp_idx)
current_esp_idx = np.concatenate([current_esp_idx, esp_shuffled[:needed]])
if len(current_tr_idx) < n_tr:
needed = n_tr - len(current_tr_idx)
current_tr_idx = np.concatenate([current_tr_idx, tr_shuffled[:needed]])
# ГОРИЗОНТАЛЬНЫЙ РИСУНОК: 1 строка, 4 столбца
fig, axes = plt.subplots(1, 4, figsize=(12, 4))
fig.suptitle('Depth Maps', fontsize=14, fontweight='bold', y=1.02)
# ESP32 пример 1
ax = axes[0]
sample = X[current_esp_idx[0]].reshape(8, 8)
im = ax.imshow(sample, cmap='plasma', vmin=vmin_global, vmax=vmax_global)
ax.set_title('ESP32 #1', fontsize=11, fontweight='bold')
ax.axis('off')
# ESP32 пример 2
ax = axes[1]
sample = X[current_esp_idx[1]].reshape(8, 8)
ax.imshow(sample, cmap='plasma', vmin=vmin_global, vmax=vmax_global)
ax.set_title('ESP32 #2', fontsize=11, fontweight='bold')
ax.axis('off')
# TRANSISTOR пример 1
ax = axes[2]
sample = X[current_tr_idx[0]].reshape(8, 8)
ax.imshow(sample, cmap='plasma', vmin=vmin_global, vmax=vmax_global)
ax.set_title('TRANSISTOR #1', fontsize=11, fontweight='bold')
ax.axis('off')
# TRANSISTOR пример 2
ax = axes[3]
sample = X[current_tr_idx[1]].reshape(8, 8)
ax.imshow(sample, cmap='plasma', vmin=vmin_global, vmax=vmax_global)
ax.set_title('TRANSISTOR #2', fontsize=11, fontweight='bold')
ax.axis('off')
# Colorbar справа
cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.7])
cbar = fig.colorbar(im, cax=cbar_ax)
cbar.set_label('Normalized distance', fontsize=10)
plt.tight_layout(rect=[0, 0, 0.9, 1])
plt.savefig(f'heatmap_set_{hm+1:02d}.png', dpi=150, bbox_inches='tight')
plt.close()
print(f"✅ Сохранена тепловая карта {hm+1}/{n_heatmaps}")
print(f"\n✅ Сохранено {n_heatmaps} тепловых карт (heatmap_set_01.png ... heatmap_set_10.png)")
# ------------------- 13. Сохранение модели -------------------
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open('model_quantized.tflite', 'wb') as f:
f.write(tflite_model)
print("Модель сохранена как model_quantized.tflite")
model.save('model_final.h5')
print("Модель сохранена как model_final.h5")
# ------------------- 14. Итоговая статистика -------------------
print("\n" + "="*60)
print("FINAL TRAINING SUMMARY")
print("="*60)
print(f"Test accuracy: {test_acc:.4f} ({test_acc*100:.2f}%)")
print(f"ROC AUC: {roc_auc:.4f}")
print(f"Best validation accuracy: {max(history.history['val_accuracy']):.4f}")
print(f"Best validation loss: {min(history.history['val_loss']):.6f}")
print(f"Training epochs done: {len(history.history['accuracy'])}")
print("="*60)