Python tensorflow条件:检查张量内的值是否为零或更大
如果我有以下张量:Python tensorflow条件:检查张量内的值是否为零或更大,python,tensorflow,Python,Tensorflow,如果我有以下张量: pmi=tf.constant([[1.5,0.0,0.0],[0.0,0.0,2.9],[1.001,5,1]]) 我希望有一个对应的张量Fpmi(或定标器),这样当PMI张量中的元素大于0时,Fpmi中的元素应该是1,当PMI中的元素=0时,Fpmi中的元素=0.0005 如果您有任何建议,我将不胜感激。使用,您可以有条件地从两个常量张量返回元素: a = tf.constant(1, shape=pmi.shape, dtype=tf.float32) b = tf.
pmi=tf.constant([[1.5,0.0,0.0],[0.0,0.0,2.9],[1.001,5,1]])
我希望有一个对应的张量Fpmi(或定标器),这样当PMI张量中的元素大于0时,Fpmi中的元素应该是1,当PMI中的元素=0时,Fpmi中的元素=0.0005
如果您有任何建议,我将不胜感激。使用,您可以有条件地从两个常量张量返回元素:
a = tf.constant(1, shape=pmi.shape, dtype=tf.float32)
b = tf.constant(0.0005, shape=pmi.shape, dtype=tf.float32)
tf.where(tf.greater(pmi, 0), a, b).eval()
#array([[ 1.00000000e+00, 5.00000024e-04, 5.00000024e-04],
# [ 5.00000024e-04, 5.00000024e-04, 1.00000000e+00],
# [ 1.00000000e+00, 1.00000000e+00, 1.00000000e+00]], dtype=float32)
如果要保留不大于阈值的原始值,请将tf.where的第二个参数替换为原始数据
data = tf.random.uniform(shape=(2, 2))
threshold = 0.4
fill_value_if_bigger = tf.constant(0.5, shape=data.shape, dtype=tf.float32)
replaced = tf.where(tf.greater(data, threshold), fill_value_if_bigger, data).numpy()