python - 张量的尺寸不适合
问题描述
我在 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 维输入。
解决方案
推荐阅读
- excel - 循环遍历范围 VBA
- .net - 将新表单添加到项目时未创建 Windows 表单设计器(resx 文件)
- python-3.x - 使用 librosa.resample 后出现“wave.Error:未知格式:3”。librosa 的输出有什么问题吗?
- c# - 为了和并行为了效率
- c# - 表单对话框复制另一个调用它的表单的内容
- c# - 为什么我的实现总是调用同一个派生类?
- jqgrid - jqgrid中的下拉菜单仅在双击时显示
- docker - 如何将 Azure Web 应用程序移动到容器
- reactjs - 酶无法识别我创建的子组件
- excel - 有没有办法以类似于 TextBox_AfterUpdate 的方式检查标签框是否已更新?