【问题标题】:tf.boolean_mask(2D, 2D) gives 1D resulttf.boolean_mask(2D, 2D) 给出一维结果
【发布时间】:2019-01-06 06:07:44
【问题描述】:

问题

tf.boolean_mask() 似乎相对简单:它从张量中删除不匹配条件的值。如果掩码的尺寸与目标张量相同,则条件按元素起作用。

使用ret = tf.boolean_mask(src, mask),我发现输出尺寸与输入尺寸不匹配。

src:    Tensor("mul_3:0", shape=(?,?), dtype=int32)
mask:   Tensor("Cast_1:0", shape=(?,?), dtype=int32)
ret:    Tensor("boolean_mask/Gather:0", shape=(?,), dtype=int32)

请注意,(?,)(?,?) 的行为不同,尽管我不确定为什么或如何。


代码

    src = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    src = tf.ones([tf.shape(src)[0], 1], tf.int32) * src

    matrix = tf.ones_like(src, tf.int32)
    matrix = tf.matrix_band_part(matrix, 3, 3) # number for mask is arbitrary
    mask = tf.cast(matrix, tf.bool)

    ret = tf.boolean_mask(tensor=src, mask=mask)

有什么问题?

【问题讨论】:

    标签: python python-3.x tensorflow mask tensor


    【解决方案1】:

    Returns section in the docs

    (N-K+1) 维张量由张量中的条目填充 对应于掩码中的 True 值。

    其中Nsrc 的维度,Kmask 的维度,当N=K 时,返回总是1D,这是你的情况。

    【讨论】:

    • 非常感谢。我会接受这个答案。您对我该如何做我想做的事情有什么建议吗(根据 2D 蒙版过滤 2D 矩阵)?
    • 您可以使用布尔掩码从二维数组中删除零,但不能保证结果仍然是二维的。例如使用[[1,0],[2,3]],您将在删除零后得到[1,2,3],但它不适合作为二维数组或矩阵。
    • 嗯。我怎样才能从 [[1,0],[2,3]] 转到 [[1],[2,3]]?我尝试使用tf.gather(src, tf.not_equal(src, 0)))...这样的东西有用吗?
    • 我怀疑你是否能以这种方式拥有一个张量(通常是平方的)。例如,tf.constant([[1],[2,3]]) 给出了一个错误。
    猜你喜欢
    • 2016-01-30
    • 2018-11-16
    • 2018-12-14
    • 2017-11-10
    • 2016-12-13
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    相关资源
    最近更新 更多