[TensorFlow] TypeError: unsupported operand type(s) for /: ‘Dimension‘ and ‘int‘

2023-05-16

错误:

TypeError: unsupported operand type(s) for /: 'Dimension' and 'int', please use // instead

问题:

使用tf.py_function()调用numpy函数时,执行出错。numpy函数出错代码如下:

def cal(boxes):
    N = boxes.shape[0]
    N1 = np.arange(N)

导致错误的代码是np.arange(N)。出错的原因是N的类型在tf中不是int,而是<class ‘tensorflow.python.framework.tensor_shape.Dimension’>

解决方案:

N = boxes.shape[0].value
# or
N = int(boxes.shape[0])

参考:

This line

self._num_examples = data.shape[0]

returns an int if data is a numpy array:

np_data = np.random.randn(10,10)
np_ans = np_data.shape[0]
print(type(np_ans))

>>> <class 'int'>

but if data is a tf.Variable :

tf_data = tf.Variable(np.random.randn(10,10), dtype=tf.float32)
tf_ans = tf_data.shape[0]
print(type(tf_ans))

>>> <class 'tensorflow.python.framework.tensor_shape.Dimension'>

an instance of tensor_shape.Dimension is returned which can then not be used by np.arrange() here:

---> 59             idx = np.arange(0, self._num_examples)

because np.arrange() requires int arguments.

As a quick fix, try swapping

self._num_examples = data.shape[0]

to

self._num_examples = data.shape[0].value

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[TensorFlow] TypeError: unsupported operand type(s) for /: ‘Dimension‘ and ‘int‘ 的相关文章

随机推荐