1

我正在尝试计算输出相对于输入的梯度,这可以称为我的模型的敏感性分析。我正在keras 2.2.4使用tensorflow 1.13.1. 这是代码

#signal_x shape (88, 50500, 1)
#signal_x <class 'numpy.ndarray'>
#metadata_x shape (88, 24)
#metadata_x <class 'numpy.ndarray'>

grad_func = tf.gradients(model.output[:, m], model.input)
jacobian_func = K.function([model.input, K.learning_phase()], grad_func)

# model.input: [<tf.Tensor 'cu_dnnlstm_1_input:0' shape=(?, ?, 1) dtype=float32>, <tf.Tensor 'dense_1_input:0' shape=(?, 24) dtype=float32>]

for i in range((signal_x.shape[0] // batch_size) + 1):
            batch_signal = signal_x[i * batch_size:((i + 1) * batch_size) if i != (signal_x.shape[0] // batch_size) else signal_x.shape[0]]
            batch_metadata = metadata_x[i * batch_size:((i + 1) * batch_size) if i != (metadata_x.shape[0] // batch_size) else metadata_x.shape[0]]
            jac_test_set = np.array(jacobian_func([batch_signal, batch_metadata, False]))

但我遇到了这个问题:

File "classes/asdas.py", line 178, in jacobian_tensorflow
    jac_test_set = np.array(jacobian_func([batch_signal, batch_metadata, False]))
  File "/home/hassan/.local/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 2715, in __call__
    return self._call(inputs)
  File "/home/hassan/.local/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 2655, in _call
    dtype=tf.as_dtype(tensor.dtype).as_numpy_dtype))
AttributeError: 'list' object has no attribute 'dtype'

任何帮助表示赞赏。提前致谢。

4

1 回答 1

0

问题是我们如何定义输入。这是解决方案:

jacobian_func = K.function([model.input[0], model.input[1], K.learning_phase()], grad_func)

除非两个输入具有相同的形状,否则无法将结果转换为 numpy 数组,因此删除转换会更好。
jac_test_set = jacobian_func([batch_signal, batch_metadata, False])

于 2019-12-18T10:34:13.633 回答