U
    fv                     @   s*  d dl Zd dlZd dlmZ ddlmZ d dlmZ d dl	Z	da
dadadaG dd deZdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zi Z ee d*< ee d+< ee d,< ee d-< ee d.< ee d/< ee d0< ee d1< ee d2< ee d3< ee d4< ee d5< ee d6< ee d7< ee d8< ee d9< ee d:< ee d;< ee d<< ee d=< ee d>< ee d?< ee d@< ee dA< ed e dB< ed e dC< ed e dD< edEge dF< ed e dG< ed e dH< ed e dI< ed e dJ< ed e dK< ed e dL< ed e dM< ed e dN< ed e dO< ed e dP< ed e dQ< ed e dR< ed e dS< ed e dT< ed e dU< ed ddVdW e dX< ed ddYdW e dZ< ed dd[dW e d\< ed dd]dW e d^< ed dd_dW e d`< ed ddadW e db< ee dc< ee dd< ee de< ee df< dS )g    N)	Explainer   )!standard_combine_mult_and_diffref)LooseVersionc                   @   sJ   e Zd ZdZddefddZdd Zdd Zdd
dZdd Z	dd Z
dS )TFDeepExplainera  
    Using tf.gradients to implement the backgropagation was
    inspired by the gradient based implementation approach proposed by Ancona et al, ICLR 2018. Note
    that this package does not currently use the reveal-cancel rule for ReLu units proposed in DeepLIFT.
    Nc                 C   sb  || _ tdkr`ddlma ddlma ttds<ddlm	a ddl
