首页 > 解决方案 > 张量的尺寸不适合

问题描述

我在 keras 中复制了一个 pytorch 模型,并且遇到了一些问题,以查看额外维度的来源。这是我的代码到目前为止的样子:

class Attention(tf.keras.Model):
def __init__(self, input_shape):
    super(Attention, self).__init__()
    in_features=input_shape[-1]
    small_in_features = max(math.floor(in_features/10), 1)
    self.d_k = small_in_features

    query = tf.keras.models.Sequential()
    query.add(tf.keras.layers.Dense(in_features))
    query.add(tf.keras.layers.Dense(small_in_features,activation="tanh"))
    self.query= query
    
    self.key = tf.keras.layers.Dense(small_in_features)

def call(self, inp):
    # inp.shape should be (B,N,C)
    q = self.query(inp)  # (B,N,C/10)
    k = self.key(inp)     # B,N,C/10
    k = tf.transpose(k)
    print(q)
    print(k)
    x = tf.linalg.matmul(q, k) / math.sqrt(self.d_k)  # B,N,N
    x = tf.nn.softmax(x)  # over rows
    x = tf.transpose(x)
    x = tf.linalg.matmul(x, inp)  # (B, N, C)
    return x

但是,如果我想将它添加到我的顺序模型中,我会收到此错误:

 ValueError: Dimensions must be equal, but are 1 and 256 for '{{node attention_19/MatMul}} = BatchMatMulV2[T=DT_FLOAT, adj_x=false, adj_y=false](attention_19/sequential_36/Identity, attention_19/transpose)' with input shapes: [?,256,1], [1,256,?].

我现在已经打印了我的 'q' 和 'k' 并打印如下:

Tensor("attention_19/sequential_36/Identity:0", shape=(None, 256, 1), dtype=float32)
Tensor("attention_19/transpose:0", shape=(1, 256, None), dtype=float32)

所以它们是 3 维的,其中一个维度是未填充的。我不太明白为什么会发生这种情况。

我怎样才能“删除”额外的维度或使这个自定义层起作用?

注意:原始代码似乎使用 3 维输入,但我想要 2 维输入。

标签: pythontensorflowmachine-learningkeras

解决方案


推荐阅读