diff --git a/02-intro_rna/03-keras-tf_playground-cercle.py b/02-intro_rna/03-keras-tf_playground-cercle.py index e4a9061..1dbdc68 100644 --- a/02-intro_rna/03-keras-tf_playground-cercle.py +++ b/02-intro_rna/03-keras-tf_playground-cercle.py @@ -1,6 +1,8 @@ import os, time import numpy as np import matplotlib.pyplot as plt +from matplotlib import cm +from matplotlib.colors import ListedColormap, LinearSegmentedColormap import tensorflow as tf from tensorflow import keras @@ -68,36 +70,74 @@ donnees_ax = fig.add_subplot(133) # Observations : x1,x2 et cibles : y # Observations ############################################################################### -# Observations d'apprentissage, de validation et de test -vetement = keras.datasets.fashion_mnist # Jeu de données Fashion MNIST -(X, y), (X_test, y_test) = vetement.load_data() -X_train, y_train = X[5000:]/255.0 , y[5000:] -X_valid, y_valid = X[:5000]/255.0 , y[:5000] -classes = ["Tshirt", "Pantalon", "Pull", "Robe", "Manteau", "Sandale", "Chemise", "Basket", "Sac", "Bottine"] +# Observations d'apprentissage +m = 1000 # Nombre d'observations +bg = 1 # Quantité du bruit gaussien # FIXME : pas en place +rayon = 2.5 # Rayon de séparation +marge = 0.25 +x1 = np.empty(m) +x2 = np.empty(m) +y = np.empty(m) + +# Go ! +j=0 +for i in range (round(m/2)-1): + + # Extérieur du cercle + r = np.random.uniform(rayon+marge, 5) + angle = np.random.uniform(0, 2* np.pi) + x1[j] = r * np.sin(angle) + x2[j] = r * np.cos(angle) + y[j] = 0 + j+=1 + + # Intérieur du cercle + r = np.random.uniform(0, rayon-marge) + angle = np.random.uniform(0, 2* np.pi) + x1[j] = r * np.sin(angle) + x2[j] = r * np.cos(angle) + y[j] = 1 + j+=1 + +# Split en observations d'entrainement et de validation +test_size=0.1 # Ratio du lot de test +m_train = int(np.round(m*(1-test_size))) +x1_train, x2_train, y_train = x1[:m_train], x2[:m_train], y[:m_train] # Jeu d'entrainement +x1_valid, x2_valid, y_valid = x1[m_train:], x2[m_train:], y[m_train:] # Jeu de validation +X_train = np.c_[x1_train, x2_train] +X_valid = np.c_[x1_valid, x2_valid] + +# Plots +donnees_ax.plot(x1_train[y_train==1], x2_train[y_train==1], "o", markerfacecolor="tab:blue", markeredgecolor='white', markeredgewidth=0.75) +donnees_ax.plot(x1_train[y_train==0], x2_train[y_train==0], "o" , markerfacecolor="tab:orange", markeredgecolor='white', markeredgewidth=0.75) +donnees_ax.plot(x1_valid[y_valid==1], x2_valid[y_valid==1], "o", markerfacecolor='tab:blue', markeredgecolor='black') +donnees_ax.plot(x1_valid[y_valid==0], x2_valid[y_valid==0], "o", markerfacecolor='tab:orange', markeredgecolor='black') + +# Nouvelles observations +m_new = 100 # Résolution par axes +x1_new=np.linspace(-6, 6, m_new).reshape(-1, 1) +x2_new=np.linspace(-6, 6, m_new).reshape(-1, 1) +x1_new_mg, x2_new_mg = np.meshgrid(x1_new, x2_new) +X_new = np.c_[x1_new_mg.ravel(), x2_new_mg.ravel()] ############################################################################### # Phase d'apprentissage ############################################################################### -n = 30 # Nombre d'itérations (valeur par défaut : 30 , hyperparamètre) +n = 200 # Nombre d'itérations (valeur par défaut : 200 , hyperparamètre) eta = 0.01 # Taux d'appentissage (valeur par défaut dans Keras : 0.01, hyperparamètre) lot=32 # Taille de lot (valeur par défaut dans Keras: 32 , hyperparamètre) -perte="sparse_categorical_crossentropy" # Type de perte (hyperparamètre) -#perte="mse" # Type de perte (hyperparamètre) + +# perte="sparse_categorical_crossentropy" # Type de perte (hyperparamètre) +perte="mse" # Type de perte (hyperparamètre) +# perte='mean_absolute_error' keras.backend.clear_session() -# np.random.seed(42) -# tf.random.set_seed(42) - model = keras.models.Sequential() # Modèle de reseau de neurones -model.add(keras.layers.Flatten(input_shape=[28, 28])) # Couche d'entrée : mise à plat des données d'entrée -> 1 node / pixel soit 784 (28x28) -model.add(keras.layers.Dense(300, activation="relu")) # Couche 1 : 300 nodes -# model.add(keras.layers.Dense(300, activation="relu")) # Couche 2 : 300 nodes -> passage de 100 à 300 -# model.add(keras.layers.Dense(300, activation="relu")) # Couche 3 : 300 nodes -> ajout -model.add(keras.layers.Dense(100, activation="relu")) # Couche 4 : 100 nodes -> ajout -model.add(keras.layers.Dense(10, activation="softmax")) # Couche de sortie : 1 node par classe soit 10 +model.add(keras.layers.Dense(4, input_dim=2, activation="relu")) # Couche 1 : 4 nodes +model.add(keras.layers.Dense(4, activation="relu")) # Couche 2 : 4 nodes +model.add(keras.layers.Dense(1, activation="sigmoid")) # Couche de sortie : 1 node par classe -# model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) optimiseur=keras.optimizers.SGD(learning_rate= eta) model.compile(loss=perte, optimizer=optimiseur, metrics=["accuracy"]) # Compilation du modèle @@ -107,20 +147,8 @@ apts = model.fit(X_train, y_train, epochs=n, batch_size=lot, validation_data=(X_ # Phase d'inférence ############################################################################### -# X_new=[] -# y_new=[] -# for i in range(8): -# idx = np.random.randint(X_test.shape[0]) # Index aléatoire -# X_new.append(X_test[idx:idx+1]/255.0) -# y_new.append(y_test[idx:idx+1]) - -idx = np.random.randint(X_test.shape[0]-32) # Index aléatoire -print ("\n") -print ("Test sur les images de "+ str(idx) + " à "+ str(idx+32) + " sur un jeu de 10 000 images.") -X_new = X_test[idx:idx+32] -y_new = np.argmax(model.predict(X_new), axis=-1) -y_new_test= y_test[idx:idx+32] -print ("\n") +y_predict=model.predict(X_new) # Prédiction +y_predict_map = y_predict.reshape(x1_new_mg.shape) ############################################################################### # Résultats @@ -140,20 +168,21 @@ apts_ax.plot(apts.epoch, apts.history['loss'], 'b-', label="Perte - entrainement apts_ax.plot(apts.epoch, apts.history['val_loss'], 'r-', label="Perte - validation") apts_ax.plot(apts.epoch, apts.history['accuracy'], 'b:', label="Précision - entrainement") apts_ax.plot(apts.epoch, apts.history['val_accuracy'], 'r:', label="Précision - validation") -apts_ax.set(ylim=(0, 1)) +apts_ax.set(ylim=(-0.05, 1.05)) apts_ax.set_xlabel("Époque") apts_ax.legend() -# Prédictions -for i in range (8): - for j in range (4): - img_ax[j][i].imshow(X_new[i*2+j], cmap="binary", interpolation="nearest") - img_ax[j][i].set_axis_off() - if y_new[i*2+j] == y_new_test[i*2+j]: - img_ax[j][i].set_title(classes[y_new[i*2+j]], fontsize=10) - else: - img_ax[j][i].set_title(classes[y_new[i*2+j]], fontsize=10, color="red") - +# Plot des données +donnees_ax.set_title("Données") +new_colors = ["tab:orange", "white", "tab:blue"] +new_cmap = LinearSegmentedColormap.from_list("mycmap", new_colors) # FIXME : faire un dégradé +cc = donnees_ax.contourf(x1_new_mg, x2_new_mg, y_predict_map, cmap=new_cmap) +donnees_ax.set_xticks([-5,0,5]) +donnees_ax.set_yticks([-5,0,5]) +donnees_ax.set_xlabel(r'$x_1$') +donnees_ax.set_ylabel(r'$x_2$', rotation=0) +donnees_ax.set(xlim=(-5.25, 5.25), ylim=(-5.25, 5.25)) +fig.colorbar(cc, ax=donnees_ax) plt.show() # Performances diff --git a/02-intro_rna/04-keras-tf_playground-xor.py b/02-intro_rna/04-keras-tf_playground-xor.py index 48684d4..b0dc275 100644 --- a/02-intro_rna/04-keras-tf_playground-xor.py +++ b/02-intro_rna/04-keras-tf_playground-xor.py @@ -79,8 +79,8 @@ donnees_ax = fig.add_subplot(133) # Observations : x1,x2 et cibles : y # Observations d'apprentissage m = 1000 # Nombre d'observations bg = 1 # Quantité du bruit gaussien # FIXME : pas en place -x1 = np.random.uniform(-5,5, m) # Liste des observations x1 -x2 = np.random.uniform(-5,5, m) # Liste des observations x2 +x1 = np.random.uniform(-5, 5, m) # Liste des observations x1 +x2 = np.random.uniform(-5, 5, m) # Liste des observations x2 y = np.empty(m) # Liste des observations cible (XOR) marge = 0.15 for i in range (m): @@ -128,7 +128,6 @@ perte="mse" # Type de perte (hyperparamètre) keras.backend.clear_session() model = keras.models.Sequential() # Modèle de reseau de neurones -# model.add(keras.layers.Flatten(input_shape=[1, 1])) # Couche d'entrée model.add(keras.layers.Dense(4, input_dim=2, activation="relu")) # Couche 1 : 4 nodes model.add(keras.layers.Dense(4, activation="relu")) # Couche 2 : 4 nodes model.add(keras.layers.Dense(1, activation="sigmoid")) # Couche de sortie : 1 node par classe @@ -178,7 +177,6 @@ donnees_ax.set_xlabel(r'$x_1$') donnees_ax.set_ylabel(r'$x_2$', rotation=0) donnees_ax.set(xlim=(-5.25, 5.25), ylim=(-5.25, 5.25)) fig.colorbar(cc, ax=donnees_ax) -# donnees_ax.legend() plt.show() # Performances diff --git a/02-intro_rna/README.md b/02-intro_rna/README.md index 7a9dcab..6b48b8b 100644 --- a/02-intro_rna/README.md +++ b/02-intro_rna/README.md @@ -8,6 +8,10 @@ ![capture d'écran](img/02-keras-classificateur_img.png) +### Réseaux de neurones avec Keras - Classificateur : Points en cercle + +![capture d'écran](img/03-keras-tf_playground-cercle.png) + ### Réseaux de neurones avec Keras - Classificateur : Ou exclusif (XOR) ![capture d'écran](img/04-keras-tf_playground-xor.png) diff --git a/02-intro_rna/img/03-keras-tf_playground-cercle.png b/02-intro_rna/img/03-keras-tf_playground-cercle.png new file mode 100644 index 0000000..f8c0301 Binary files /dev/null and b/02-intro_rna/img/03-keras-tf_playground-cercle.png differ