InvalidArgumentError:输出形状的内部尺寸必须匹配更新形状的内部尺寸
Posted
技术标签:
【中文标题】InvalidArgumentError:输出形状的内部尺寸必须匹配更新形状的内部尺寸【英文标题】:InvalidArgumentError: Inner dimensions of output shape must match inner dimensions of updates shape 【发布时间】:2021-08-11 15:00:55 【问题描述】:我正在尝试在 keras 中实现 SPL 损失。我需要做的很简单,我会用 numpy 写来解释我需要什么:
def spl_loss(y_true, y_pred, lmda):
# compute any arbitrary loss function
L = categorical_cross_entropy(y_true, y_pred)
# set to zero those values with an error greater than lambda
L[L>lmda] = 0
return L
我正在尝试实现它following this tutorial,但在将值设置为零所需的步骤时遇到了麻烦。
目前我有以下代码:
def spl_loss(lmda, loss_fn):
def loss(y_true, y_pred):
# compute an arbitrary loss function, L
loss_value = loss_fn(y_true, y_pred) # tensor of shape (64,)
# get the mask of L greater than lmda
mask = tf.greater( loss_value, tf.constant( float(lmda) ) ) # tensor of shape (64,)
# compute indexes for the mask
indexes = tf.reshape(tf.where(mask), [-1]) # tensor of shape (n,); where n<=64
# set to zero values on indexes
spl_loss_value = tf.tensor_scatter_nd_update(loss_value, indexes, tf.zeros_like(loss_value, dtype=loss_value.dtype) ) # this line gives the error
return spl_loss_value
return loss
根据docs,tensor_scatter_nd_update
操作应该执行赋值操作,但是失败并出现以下错误:
spl_loss_value = tf.tensor_scatter_nd_update(loss_value, indexes, tf.zeros_like(loss_value, dtype=loss_value.dtype) )
/usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper **
return target(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/array_ops.py:5512 tensor_scatter_nd_update
tensor=tensor, indices=indices, updates=updates, name=name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/ops/gen_array_ops.py:11236 tensor_scatter_update
_ops.raise_from_not_ok_status(e, name)
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py:6862 raise_from_not_ok_status
six.raise_from(core._status_to_exception(e.code, message), None)
<string>:3 raise_from
InvalidArgumentError: Inner dimensions of output shape must match inner dimensions of updates shape. Output: [64] updates: [64] [Op:TensorScatterUpdate]
我在colab中运行,here你可以试试。
我尝试了几种重新形状,因为我知道这是预期形状与获得形状的问题,但我找不到方法。这是怎么回事?
提前致谢
【问题讨论】:
【参考方案1】:您收到此错误的原因是tf.tensor_scatter_nd_update
中的indices
至少需要两个轴,或者需要填充tf.rank(indices) > = 2
。 2D
中indices
的原因(在scaler更新中)是为了保存两个信息,一个是更新的长度(num_updates)和索引向量的长度强>。有关这方面的详细概述,请查看以下答案:Tensorflow 2 - what is 'index depth' in tensor_scatter_nd_update?。
这是tensorflow中SPL loss的正确实现。
def spl_loss(lmda):
def loss(y_true, y_pred):
# compute an arbitrary loss function, L
loss_value = keras.losses.sparse_categorical_crossentropy(y_true, y_pred)
# get the mask of L greater than lmda
mask = tf.greater( loss_value, tf.constant(float(lmda) ) )
# compute indexes for the mask
indexes = tf.where(mask) # tensor of shape (n,); where n<=64
updates = tf.reshape(tf.zeros_like(indexes, dtype=tf.float32), [-1])
# scaler update check
num_updates, index_depth = indexes.shape.as_list()
assert updates.shape == [num_updates]
assert index_depth == tf.rank(loss_value)
# print()
# print('A', tf.reshape(tf.where(mask), [-1])[:10].numpy())
# print('B', tf.where(mask).numpy()[:10])
# print('Ranks: ', tf.rank(loss_value).numpy(),
# tf.rank(indices).numpy(),
# tf.rank(updates).numpy())
# print('Shape: ', loss_value.shape, indexes.shape, updates.shape)
# set to zero values on indexes
spl_loss_value = tf.tensor_scatter_nd_update(loss_value, indexes, updates )
return spl_loss_value
return loss
...
model.compile(optimizer="adam", loss=spl_loss(lmda=2.), run_eagerly=True)
...
参考:tf.tensor_scatter_nd_update
【讨论】:
以上是关于InvalidArgumentError:输出形状的内部尺寸必须匹配更新形状的内部尺寸的主要内容,如果未能解决你的问题,请参考以下文章
InvalidArgumentError:不兼容的形状:[29] 与 [29,7,7,2]
自定义损失函数返回 - InvalidArgumentError:第二个输入必须是标量,但它具有形状 [64]
InvalidArgumentError:找到 2 个根错误。 Tensorflow 文本分类模型中的不兼容形状
InvalidArgumentError:无法将张量添加到批次:元素数量不匹配。形状是:[张量]:[4],[批次]:[5] [Op:IteratorGetNext]
InvalidArgumentError:重塑的输入是一个178802值的张量,但请求的形状有89401
keras 分割 InvalidArgumentError:不兼容的形状:[32,256,256,3] 与 [32,256,256,4]