attjtdk r`td tdkrz(ddlattjtd	k rtd
 W n   Y nX tt|dr|j| _|jd j| _ntt|dr|j| _|jd j| _nptt|dr|j| _|jd j| _nDtt|drH|d | _|d | _ndsbttt|d t| jtksztdt| jjdk stdd| _t| jjdkrd| _d| _t| jtkst| jdkrd| _t| jtkr| jg| _t|tkrt|ddkr|g}|| _i | _i | _ |dkrzJtdk	rrttj!j"drrtj!j"j#dk	rrtj!$ | _%ntjj!$ | _%W n   tj&j'jj!$ | _%Y nX n|| _%|dkr0g | _(| j%j)* D ]T}d|j+kr|jdkrt|j,d jdkr|j,d j-tj.kr| j(/| qdd | j(D | _0ndd |D | _(t| jdrVd| _1n<| jd jd dkrvtd | 2| j| j| j3d| _1t4| j(}d d t5D }t6| jj7g||}	t8d!d | jD |||	d"| _9i | _:| j9D ],}d| j:|j< |jt5krt;d#|jd$ q| js&dg| _<n8| jj= d }
|
dk	rVd%d t>|
D | _<nt?d&dS )'a   An explainer object for a deep model using a given background dataset.

        Note that the complexity of the method scales linearly with the number of background data
        samples. Passing the entire training dataset as `data` will give very accurate expected
        values, but be unreasonably expensive. The variance of the expectation estimates scale by
        roughly 1/sqrt(N) for N background data samples. So 100 samples will give a good estimate,
        and 1000 samples a very good estimate of the expected values.

        Parameters
        ----------
        model : keras.Model or (input : [tf.Operation], output : tf.Operation)
            A keras model object or a pair of TensorFlow operations (or a list and an op) that
            specifies the input and output of the model to be explained. Note that SHAP values
            are specific to a single output value, so you get an explanation for each element of
            the output tensor (which must be a flat rank one vector).

        data : [numpy.array] or [pandas.DataFrame] or function
            The background dataset to use for integrating out features. DeepExplainer integrates
            over all these samples for each explanation. The data passed here must match the input
            operations given to the model. If a function is supplied, it must be a function that
            takes a particular input example and generates the background dataset for that example
        session : None or tensorflow.Session
            The TensorFlow session that has the model we are explaining. If None is passed then
            we do our best to find the right session, first looking for a keras session, then
            falling back to the default TensorFlow session.

        learning_phase_flags : None or list of tensors
            If you have your own custom learning phase flags pass them here. When explaining a prediction
            we need to ensure we are not in training mode, since this changes the behavior of ops like
            batch norm or dropout. If None is passed then we look for tensors in the graph that look like
            learning phase flags (this works for Keras models). Note that we assume all the flags should
            have a value of False during predictions (and hence explanations).

        combine_mult_and_diffref : function
            This function determines how to combine the multipliers,
             the original input and the reference input to get
             the final attributions. Defaults to
             standard_combine_mult_and_diffref, which just multiplies
             the multipliers with the difference-from-reference (in
             accordance with the standard DeepLIFT formulation) and then
             averages the importance scores across the different references.
             However, different approaches may be applied depending on
             the use case (e.g. for computing hypothetical contributions
             in genomic data)
        Nr   )ops)gradients_impl_IsBackpropagatable)gradients_utilz1.4.0z>Your TensorFlow version is older than 1.4.0 and not supported.z2.1.0z9Your Keras version is older than 2.1.0 and not supported.z$keras.engine.sequential.Sequential'>zkeras.models.Sequential'>zkeras.engine.training.Model'>ztuple'>r   Fz) is not currently a supported model type!z9The model output to be explained must be a single tensor!   z4The model output must be a vector or a single value!T__call___SESSIONZlearning_phaseZConstc                 S   s   g | ]}|j d  qS r   )outputs.0op r   C/tmp/pip-target-lpfmz8o1/lib/python/shap/explainers/deep/deep_tf.py
<listcomp>   s     z,TFDeepExplainer.__init__.<locals>.<listcomp>c                 S   s   g | ]
}|j qS r   )r   r   tr   r   r   r      s     i  zjYou have provided over 5k background samples! For better performance consider using smaller random sample.c                 S   s   g | ]}t | tkr|qS r   )op_handlersbreak_dependencer   kr   r   r   r      s      c                 S   s   g | ]}|  D ]}|qqS r   )	consumers)r   inputr   r   r   r   r      s     
  )
within_opsz	Warning: zWused in model but handling of op is not specified by shap; will use original  gradientsc                 S   s   g | ]}d qS Nr   r   ir   r   r   r      s     zTThe model output tensor to be explained cannot have a static shape in dim 1 of None!)@combine_mult_and_diffreftfZtensorflow.python.frameworkr   tf_opsZtensorflow.python.opsr   tf_gradients_implhasattrr
   Z
tensorflowr   __version__warningswarnkerasstrtypeendswithinputsmodel_inputsZlayersoutputmodel_outputAssertionErrorlistlenshapemulti_outputmulti_inputdata_vinputs
orig_gradsbackendZtensorflow_backendr   Zget_sessionsessioncompatZv1Zlearning_phase_opsgraphZget_operationsnamer   Zdtypeboolappendlearning_phase_flagsZexpected_valuerunZmeantensors_blocked_by_falser   backward_walk_opsr   forward_walk_opsbetween_ops
used_typesprintphi_symbolicsas_listrange	Exception)selfmodelr9   r=   rC   r#   r   tensor_blacklistZdependence_breakersZback_opsZnoutputsr   r   r   __init__   s    1



 

*
.

  


zTFDeepExplainer.__init__c                    s:   |j  jkr.t fdd|jD  j|j <  j|j  S )z_ Return which inputs of this operation are variable (i.e. depend on the model inputs).
        c                    s.   g | ]&}|j  jkp(|jd d  jD kqS )c                 S   s   g | ]
}|j qS r   r@   )r   xr   r   r   r      s     z?TFDeepExplainer._variable_inputs.<locals>.<listcomp>.<listcomp>)r   rH   r@   r0   r   rO   r   r   r      s     z4TFDeepExplainer._variable_inputs.<locals>.<listcomp>)r@   r:   nparrayr/   )rO   r   r   rU   r   _variable_inputs   s    "z TFDeepExplainer._variable_inputsc              
   C   s   | j | dkrtjj}tD ]P}||krT|| d | j|< t| tk	rj| j|| d< q|| jkrt	|d qt
tdrtj}dd t_z6| jr| jdd|f n| j}t|| j| j |< W 5 t
tdr|t_tD ]}||kr| j| || d< qX | j | S )zH Get the SHAP value computation graph for a given model output.
        Nr-   z; was used in the model but is not in the gradient registry!r	   c                 S   s   dS )NTr   )Ztensorr   r   r   <lambda>       z.TFDeepExplainer.phi_symbolic.<locals>.<lambda>)rK   r%   Z_gradient_registry	_registryr   r;   passthroughcustom_gradrI   rN   r'   r&   r	   r7   r2   r$   	gradientsr0   )rO   r"   regnZorig_IsBackpropagatableoutr   r   r   phi_symbolic   s*    



zTFDeepExplainer.phi_symbolicmaxc                    s   | j s@t tkr,t dkr,ds>tdqTt tkrT g nt tksTtdt| jt kstdt| jt f |d k	r
| jr
| | j| j }|dkrt	
| }n:|dkrt	
|}n&|dkrt	
t	|}ndstd	|d d d |f }n&t	t	t| j d
 jd
 df}g }t|jd D ]}g }	tt D ]}
|	t	 |
 j qXt d
 jd
 D ]L|d k	rȈ| d
krtdd d
 jd
  tj  t| jdr|  fddtt D ttkrgn| j fddtt D fddtt D }||f }| | || j|| jfddtt D  fddtt D d}tt D ]}|| |	| < qq|| j s|	d
 n|	 qB| js|d
 S |d k	r||fS |S d S )Nr   Fz(Expected a single tensor as model input!z Expected a list of model inputs!zANumber of model inputs (%d) does not match the number given (%d)!rc   minZmax_absz/output_rank_order must be max, min, or max_abs!r   Donezexamples ofr   c                    s   g | ]} |  qS r   r   r   lXjr   r   r     s     z/TFDeepExplainer.shap_values.<locals>.<listcomp>c                    sX   g | ]P}t  | d   | jd ftdd tt | jd  D  qS )r   r   c                 S   s   g | ]}d qS r   r   r   r   r   r   r   "  s     z:TFDeepExplainer.shap_values.<locals>.<listcomp>.<listcomp>)rV   tiler6   tuplerM   r5   rf   )ri   bg_datarj   r   r   r   "  s     c                    s$   g | ]}t |  | gd qS r   )rV   Zconcatenaterf   )rn   tiled_Xr   r   r   #  s     c                    s(   g | ] }| d  | j d   qS )Nr   )r6   rf   )rn   sample_phisr   r   r   +  s   c                    s   g | ]} |  qS r   r   rf   rh   r   r   r   -  s     )ZmultZorig_inprn   )r8   r-   r4   r5   r3   r0   r7   rD   r2   rV   Zargsortabsrl   ZarangerK   r6   rM   rB   ZzerosrJ   sysstdoutflushr'   r9   rb   r#   )rO   ri   Zranked_outputsZoutput_rank_orderZprogress_messageZmodel_output_valuesZmodel_output_ranksZoutput_phisr"   Zphisr   Zjoint_inputZfeature_indZphis_jrg   r   )ri   rn   rj   rp   ro   r   shap_values   sl    ,&

"

zTFDeepExplainer.shap_valuesc                 C   s0   t t||}| jD ]}d||< q| j||S )zN Runs the model while also setting the learning phase flags to False.
        F)dictziprC   r=   rD   )rO   ra   r0   ri   Z	feed_dictr   r   r   r   rD   <  s    

zTFDeepExplainer.runc                 G   s   t |j | |f| S )zG Passes a gradient op creation request to the correct handler.
        )r   r-   )rO   r   gradsr   r   r   r]   D  s    zTFDeepExplainer.custom_grad)Nrc   N)__name__
__module____qualname____doc__r   rR   rX   rb   ru   rD   r]   r   r   r   r   r      s   
 3&  
Ir   c                    s(   g   fdd| D ]}| q S )z Follows a set of ops assuming their value is False and find blocked Switch paths.

    This is used to prune away parts of the model graph that are only used during the training
    phase (like dropout, batch norm, etc.).
    c                    sB   | j dkr | jd  n"| jD ]}| D ]}| q.q"d S )NSwitchr   )r-   rB   r   r   )r   ra   cZblockedrecurser   r   r   Q  s
    

z)tensors_blocked_by_false.<locals>.recurser   )r   r   r   r   r   rE   J  s
    
rE   c                 C   sh   g }dd | D }t |dkrd| }|j|kr||kr|| |jD ]}||krH||j qHq|S )Nc                 S   s   g | ]}|qS r   r   r   r   r   r   r   _  s     z%backward_walk_ops.<locals>.<listcomp>r   )r5   popr-   rB   r/   r   )	start_opsrQ   op_type_blacklist	found_opsop_stackr   r   r   r   r   rF   ]  s    

rF   c           	      C   s|   g }dd | D }t |dkrx| }|j|kr||kr||kr|| |jD ]$}||krP| D ]}|| qdqPq|S )Nc                 S   s   g | ]}|qS r   r   r   r   r   r   r   k  s     z$forward_walk_ops.<locals>.<listcomp>r   )r5   r   r-   rB   r   r   )	r   rQ   r   r   r   r   r   ra   r~   r   r   r   rG   i  s    

rG   c              	   G   s  |j d }tj|dddd}|| }tj|dd}tj|ddd}|| }| j|j|j|j|jg tj|||d d	d }	| jd
d= t	|d\}
}t	|d\}}|
| }dgdd |j
dd D  }ttt||dk |	|	t|| | | S )a   Just decompose softmax into its components and recurse, we can handle all of them :)

    We assume the 'axis' is the last dimension because the TF codebase swaps the 'axis' to
    the last dimension before the softmax op if 'axis' is not already the last dimension.
    We also don't subtract the max before tf.exp for numerical stability since that might
    mess up the attributions and it seems like TensorFlow doesn't define softmax that way
    (according to the docs)
    r   r   Tin0_max)axiskeepdimsr@   Z
custom_exprS   r   r   )Zgrad_ysN   c                 S   s   g | ]}d qS rk   r   r!   r   r   r   r     s     zsoftmax.<locals>.<listcomp>r   ư>)r/   r$   Z
reduce_maxexp
reduce_sumrH   extendr   r^   splitr6   whererl   rq   )	explainerr   rx   Zin0r   Zin0_centeredZevalsZrsumdivra   xin0rin0Zxin0_centeredZrin0_centered	delta_in0dup0r   r   r   softmaxw  s$    	
r   c                 G   s   t |jd d\}}t |jd d\}}|| }dgdd |jdd  D  }t ||}	t |	| ||	 gd}
t | j|j ||d |
 d\}}t 	t 
t |dk t ||| | |S )Nr   r   c                 S   s   g | ]}d qS rk   r   r!   r   r   r   r     s     zmaxpool.<locals>.<listcomp>r   Hz>)r$   r   r/   r   r6   maximumconcatr;   r-   rl   r   rq   
zeros_like)r   r   rx   r   r   xoutroutr   r   Z	cross_maxZdiffsZxmax_posZrmax_posr   r   r   maxpool  s    &
r   c              	   G   s  |j d }| |}|d rP|d sPt|jdks>tdtt|j d d\}}t|jd d\}}dgdd |jdd  D  }	dgdd |jdd  D  }
t	|| |	}t
|d t	|| |
 ttt|jt|d j}|jdkr(d tt|d	k t||| gS d tt|d	k t||| d gS |d r~|d s~| j|j ||d d gS d
stdd S )Nr   r   r   z4Only scalar indices supported right now in GatherV2!c                 S   s   g | ]}d qS rk   r   r!   r   r   r   r     s     zgather.<locals>.<listcomp>c                 S   s   g | ]}d qS rk   r   r!   r   r   r   r     s     ResourceGatherr   Fz3Axis not yet supported to be varying for gather op!)r/   rX   r5   r6   r3   r$   r   Zto_floatr   rl   r   r4   rM   r-   r   rq   r   r;   )r   r   rx   indicesvarxin1rin1r   r   Zdup_in1Zdup_outZdelta_in1_tZout_sumr   r   r   gather  s4    

:r   c                    s    fdd}|S )Nc                    s   |  |}|  r,| s,t | |f| S | rN|  sNt| |f| S |  rt| rtt | |f| S dd |jD S d S )Nc                 S   s   g | ]}d qS r    r   r   _r   r   r   r     s     zAlinearity_1d_nonlinearity_2d.<locals>.handler.<locals>.<listcomp>)rX   linearity_1d_handlernonlinearity_2d_handlerr/   r   r   rx   r   
input_ind0
input_ind1op_funcr   r   handler  s    
z-linearity_1d_nonlinearity_2d.<locals>.handlerr   r   r   r   r   r   r   r   linearity_1d_nonlinearity_2d  s    
r   c                    s    fdd}|S )Nc                    s   |  |}|  r,| s,t | |f| S | rN|  sNt| |f| S |  rt| rtt | |f| S dd |jD S d S )Nc                 S   s   g | ]}d qS r    r   r   r   r   r   r     s     zDnonlinearity_1d_nonlinearity_2d.<locals>.handler.<locals>.<listcomp>)rX   nonlinearity_1d_handlerr   r/   r   r   r   r   r     s    
z0nonlinearity_1d_nonlinearity_2d.<locals>.handlerr   r   r   r   r   nonlinearity_1d_nonlinearity_2d  s    
r   c                    s    fdd}|S )Nc                    s   t  | |f| S r    )r   r   r   rx   	input_indr   r   r     s    z nonlinearity_1d.<locals>.handlerr   r   r   r   r   r   nonlinearity_1d  s    r   c              	   G   s  t t|jD ]4}|| kr||| rtt|d |j d qt|j|  d\}}t|j	|  d\}}|| }	dgdd |	j
dd  D  }
dd |jD }|j|j ||d }ttt|	|
d	k t|jdkr||  n||d t|| |	 |
 || < |S )
Nth input to  cannot vary!r   c                 S   s   g | ]}d qS rk   r   r!   r   r   r   r     s     z+nonlinearity_1d_handler.<locals>.<listcomp>r   c                 S   s   g | ]}d qS r    r   r   r   r   r   r     s     r   r   )rM   r5   r/   rX   r3   r,   r@   r$   r   r   r6   r;   r-   r   rl   rq   )r   r   r   rx   r"   r   r   r   r   r   r   ra   r;   r   r   r   r     s    *r   c                 G   s   | dkr|dkst dt|jd d\}}t|j|  d\}}	t|j| d\}
}||	 }|
| }dgdd |jdd  D  }|||}||	|
}|| }}d|| | |  }|d t|| | }d|| | |  }|d t|| | }tt	|jt	|jkrVt
t	|jt	|jkd d }tj||dd	}nVtt	|jt	|jkrt
t	|jt	|jkd d }tj||dd	}t
tt||d
k t||}t
tt||d
k t||}||gS )Nr   r   z8TODO: Can't yet handle double inputs that are not first!r   c                 S   s   g | ]}d qS rk   r   r!   r   r   r   r     s     z+nonlinearity_2d_handler.<locals>.<listcomp>g      ?Tr   r   )r3   r$   r   r   r/   r6   rl   rV   anyrW   r   r   rq   r   )r   r   r   r   r   rx   r   r   r   r   r   r   r   Z	delta_in1r   Zout10Zout01Zout11Zout00Zout0Zout1Zbroadcast_indexr   r   r   r     s.    


 & &&&r   c                    s    fdd}|S )Nc                    s   t  | |f| S r    )r   r   r   r   r   r     s    zlinearity_1d.<locals>.handlerr   r   r   r   r   linearity_1d  s    r   c                 G   sZ   t t|jD ]4}|| kr||| rtt|d |j d q|j|j |f| S Nr   r   	rM   r5   r/   rX   r3   r,   r@   r;   r-   )r   r   r   rx   r"   r   r   r   r     s    *r   c                    s    fdd}|S )Nc                    s   t  | |f| S r    )linearity_with_excluded_handlerr   
input_indsr   r   r     s    z(linearity_with_excluded.<locals>.handlerr   )r   r   r   r   r   linearity_with_excluded  s    r   c                 G   sl   t t|jD ]F}|| ks,|t|j | kr||| rtt|d |j d q|j|j |f| S r   r   )r   r   r   rx   r"   r   r   r   r   #  s    *r   c                 G   s   | j |j |f| S r    )r;   r-   r   r   r   r   r\   *  s    r\   c                 G   s   dd |j D S )a   This function name is used to break attribution dependence in the graph traversal.
     
    These operation types may be connected above input data values in the graph but their outputs
    don't depend on the input values (for example they just depend on the shape).
    c                 S   s   g | ]}d qS r    r   r   r   r   r   r   3  s     z$break_dependence.<locals>.<listcomp>)r/   r   r   r   r   r   -  s    r   ZIdentityZStridedSliceZSqueezeZ
ExpandDimsZPackZBiasAddZUnpackAddSubZMergeZSumZMeanZCastZ	TransposeZEnterZExitZNextIterationZTileZTensorArrayScatterV3ZTensorArrayReadV3ZTensorArrayWriteV3ZShapeZRandomUniformZ	ZerosLikeZReshapeZPadZ	ReverseV2r   ZConcatV2ZConv2Dr}   ZAvgPoolZFusedBatchNormZReluZEluZSigmoidZTanhZSoftplusZExpLogZClipByValueZRsqrtZSquareZMaxc                 C   s   | | | |  S r    r   rT   yr   r   r   rY   m  rZ   rY   ZSquaredDifferencec                 C   s   t | |S r    )r$   minimumr   r   r   r   rY   n  rZ   ZMinimumc                 C   s   t | |S r    )r$   r   r   r   r   r   rY   o  rZ   ZMaximumc                 C   s   | | S r    r   r   r   r   r   rY   r  rZ   ZMulc                 C   s   | | S r    r   r   r   r   r   rY   s  rZ   ZRealDivc                 C   s   t | |S r    )r$   matmulr   r   r   r   rY   t  rZ   ZMatMulZGatherV2r   ZMaxPoolZSoftmax)!numpyrV   r)   Zshap.explainers.explainerr   miscr   Zdistutils.versionr   rr   r+   r$   r%   r&   r   rE   rF   rG   r   r   r   r   r   r   r   r   r   r   r   r   r\   r   r   r   r   r   r   <module>   s     ?	