如何计算一个值在2D张量上出现的次数:UniqueWithCounts仅支持1D张量



我正在学习Tensorflow 2.10,使用Python 3.7.7。

我正在尝试使用教程"Tensorflow - 自定义训练:演练"来使用我自己的损失函数。

这是我的第一个损失函数版本,它有效:

def loss(model, x, y):
output = model(x)
return tf.norm(y - output)

我已经更改为尝试另一个,但它不起作用:

def my_loss(model, x, y):
output = model(x)
# Only valid values for output var are 0.0 and 1.0.
output_np = np.array(output)
output_np[output_np >= 0.5] = 1.0
output_np[output_np < 0.5] = 0.0
# Counts how many 1.0 are on y var.
unique, counts = np.unique(y, return_counts=True)
dict_wmh = dict(zip(unique, counts))  
wmh_count = 0
if 1.0 in dict_wmh:
wmh_count = dict_wmh[1.0]
# Add y and output to get another array.
c = y + output_np
unique, counts = np.unique(c, return_counts=True)
dict_net = dict(zip(unique, counts))
# Counts how many 2.0 are on this new array.
net_count = 0
if 2.0 in dict_net:
net_count = dict_net[2.0]
# Return the different between the number of ones in the label and the network output.
return wmh_count - net_count

但我可以使用它,因为我的新损失函数"中断了梯度磁带记录的梯度链"。

因此,我尝试仅使用Tensorflow Tensor:

def my_loss_tensor(model, x, y):
output = model(x)
# Only valid values for output var are 0.0 and 1.0.
output = tf.math.round(output)
output = tf.clip_by_value(output, clip_value_min=0.0, clip_value_max=1.0)
# Counts how many 1.0 are on y var (WMH mask).
y_ele, y_idx, y_count = tf.unique_with_counts(y)
# Add output to WMH mask.
sum = tf.math.add(output, y)
# Counts how many 2.0 are on the sum.
sum_ele, sum_idx, sum_count = tf.unique_with_counts(sum)
return tf.math.subtract(sum_count[sum_ele == 1.0], y_count[y_ele == 2.0])

x是一个tf.Tensor([[[[...]]]], shape=(1, 200, 200, 1), dtype=float32)y是一个tf.Tensor([[[[...]]]], shape=(1, 200, 200, 1), dtype=float32)

它们是图像(200x200x1).

我收到以下错误:

唯一需要一维矢量。[操作:UniqueWithCounts]

关于如何计算一个值在张量上出现的次数的任何想法?

真实的图像数据在200x200维度上,另外两个在我的CNN上使用。

你可以在损失中使用tf.reshape((方法将其转换为一维向量:

out_flat = tf.reshape(output,[-1])
y_ele, y_idx, y_count = tf.unique_with_counts(out_flat)

最新更新