为什么Tensorflow不能覆盖张量的eq?

2024-05-03 03:42:45 发布

您现在位置:Python中文网/ 问答频道 /正文

Tensorflow重写Tensor类、including ^{}, ^{}等的多个运算符

但是,__eq__seems to be conspicuously absent的实现:

ops.Tensor._override_operator("__lt__", gen_math_ops.less)
ops.Tensor._override_operator("__le__", gen_math_ops.less_equal)
ops.Tensor._override_operator("__gt__", gen_math_ops.greater)
ops.Tensor._override_operator("__ge__", gen_math_ops.greater_equal)

为什么tensorflow的张量的==与numpy数组的行为不一样?在

代码示例:

^{pr2}$

另一方面,对于numpy:

a = np.asarray([1,2])
b = np.asarray([3, 4])
a == b
>>> array([False, False], dtype=bool)

Tags: numpyfalsetensorflownpmathequaloperatorops
1条回答
网友
1楼 · 发布于 2024-05-03 03:42:45

{1}实现this GitHub issue,这解释了为什么张量测试身份而不广播:

This may be a complication of fact that tensors can be used as keys in dictionaries, which I believe use == to find the matching object with the same hash

注释器是正确的;如果__eq__被重载为广播,那么您就不能在字典中使用张量作为键。定义__hash__方法的对象(如果要将此类对象用作字典中的键,则必需),必须为两个相等的对象生成相同的哈希值;请参见^{} method

The only required property is that objects which compare equal have the same hash value

但是广播将为具有不同哈希值的对象生成一个“真”张量对象。在

(关于__eq__将破坏布尔测试的推测是错误的;布尔测试使用^{},张量确实实现了这一点)。在

如果需要对张量进行元素相等性测试,可以使用^{}^{}函数。在

相关问题 更多 >