DL

CAM(class activation map)

math_tbro 2021. 12. 17. 00:47

 

 

CODE

def extract_cam(model,resize_data_set,img_start_num,img_end_num):
    for i in range(img_start_num,img_end_num):
        img = resize_data_set[i]
        img_array = np.expand_dims(np.asarray(img)[:,:,:3]/255.,0)
        # get prediction result and convolution output values
        get_output = K.function([model.layers[0].input], [model.layers[-4].output, model.layers[-1].output])
        [conv_outputs, predictions] = get_output([img_array])
        class_idx = np.argmax(predictions)
        conv_outputs = conv_outputs[0,:,:,:]
        class_weights = model.layers[-1].get_weights()[0]
        # calculate cam
        cam = np.zeros(dtype=np.float32, shape=conv_outputs.shape[0:2])
        for i, w in enumerate(class_weights[:,class_idx]):
            cam += w*conv_outputs[:,:,i]
        # normalize cam and resize to fit the original image size
        cam = cam/np.max(cam)
        cam = cv2.resize(cam, (224, 224))
        # print cam image and original image
        plt.figure(figsize=(10,20))
        plt.subplot(1,2,1)
        plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        plt.axis('off')
        plt.subplot(1,2,2)
        plt.imshow(cam, cmap='jet', alpha=0.8)
        plt.imshow(img, alpha=0.3)
        plt.axis('off')
        plt.show()

 

 

시각화 할때 쓴 코드는 이런데 도움이 될지는 모르겠다....

vgg16 을 사용했고 vgg16 -> gap -> dense1 로 설정한 것이다. 

 

 

결과를 보여드리면 

 

 

 

 

 

개와 이빨의 특징을 잘 잡아준 모습을 볼 수 있따.

'DL' 카테고리의 다른 글

딥러닝)Optimizer 알고리즘  (0) 2022.01.09
2.1 딥러닝  (0) 2022.01.03
[딥러닝]역전파 - Back Propagation  (0) 2022.01.03
GAP (global average pooling)  (0) 2021.12.17
VGG 16  (0) 2021.12.17