【问题标题】:how to apply "or" operation to tensor with float32 type?如何对 float32 类型的张量应用“或”操作?
【发布时间】:2020-08-21 12:15:37
【问题描述】:

我想合并两个稀疏的 Bird-Eye-View 特征图。

它们在大多数像素上的值为 0。并且它们是对齐的,因此对应的像素代表相同的位置,这使得合并合理。

  • 以两个张量为例:
net1=[
[0,   0.2, 0], 
[0,   0.1, 0],
[0,   0  , 0]]

net2_aligned=[
[0.3, 0  , 0], 
[0,   0.4, 0],
[0,   0  , 0]]
  • 只有当 net1 的像素值为 0 时,才会被 net2_aligned 中对应的像素值替换。

    • (如果您对两个张量中都有值的像素使用最大/均值,也可以接受)
  • 即我们假设在 float32 的“或运算”之后得到这个结果:

net_result=[
[0.3, 0.2, 0], 
[0  , 0.1, 0],
[0  , 0  , 0]]

tensorflow中有这样的方法吗?我正在考虑是否可以使用特殊的 1x1 卷积来完成。

【问题讨论】:

    标签: python image tensorflow keras conv-neural-network


    【解决方案1】:

    你可以这样做:

    import tensorflow as tf
    
    net1 = tf.convert_to_tensor([[0,   0.2, 0], 
                                 [0,   0.1, 0],
                                 [0,   0  , 0]])
    net2_aligned = tf.convert_to_tensor([[0.3, 0  , 0], 
                                         [0,   0.4, 0],
                                         [0,   0  , 0]])
    
    bools = (net1==0) # Gives a boolean tensor
    bools = tf.cast(bools, tf.float32) # Converts the boolean tensor to float32 dtype, so you can multiply it with net2_aligned 
    
    net_result = net1 + bools*net2_aligned # This is possible thanks to the particularity of your problem, as each time you want to replace a net1 value by one of net2_aligned, it is equal to 0. Thus the sum.
    

    输出:

    <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
    array([[0.3, 0.2, 0. ],
           [0. , 0.1, 0. ],
           [0. , 0. , 0. ]], dtype=float32)>
    

    如果您想替换每个等于net1 的值,例如0.2,您可以这样做:

    bools = tf.cast(net1==0.2, tf.float32)
    net_result = net1*(1-bools) + bools*net2_aligned
    

    【讨论】:

    • 当涉及到 4-D 张量时,布尔值不能很好地工作。 ValueError: Shapes () and (?, 63, 126, 80) are incompatible。你知道在 4-D 情况下改进bools = (net1==0) 的方法吗?
    • 你确定吗?它非常适合我,你可以尝试使用张量 [[[[1,0],[0,2]],[[4,5],[5,0]]],[[[0,0],[1,1]],[[8,0],[0,0]]]] (我知道很丑)。你不认为问题来自你的张量吗?由于您的第一个维度似乎没有定义(因为有一个?)。
    • 我使用batch size=4进行训练,因此第一个维度是未知的。我检查了角落像素的值:它是一个浮点数,在一半的探针中等于 0。所以重点是bools = (net1==0) 未知维度为net1 的行
    【解决方案2】:

    您可以为此使用 numpy:

    import numpy as np
    
    net1=np.array([
    [0,   0.2, 0], 
    [0,   0.1, 0],
    [0,   0  , 0]])
    
    net2_aligned=np.array([
    [0.3, 0  , 0], 
    [0,   0.4, 0],
    [0,   0  , 0]])
    
    result = np.copy(net1)
    mask = net1 == 0
    
    result[mask] = net2_aligned[mask]
    print(result)
    

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2021-07-09
      • 2020-03-30
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多