<jupyter_start><jupyter_text>Definindo variaveis<jupyter_code>DATA_DIR  = '../bases/pickle/imagens/cifar10/cifar10-test-pickle.pickle'
TEST2_DIR = '../bases/dados/imagens/teste2/amostra-CIFAR10'

#DATA_DIR  = '../bases/pickle/imagens/mnist/mnist-test-pickle.pickle'
#TEST2_DIR = '../bases/dados/imagens/teste2/amostra-numerica'

formato = 'jpg'
IMG_SIZE = 32
numero_de_canais = 3

#DATA_DIR = pathlib.Path(DATA_DIR)
#TEST2_DIR = pathlib.Path(TEST2_DIR)

pickle_in = open(DATA_DIR,"rb")
data_train = pickle.load(pickle_in)

model = tf.keras.models.load_model('../modelos_salvos/tensorflow/modelo_cifar10-aug-EPOCHS=50 - val_acc = 0.5922 exec_time - 9886.943656682968.h5')
model.summary()
#model = tf.keras.models.load_model('../modelos_salvos/tensorflow/modelo.h5')<jupyter_output>Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 25, 25, 32)        6176      
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 12, 12, 32)        0         
_________________________________________________________________
dropout (Dropout)            (None, 12, 12, 32)        0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 9, 9, 16)          8208      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 4, 4, 16)          0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 4, 4, 16)          0         
________________________________________________________[...]<jupyter_text>Definindo categorias<jupyter_code>#CATEGORIES = []
CATEGORIES = ut.get_classes(data_train)
CATEGORIES.sort()
try:
    CATEGORIES.remove('.ipynb_checkpoints')
except:
    pass
print(CATEGORIES)<jupyter_output>['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']<jupyter_text>Preparando dados<jupyter_code>def prepare(filepath):
    if numero_de_canais == 1:
        img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
    else:
        img_array = cv2.imread(filepath, cv2.IMREAD_COLOR)
    
    new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
    return new_array, new_array.reshape(-1, IMG_SIZE, IMG_SIZE, numero_de_canais)

def plot_image(prediction_array, true_label, img):
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(img, cmap='gray')
    predicted_label = np.argmax(prediction_array)        
    if predicted_label == true_label:
        color = 'green'
    else:
        color = 'red'
    plt.xlabel("Classe - {} | {:2.0f}% (true class {})".format(CATEGORIES[predicted_label], 100*np.max(prediction_array), CATEGORIES[true_label]), color=color)

def plot_value_array(prediction_array, true_label):
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])
    thisplot = plt.bar(range(len(CATEGORIES)), prediction_array, color= "#777777")
    plt.ylim([0, 1])
    predicted_label = np.argmax(prediction_array)

    thisplot[predicted_label].set_color('red')
    print(CATEGORIES[true_label])
    thisplot[true_label].set_color('green')
for category in CATEGORIES:

    true_label_num = CATEGORIES.index (category)
    
    DIR = TEST2_DIR+'/previsao '+'(' + category + ').'+formato
    
    xp, Xp = prepare(DIR)

    Xp=np.array(Xp/255.0)
       
    prediction = model.predict( Xp )
    
    prev = prediction[0]

    plt.figure(figsize=(6,3))
    plt.subplot(1,2,1)

    plot_image(prediction[0], true_label_num, xp)
    plt.subplot(1,2,2)
    plot_value_array(prediction[0],  true_label_num)
    plt.show()
    
    infos = []
    
    for i in range( len(prev) ):
        
        infos.append([str(CATEGORIES[i]), np.round(prev[i]*100, 3)])
        
        #print( 'Classe - {} | Confiança - {} %'.format(CATEGORIES[i], np.round(prev[i]*100, 2) ) )
    
    infos = sorted(infos[:], key=itemgetter(1), reverse = True)
    
    for i in range(len(prev)):
        
        print('Classe - {:<11} | Confiança - {:<5}'.format(infos[i][0], infos[i][1]))
        
        #print( infos[i][0], infos[i][1] )
    
    #print(  np.flip(np.sort(infos, axis=0,), axis=0)   )
    
    inp = model.inputs 
    
    k=0
    '''
    for layer in model.layers:
        if 'conv' in layer.name: 
            fig= plt.figure(figsize=(15,15))
            out = layer.output
            #print(out)
            feature_map = Model(inputs= inp, outputs= out)
            f = feature_map.predict(Xp)
              
            feature_map.summary()
            
            print('Ativação na {}° camada'.format(k+1))

            for i in range(f.shape[3]):

                #p = f[:,:,:,i]
                
                p = f[0,:,:,i]
                
                #print(p.shape)
                #print(p.shape[2])
                
                ax = fig.add_subplot(16,8,i+1)
                ax.imshow(p, cmap='gray')

            plt.show()
        k=k+1
    '''
    print('\n\n')<jupyter_output>airplane
{'fraction_non_alphanumeric': 0.14869816779170686, 'fraction_numerical': 0.03143683702989392, 'mean_word_length': 2.8875562218890556, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '374240', 'license': 'MIT', 'n_tokens_mistral': 1908, 'n_tokens_neox': 1813, 'n_words': 276, 'path': 'Fazendo previsoes.ipynb', 'repo_name': 'Birunda3000/Reconhecimento-de-imagem', 'size': '5185'}