【问题标题】:How to calculate mean of each slice in tensorflow tensor?如何计算张量流张量中每个切片的平均值?
【发布时间】:2018-10-24 02:15:32
【问题描述】:

我有一堆图像,张量形状=(?, 64, 64)。我正在尝试对每个图像应用蒙版,获取蒙版内像素的平均值,并与使用不同蒙版计算的平均值进行比较。我会用它来比较均方误差。通常,我会通过循环切片来计算这个,但 tensorflow 不允许循环。任何建议如何做到这一点?

for l in range(NumberOfExams): 
I = images[l,:,:]
    meansRef[l] = I[referenceMasks[l,:,:]]
    meansOut[l] = I[calculatedMasks[l,:,:]]

MSE = np.mean((meansRef - meansOut)**2/meansRef**2)

我尝试使用 tf.boolean_mask,它可以根据所有 referenceMask 和计算的Mask 为我提供平均值,但到目前为止,我还不清楚如何使用这种或其他 tensorflow 方法获得每个图像的平均值。

非常感谢。

【问题讨论】:

  • 你不能为此使用卷积吗? IE。将蒙版用作“过滤器”并将其卷积在图像上。
  • 卷积很有意义。试图弄清楚如何构图 - 图像和计算的蒙版都是 [batch_size,height,width,1]。过滤例如tf.nn.conv2d 应该是 [height,width,channel_in,channel_out]。我试图将计算掩码重塑为 [height,width,batch_size,batch_size] 旨在获得 [1,1,batch_size] 输出,但它似乎不起作用。另一个问题是 batch_size 在技术上是无,所以我不确定我可以使用“-1”重塑它: tf.nn.conv2d(images,tf.reshape(calculatedMasks,[xsze,ysze,-1,-1 ]),stride=1,padding='VALID')
  • 我已经弄清楚维度 = 无问题 - 可以使用 tf.shape(images)[0]。由于需要使用整批掩码,我目前最好的猜测是假设一批中的图像是通道:imgReshape = tf.reshape(images,[1,xszeysze,-1]) kernel = tf. reshape(masks,[xszeysze,tf.shape(images)[0],1]) y_slice_means = tf.nn.conv1d(img,kernel,stride=1,padding='VALID')。这给出了 (1,1,batch_size) 的合理输出尺寸,但平均值是错误的。我不太确定 conv 函数如何使用 channels_in/channels_out - 我怀疑这是问题
  • 如果您的图像是 [batch, h, w, 1] 形状为 [h, w, 1, 1] 且 padding=valid 的过滤器应该给您一个 [batch, 1, 1, 1 ] 结果。
  • @Alexandre Passos 对,但建议是使用这批口罩作为“过滤器”。即过滤器形状不会是 [h, w, 1, 1],而是类似于 [h, w, batch, 1]。但是,与它卷积会给出所有相等的值,而不是差异 mean(Image[ReferenceMask]) - mean(Image[calculatedMask]) 根据需要。

标签: python tensorflow neural-network


【解决方案1】:

可以使用tf.map_fn 来比较每个图像的蒙版均值。这将返回批量中每个图像的任意操作的结果,本质上允许循环:

所以:

for l in range(NumberOfExams): 
I = images[l,:,:]
    meansRef[l] = I[referenceMasks[l,:,:]]
    meansOut[l] = I[calculatedMasks[l,:,:]]

MSE = np.mean((meansRef - meansOut)**2) 

可以这样做(可以使用清理):

calculatedMasksInf = tf.where(calc_mask > 0.5,Ex,-np.inf * tf.ones_like(calc_mask ))
referenceMasksInf = tf.where(ref_mask > 0.5, Ex, -np.inf * tf.ones_like(ref_mask ))

stiff_means_calculated = tf.map_fn(lambda frame: tf.reduce_mean(tf.boolean_mask(frame,tf.logical_not(tf.is_inf(frame)))), calculatedMasksInf)
stiff_means_reference = tf.map_fn(lambda frame: tf.reduce_mean(tf.boolean_mask(frame,tf.logical_not(tf.is_inf(frame)))), referenceMasksInf)

SqErr = (stiff_means_calculated - stiff_means_reference) ** 2
MSE = tf.reduce_mean(tf.boolean_mask(SqErr,tf.logical_not(tf.is_nan(SqErr))))

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 2017-12-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    相关资源
    最近更新 更多