简体   繁体   English

Tensorflow model层连接失败,无法使用shap.DeepExplainer

[英]Tensorflow model layer connection failed, and can not use shap.DeepExplainer

I am trying to apply shap.deepexplainer to explain the model output.我正在尝试应用 shap.deepexplainer 来解释 model output。

My model class is as follows:我的model class如下:

class MyModel(tf.keras.Model):
    def __init__(self,
                 input_dim,
                 emb_dim=128,
                 alpha_hidden_dim_size=128,
                 beta_hidden_dim_size=128,
                 keep_prob_emb=0.25,
                 keep_prob_context=0.25,
                 num_class=1):
        super(MyModel, self).__init__()

        self.embedding = layers.Dense(emb_dim,
                                      use_bias=False,
                                      input_shape=(input_dim, ))

        self.emb_drp = layers.Dropout(keep_prob_emb)

        self.enroll = layers.Dense(emb_dim, activation='tanh')

        
        self.gru_alpha = layers.Bidirectional(
            layers.LSTM(alpha_hidden_dim_size, return_sequences=True))
        self.gru_beta = layers.Bidirectional(
            layers.LSTM(beta_hidden_dim_size, return_sequences=True))

        self.alpha = layers.Dense(1)
        self.beta = layers.Dense(emb_dim, activation='tanh')

        self.context_drp = layers.Dropout(keep_prob_context)

        self.out = layers.Dense(num_class)

    def call(self, visits, enroll, lengths, **kwargs):
        max_len = lengths[tf.argmax(lengths)]
        visits = visits[:, :max_len]
        emb = self.embedding(visits)
        emb = self.emb_drp(emb, training=kwargs.get('training', False))
        enroll = self.enroll(enroll)
        mask = tf.sequence_mask(lengths)
        h_a = self.gru_alpha(emb, mask=mask)
        h_b = self.gru_beta(emb, mask=mask)
        preAlpha = self.alpha(h_a)
        preAlpha = tf.keras.backend.squeeze(preAlpha, axis=2)
        mask_norm = (1 - tf.cast(mask, tf.float32)) * NEG_INF
        alpha = tf.nn.softmax(preAlpha + mask_norm, axis=1)
        beta = self.beta(h_b)
        c_t = tf.math.reduce_sum(alpha[:, :, None] * beta * emb, axis=1)
        c_t = layers.add([c_t, enroll])
        c_t = self.context_drp(c_t, training=kwargs.get('training', False))
        preY = self.out(c_t)

        return preY, alpha, beta

When I applied my model as:当我将 model 应用为:

model = MyModel(**flags)

And the model is successfully loaded: model 加载成功:

print(model) 
<__main__.MyModel object at 0x7f51db414400>

Then I am trying to use the然后我尝试使用

background = X.loc[10:20]
e = shap.DeepExplainer((model.layers[0].input, model.layers[-1].output), background)

but then it gives me the error:但后来它给了我错误:

AttributeError: Layer dense is not connected, no input to return. AttributeError: 层密集未连接,没有输入返回。 Traceback (most recent call last): File "/home/ANANT/codes/test/env/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py",line 1808, in input' is not connected, no input to return.')回溯(最近一次调用):文件“/home/ANANT/codes/test/env/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py”,第 1808 行,在输入中未连接,没有输入返回。')

And also the model.layers[-1].output can not give proper output neither:而且model.layers[-1].output也不能给出正确的 output :

AttributeError: Layer dense_4 has no inbound nodes. AttributeError:Layer dense_4 没有入站节点。 Traceback (most recent call last): File "/home/ANANT/test/env/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 1827, in output raise AttributeError('Layer ' + self.name + ' has no inbound nodes.')回溯(最后一次调用):文件“/home/ANANT/test/env/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py”,第 1827 行,output raise AttributeError( '图层' + self.name + '没有入站节点。')

My package versions are: keras==2.3.1, tensorflow==1.15.3, shap==0.35.0我的 package 版本是:keras==2.3.1,tensorflow==1.15.3,shap==0.35.0

I stuck at this question for a few days, tried shap.KernelExplainer as well, and it gives me a different error:我在这个问题上停留了几天,也尝试了 shap.KernelExplainer,它给了我一个不同的错误:

shap.KernelExplainer(model, df_fis, link="logit")

And the error is as follows:错误如下:

TypeError: call() missing 2 required positional arguments: 'enroll' and 'lengths' Traceback (most recent call last): File "/home/ANANT/test/env/lib/python3.6/site-packages/shap/explainers/kernel.py", line 97, in __init__model_null = match_model_to_data(self.model, self.data) File "/home/ANANT/test/env/lib/python3.6/site-packages/shap/common.py", line 89, in match_model_to_dataout_val = model.f(data.data) File "/home/ANANT/test/env/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 968, in __call__outputs = self.call(cast_inputs, *args, **kwargs) TypeError: call() missing 2 required positional arguments: 'enroll' and 'lengths' Traceback (最近一次调用最后): File "/home/ANANT/test/env/lib/python3.6/site-packages/shap/explainers /kernel.py”,第 97 行,在 __init__model_null = match_model_to_data(self.model, self.data) 文件“/home/ANANT/test/env/lib/python3.6/site-packages/shap/common.py”中,第 89 行,在 match_model_to_dataout_val = model.f(data.data) 文件“/home/ANANT/test/env/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py”中,第 968 行, 在 __call__outputs = self.call(cast_inputs, *args, **kwargs)

Please help, thanks in advance!请帮忙,提前谢谢!

I think you missed the softmax part我想你错过了softmax部分

Pytorch version Pytorch版本

self.softmax = LogSoftmax(dim=1)

Keras version Keras版

layers.Dense(num_classes, activation="softmax")

Add the above line at the end of your __init__ method, see if it works__init__方法的末尾添加上面的行,看看它是否有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 shap.DeepExplainer 给出与 CNN 的 GlobalMaxPooling1D 层相关的错误 - shap.DeepExplainer gives an error related to GlobalMaxPooling1D layer of CNN Python 中的 SHAP 在使用 DeepExplainer 时是否支持 Keras 或 TensorFlow 模型? - Does SHAP in Python support Keras or TensorFlow models while using DeepExplainer? 带有 Shap ValueError 的 DeepExplainer:使用不是符号张量的输入调用了 Layersequential_1 - DeepExplainer with Shap ValueError: Layer sequential_1 was called with an input that isn't a symbolic tensor Tensorflow:在另一个 model 中使用 model 作为层 - Tensorflow: Use model inside another model as layer PyTorch 的 SHAP 值 - KernelExplainer vs DeepExplainer - SHAP values with PyTorch - KernelExplainer vs DeepExplainer 如何在Tensorflow DNNClassifier中使用SHAP KernelExplainer - How to use SHAP KernelExplainer with Tensorflow DNNClassifier 用 SHAP 解释多标签目标 Tensorflow 模型 - Explaining a multi-label target Tensorflow model with SHAP SHAP DeepExplainer 错误:“元组”对象没有属性“设备” - SHAP DeepExplainer Error: 'tuple' object has no attribute 'device' 由于 Tensorflow 错误(张量不可散列),无法使用 SHAP GradientExplainer - Unable to use SHAP GradientExplainer due to Tensorflow error (tensors are unhashable) tensorflow model 中的随机 select 层 - Randomly select layer in tensorflow model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM