Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ethen8181
GitHub Repository: ethen8181/machine-learning
Path: blob/master/keras/resnet_cam/__pycache__/explainer.cpython-36.pyc
2597 views
3

���[e�@sNddlZddlmZddlmZddlmZddlm	Z	m
Z
Gdd�d�ZdS)�N)�zoom)�Model)�preprocess_input)�load_img�img_to_arrayc@sBeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�CAMExplainerz$CAM (Class Activation Map) Explainer��cCs||_||_d|_d|_dS)N)�model�target_size�class_weights_�resnet50_cam_layers_)�selfr	r
�r�?/Users/mingyuliu/machine-learning/keras/resnet_cam/explainer.py�__init__szCAMExplainer.__init__cCs@|jdkr|j�\|_|_|j|�\|_}|j|�\|_|_|S)N)r�_get_resnet50_cam_infor�_read_and_process_img�img_�_create_cam�cam_Zpredicted_class_)r
�img_path�	keras_imgrrr�fits

zCAMExplainer.fitcCsDddlj}|j�\}}|j|jdd�|j|jddd�|j�dS)Nrg�?)�alpha�jet)�cmapr)�matplotlib.pyplot�pyplot�subplots�imshowrr�show)r
�plt�fig�axrrr�plots

zCAMExplainer.plotcCs�|jj|�\}}|jd}|jd}|jd}tj|�}|jdd�|f}tj|�jd|f�}tj||�j||f�}	|j	d|}
|j	d|}t
|	|
|fdd�}	|	|fS)N���r)�order�����)r�predict�shape�np�argmaxr�squeeze�reshape�dotr
r)r
�img�before_gap_output�
predictionZ	img_widthZ
img_heightZn_activation�predicted_class�dominate_class_weight�camZwidth_scale_ratioZheight_scale_ratiorrrr"s



zCAMExplainer._create_camcCs4t||jd�}t|�}tj|dd�}t|�}||fS)z�
        Reads in a single image, resize it to the specified target size
        and performs the same preprocessing on the image as the original
        pre-trained model.
        )r
r)�axis)rr
rr,�expand_dimsr)r
rr1Zimg_arrrrrrr9s
z"CAMExplainer._read_and_process_imgcCsH|jjd}|jjd}|j|jf}t|jj|d�}|j�d}||fS)N�r%)�inputs�outputsr�����r))r	�layers�outputr�input�get_weights)r
�before_gap_layer�class_pred_layerr;�resnet50_cam_layers�
class_weightsrrrrLsz#CAMExplainer._get_resnet50_cam_infoN�rr)rE)
�__name__�
__module__�__qualname__�__doc__rrr$rrrrrrrrs
r)�numpyr,�
scipy.ndimager�keras.modelsrZkeras.applications.resnet50rZkeras.preprocessing.imagerrrrrrr�<module>s