如何在稀疏张量上做tf.not_equal()?

时间:2018-04-25 23:46:24

标签: python tensorflow

我得到TypeError: Failed to convert object。有没有办法在稀疏张量上做tf.not_equal()或等价?它必须保持稀疏;转换为密集不允许。

2 个答案:

答案 0 :(得分:0)

我认为你必须独立操作指数/价值。

import numpy as np
import tensorflow as tf


def sparse_not_equal(sparse_tensor, value):
    indices = sparse_tensor.indices
    values = sparse_tensor.values
    condition = tf.squeeze(tf.where(tf.not_equal(values, 2)), axis=-1)
    indices = tf.gather(indices, condition)
    values = tf.ones(shape=(tf.shape(indices)[0],), dtype=tf.bool)
    return tf.SparseTensor(
      indices,
      values,
      sparse_tensor.dense_shape)


def get_sparse():
    vals = tf.constant([2, 3, 4, 2])
    indices = tf.constant(np.array([[1], [4], [5], [10]]))
    dense_shape = [16]
    return tf.SparseTensor(indices, vals, dense_shape)


sparse_tensor = get_sparse()
sparse_filtered = sparse_not_equal(sparse_tensor, 2)


with tf.Session() as sess:
    s = sess.run(sparse_filtered)

print(s)

答案 1 :(得分:0)

假设您想要比较两个稀疏张量,并且其中包含数字,我认为最简单的方法是从另一个中减去一个,并使{ "_id": { "$oid": "5a27b4d4c14826880321c8e4" }, "ope": "ptp", "shopId": "121", "ptst": 6, "timestampField": 1512554442 } 将非零值保持为“真”。只有当你想要将稀疏张量与常数进行比较时,DomJack的答案才有效,但是tf.sparse_retain()就像下面的函数tf.sparse_retain()一样容易。 (请注意,这不是一个准确的 not_equal 操作,因为它只测试不等式的现有值。由于稀疏张量的未列出元素为零,如果我们要比较的常量本身不是零,那么矩阵的其余部分也应该被标记为不相等。当使用sparse_not_equal_to_constant()参数转换回密集时,最好这样做,但考虑矩阵具有值的起始位置。)用于比较的经过测试的代码两个稀疏张量,包括将它与常数进行比较的函数:

default_value

输出:

  

[[假错误真假]
   [假假假真假]
   [假错假真假]
   [假错假错]
   [假假假假]]

正如所料。