Create SCA.py
Browse files
SCA.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from cnn_model import build_cnn_model
|
| 3 |
+
|
| 4 |
+
# -------------------------
|
| 5 |
+
# Fonction objectif pour SCA
|
| 6 |
+
# -------------------------
|
| 7 |
+
def objective_function(x, X_train, y_train):
|
| 8 |
+
filter1 = int(x[0])
|
| 9 |
+
filter2 = int(x[1])
|
| 10 |
+
filter3 = int(x[2])
|
| 11 |
+
learning_rate = float(x[3])
|
| 12 |
+
dropout = float(x[4])
|
| 13 |
+
|
| 14 |
+
model = build_cnn_model(
|
| 15 |
+
input_shape=(X_train.shape[1], X_train.shape[2]),
|
| 16 |
+
num_classes=y_train.shape[1],
|
| 17 |
+
filter1=filter1,
|
| 18 |
+
filter2=filter2,
|
| 19 |
+
filter3=filter3,
|
| 20 |
+
learning_rate=learning_rate,
|
| 21 |
+
dropout=dropout
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
history = model.fit(
|
| 25 |
+
X_train, y_train,
|
| 26 |
+
validation_split=0.2,
|
| 27 |
+
epochs=3, # rapide pour optimisation
|
| 28 |
+
batch_size=32,
|
| 29 |
+
verbose=0
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
val_acc = history.history['val_accuracy'][-1]
|
| 33 |
+
return 1 - val_acc # minimiser 1 - précision
|
| 34 |
+
|
| 35 |
+
# -------------------------
|
| 36 |
+
# Implémentation simple de SCA
|
| 37 |
+
# -------------------------
|
| 38 |
+
def devsca(objf, lb, ub, dim, N, T, X_train, y_train):
|
| 39 |
+
X = np.random.uniform(0, 1, (N, dim)) * (np.array(ub) - np.array(lb)) + np.array(lb)
|
| 40 |
+
fitness = np.array([objf(ind, X_train, y_train) for ind in X])
|
| 41 |
+
best_idx = np.argmin(fitness)
|
| 42 |
+
best_X = X[best_idx].copy()
|
| 43 |
+
best_fit = fitness[best_idx]
|
| 44 |
+
convergence_curve = []
|
| 45 |
+
|
| 46 |
+
for t in range(T):
|
| 47 |
+
r1 = np.linspace(2, 0, T)[t] # diminue avec le temps
|
| 48 |
+
for i in range(N):
|
| 49 |
+
for j in range(dim):
|
| 50 |
+
r2 = 2 * np.pi * np.random.rand()
|
| 51 |
+
r3 = 2 * np.random.rand()
|
| 52 |
+
r4 = np.random.rand()
|
| 53 |
+
if r4 < 0.5:
|
| 54 |
+
X[i, j] = X[i, j] + r1 * np.sin(r2) * abs(r3 * best_X[j] - X[i, j])
|
| 55 |
+
else:
|
| 56 |
+
X[i, j] = X[i, j] + r1 * np.cos(r2) * abs(r3 * best_X[j] - X[i, j])
|
| 57 |
+
|
| 58 |
+
X[i] = np.clip(X[i], lb, ub)
|
| 59 |
+
|
| 60 |
+
fit = objf(X[i], X_train, y_train)
|
| 61 |
+
if fit < best_fit:
|
| 62 |
+
best_fit = fit
|
| 63 |
+
best_X = X[i].copy()
|
| 64 |
+
|
| 65 |
+
convergence_curve.append(best_fit)
|
| 66 |
+
print(f"Iteration {t+1}/{T} | Best Accuracy: {1 - best_fit:.4f}")
|
| 67 |
+
|
| 68 |
+
return best_X, best_fit, convergence_curve
|