3

I have below code which I am trying to understand keras mean and want to get pooled_grads print. While printing I am getting below error

import numpy as np
import tensorflow as tf

arr3 = np.array([ [
                   [1,2,3],
                   [4,5,6]
                 ],
                 [
                   [1,2,3],
                   [4,5,6]
                 ],
                 [
                   [1,2,3],
                   [4,5,6]
                 ]
                ] 
               )

#print("Arr shape", arr3.shape)

import keras.backend as K

import numpy as np

pooled_grads = K.mean(arr3, axis=(0, 1, 2))

print("------------------------")

print(pooled_grads)

I am getting below error

AttributeError: 'numpy.dtype' object has no attribute 'base_dtype'

2
  • Since the arr3 is 3d, K.mean(arr3) is equivalent to K.mean(arr3, axis=(0,1,2)) Commented May 18, 2021 at 18:00
  • P.S. I believe the error is not on the print(pooled_grads) but on the K.mean(arr3, axis=(0,1,2)) Commented May 18, 2021 at 18:03

1 Answer 1

4

Most Keras backend functions expect Keras tensors as inputs. If you want to use a NumPy array as input, convert it to a tensor first, for example with K.constant:

pooled_grads = K.mean(K.constant(arr3), axis=(0, 1, 2))

Note that pooled_grads here will be another tensor, so printing it will not give you the value directly, but just a reference to the tensor object. In order to get the value of the tensor, you can use for example K.get_value:

print(K.get_value(pooled_grads))
# 3.5
Sign up to request clarification or add additional context in comments.

1 Comment

I had the same error with K.clip() function. K.constant didn't work, so I solved it with tf.convert_to_tensor() and passing the tensors to the Keras clip() function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.