1

I'm trying to compute the gradients of the output with respect to the input, which can be called the sensitivity analysis of my model. I'm using keras 2.2.4 backed by tensorflow 1.13.1. Here is the code

#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]))

But I'm getting this problem:

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'

Any help is appreciated. Thanks in advance.

Maystro
  • 2,907
  • 8
  • 36
  • 71

1 Answers1

0

The problem is how we defined the inputs. Here is the solution:

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

And casting the result in a numpy array can't be done unless both inputs have the same shape so removing the casting would be better.
jac_test_set = jacobian_func([batch_signal, batch_metadata, False])

Maystro
  • 2,907
  • 8
  • 36
  • 71