diff --git a/01-fondamentaux/03-descente_gradient_stochastique.py b/01-fondamentaux/03-descente_gradient_stochastique.py index f1fd85e..3531c39 100644 --- a/01-fondamentaux/03-descente_gradient_stochastique.py +++ b/01-fondamentaux/03-descente_gradient_stochastique.py @@ -1,4 +1,3 @@ - import time import numpy as np import sklearn diff --git a/03-vision/01-digit-prepa_data.py b/03-vision/01-digit-prepa_data.py index 8e6858a..3465fbd 100644 --- a/03-vision/01-digit-prepa_data.py +++ b/03-vision/01-digit-prepa_data.py @@ -55,7 +55,7 @@ t_debut = time.time() # Init des plots fig = plt.figure(layout="constrained", figsize=(20, 7)) fig.suptitle(" Vision par ordinateur - Reconnaissance de digit - Analyse et préparation des données") -img_ax = fig.subplots(10, 30) +img_ax = fig.subplots(10, 40) ############################################################################### # Observations @@ -71,146 +71,26 @@ X_train, y_train = X[5000:]/255.0 , y[5000:] X_valid, y_valid = X[:5000]/255.0 , y[:5000] classes = [0,1,2,3,4,5,6,7,8,9] -# ############################################################################### -# # Phase d'apprentissage -# ############################################################################### - -# n = 2 # Nombre d'itérations (valeur par défaut : 30 , 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) - -# keras.backend.clear_session() -# 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(100, activation="relu")) # Couche 2 : 100 nodes -> ajout -# model.add(keras.layers.Dense(10, activation="softmax")) # Couche de sortie : 1 node par classe soit 10 - -# optimiseur=keras.optimizers.SGD(learning_rate= eta) -# model.compile(loss=perte, optimizer=optimiseur, metrics=["accuracy"]) # Compilation du modèle - -# apts = model.fit(X_train, y_train, epochs=n, batch_size=lot, validation_data=(X_valid, y_valid)) # Entrainement - ############################################################################### -# Phase d'inférence +# Classement des images avec l'étiquette ############################################################################### print ("\n") -print ("Test sur les 80 images différentes sur un jeu de 10 000 images.") +print ("Recherche de 400 images sur le jeu de test (10 000 images).") +# X_new_unique = np.unique(X_test, axis=0, return_index=True) -# X_new = np.empty([80, 28, 28]) -# y_new_test = np.empty(80) -# for i_new in range(80): -# # print ("i_new ", i_new ) +for ligne in range (10): # Ligne + i_first=-1 + for colonne in range (40): # Colonne + for i in range (i_first+1, X_test.shape[0]): + if y_test[i] == ligne: + # if y_test[i] == 2: + img_ax[ligne][colonne].imshow(X_test[i], cmap="binary", interpolation="nearest") + img_ax[ligne][colonne].set_axis_off() + img_ax[ligne][colonne].set_title(str(i), fontsize=10) + i_first=i + break -# # Boucle de remplissage -# deja_present=True -# while deja_present == True: -# idx = np.random.randint(X_test.shape[0]) # Index aléatoire -# # print ("idx ", idx ) -# X_idx = X_test[idx] - -# # Comparaison de chaque images présentes avec image idx -# deja_present_unitaire=[] -# for i_img in range (80): -# # print ("i_img ", i_img ) -# deja_present_unitaire.append(True) -# for j in range (28): -# for k in range (28): -# if X_new[i_img][j][k] != X_idx[j][k]: -# deja_present_unitaire[i_img]=False - -# # Test sur l'ensemble des images -# deja_present=False -# for i_img in range (80): -# if deja_present_unitaire[i_img]==True: -# deja_present = True - -# # Ajout de la nouvelle image idx -# X_new[i_new]=X_test[idx] -# y_new_test[i_new] = y_test[idx] -# print ("ajout ", i_new, idx) - -# FIXME : ne marche pas -> à faire à la main - -# (X_train, Y_train), (X_test, Y_test) = tf.keras.datasets.mnist.load_data() -# train_filter = np.unique(Y_train, return_index=True) -# X_train, Y_train = X_train[train_filter[1:]], Y_train[train_filter[1:]] - -X_new_unique = np.unique(X_test, axis=0, return_index=True) - -# X_new = np.empty([80, 28, 28]) -# y_new_test = np.empty(80) -# new_unique = random.sample(list(X_new_unique_i), 80) -# for i in range(80): -# X_new[i]=X_test[new_unique[i]] -# y_new_test[i] = y_test[new_unique[i]] - -# X_new_idx = np.empty(80) -# for i in range(80): - -# # Vérification que l'index aléatoire n'a pas été -# idx_unique= False -# while idx_unique ==False : -# idx_unique= True -# idx = np.random.randint(len(test_filter[1])) # Index aléatoire -# for j in range (80): -# if X_new_idx[j] == idx: -# idx_unique= False - - -# X_new[i]=X_test[idx] -# y_new_test[i] = y_test[idx] - -# y_new = np.argmax(model.predict(X_new), axis=-1) print ("\n") -# ############################################################################### -# # Résultats -# ############################################################################### - -# # Modèle -# model_ax.set_title("Modèle") -# keras.utils.plot_model(model, "model.png", show_shapes=True) -# model_img=plt.imread("model.png") -# model_ax.imshow(model_img) -# model_ax.set_axis_off() -# os.remove("model.png") # Supression du fichier temporaire - -# # Courbes d'apprentissage -# apts_ax.set_title("Courbes d'apprentissage") -# 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_xlabel("Époque") -# apts_ax.legend() - -# # Prédictions -# for i in range (10): -# for j in range (8): -# 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") - -# Prédictions -k=0 -for i in range (10): # Ligne - for j in range (30): # Colonne - img_ax[i][j].imshow(X_test[k], cmap="binary", interpolation="nearest") - img_ax[i][j].set_axis_off() - img_ax[i][j].set_title(str(k)+" : "+str(y_test[k]), fontsize=10) - k+=1 - plt.show() - - -# Performances -print ("Temps total : "+str(time.time()-t_debut)) diff --git a/03-vision/02-digit-simple.py b/03-vision/02-digit-simple.py index bf9a642..4da16b7 100644 --- a/03-vision/02-digit-simple.py +++ b/03-vision/02-digit-simple.py @@ -58,7 +58,7 @@ fig.suptitle("Vision par ordinateur - Reconnaissance de digit par réseaux de ne subfigs = fig.subfigures(1, 3) model_ax = subfigs[0].subplots(1, 1) apts_ax = subfigs[1].subplots(1, 1) -img_ax = subfigs[2].subplots(8, 10) +img_ax = subfigs[2].subplots(10, 15) ############################################################################### # Observations @@ -66,8 +66,8 @@ img_ax = subfigs[2].subplots(8, 10) # Observations d'apprentissage, de validation et de test -chiffre = keras.datasets.mnist # Jeu de données MNIST (digit) -(X, y), (X_test, y_test) = chiffre.load_data() +mnist = keras.datasets.mnist # Jeu de données MNIST (digit) +(X, y), (X_test, y_test) = mnist.load_data() X_train, y_train = X[5000:]/255.0 , y[5000:] X_valid, y_valid = X[:5000]/255.0 , y[:5000] @@ -98,16 +98,57 @@ apts = model.fit(X_train, y_train, epochs=n, batch_size=lot, validation_data=(X_ # Phase d'inférence ############################################################################### +# Inférence sur la totalité du jeu de test print ("\n") -print ("Test sur les 80 images différentes sur un jeu de 10 000 images.") - -idx = np.random.randint(X_test.shape[0]-80) # Index aléatoire -print ("\n") -print ("Test sur les images de "+ str(idx) + " à "+ str(idx+80) + " sur un jeu de 10 000 images.") -X_new = X_test[idx:idx+80] +print ("Test sur le jeu de test (10 000 images).") +X_new = X_test y_new = np.argmax(model.predict(X_new), axis=-1) # Prédictions -y_new_test= y_test[idx:idx+80] # Cibles +y_new_target= y_test # Cibles +eval=model.evaluate(X_new, y_new_target) +# print ("Il y a "+str(int(np.round((1-eval[1])*X_new.shape[0]))) + " images non reconnues.\n") + +# Division du jeu de test par classes print ("\n") +print ("Test sur les jeux divisés par classe.") +_X_new_classes_lst=[] +_y_new_target_classes_lst=[] +for i in range (10): # Classe + _X_new_classe=[] + _y_new_target_classe=[] + for j in range (X_new.shape[0]): # Lecture de toutes les images + if y_new_target[j] == i: + _X_new_classe.append(X_new[j]) + _y_new_target_classe.append(y_new[j]) + _X_new_classes_lst.append(_X_new_classe) + _y_new_target_classes_lst.append(_y_new_target_classe) + +# Remplissage du tableau à partir de la liste +X_new_classes=[] +y_new_target_classes=[] +for i in range (10): + X_new_classes.append(np.empty(shape=(len(_X_new_classes_lst[i]),28,28))) + y_new_target_classes.append(np.empty(shape=(len(_y_new_target_classes_lst[i]),))) + for j in range (len(_X_new_classes_lst[i])): + X_new_classes[i][[j]]=_X_new_classes_lst[i][j] + y_new_target_classes[i][[j]]=_y_new_target_classes_lst[i][j] + +# Inférence sur les jeux par classe +y_new_classes=[] +for i in range (10): + y_new_classes.append(np.argmax(model.predict(X_new_classes[i]), axis=-1)) # Prédictions +somme=0 +print ("\n") +for i in range (10): + k=0 + for j in range (X_new_classes[i].shape[0]): + if y_new_classes[i][j] != i: + k +=1 + somme +=1 + print ("Dans la classe "+str(i)+", il y a "+str(k) + " images non reconnues sur "+ str(X_new_classes[i].shape[0])+".") + +print ("\n") +print ("Au total, il y a "+str(somme) + " images non reconnues sur 10 000.") +print ("Soit une précision de "+str(1-(somme/10000))+".") # ############################################################################### # # Résultats @@ -132,16 +173,20 @@ apts_ax.set_xlabel("Époque") apts_ax.legend() # Prédictions -for i in range (10): - for j in range (8): - 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(y_new[i*2+j], fontsize=10) - else: - img_ax[j][i].set_title(y_new[i*2+j], fontsize=10, color="red") +for ligne in range (10): # Ligne + i_first=-1 + for colonne in range (15): # Colonne + for i in range (i_first+1, X_new.shape[0]): + img_ax[ligne][colonne].set_axis_off() + if y_new_target[i] == ligne and y_new[i]!=y_new_target[i]: + # if y_test[i] == 2: + img_ax[ligne][colonne].imshow(X_new[i], cmap="binary", interpolation="nearest") + img_ax[ligne][colonne].set_title(str(y_new[i]), fontsize=10, color="red") + i_first=i + break plt.show() # Performances +print ("\n") print ("Temps total : "+str(time.time()-t_debut)) diff --git a/03-vision/README.md b/03-vision/README.md index 009eacf..f069f08 100644 --- a/03-vision/README.md +++ b/03-vision/README.md @@ -1,9 +1,13 @@ # Mes scripts de ML - Vision par ordinateur -### Reconnaissance de digits par réseaux de neurones simples (RNA) +### Reconnaissance de digits - Analyse et préparation des données -![capture d'écran](img/01-digit_simple.png) +![capture d'écran](img/01-digit-prepa_data.png) + +### Reconnaissance de digits - Réseaux de neurones simples (RNA) + +![capture d'écran](img/02-digit_simple.png) -### Reconnaissance de digits par réseaux de neurones convolutifs (CNN) +### Reconnaissance de digits - Réseaux de neurones convolutifs (CNN) -![capture d'écran](img/02-digit_cnn.png) +![capture d'écran](img/03-digit_cnn.png) diff --git a/03-vision/img/02-digit-simple.png b/03-vision/img/02-digit-simple.png new file mode 100644 index 0000000..8a32e9e Binary files /dev/null and b/03-vision/img/02-digit-simple.png differ