Skip to main content
 首页 » 编程设计

python之为什么 Tensorflow 不覆盖 Tensors 的 __eq__

2024年10月01日29kuangbin

Tensorflow 覆盖了 Tensor 类的多个运算符,including __lt__, __ge__等

但是,__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 数组不同?

代码示例:

a = tf.constant([1,2]) 
b = tf.constant([3,4]) 
a == b 
>>> False 
a < b 
>>> <tf.Tensor 'Less:0' shape=(2,) dtype=bool> 

另一方面,对于 numpy:

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

请您参考如下方法:

张量确实实现了__eq__,但是the implementation only tests for identity .我找到了 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__ 方法的对象(如果要将此类对象用作字典中的键则需要),必须为两个相等的对象生成相同的散列值;查看__hash__ method :

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

但是广播会为具有不同哈希值的对象生成“真实的”张量对象。

(关于 __eq__ 会破坏 bool 测试的推测是错误的; bool 测试使用 __bool__ ,张量确实实现了)。

如果需要对张量进行逐元素相等性测试,可以使用 tf.equal()和 tf.not_equal()功能。