我想在Tensorflow/Keras中创建一个自定义层。我创建了一个注意力层,它被下面的Deepset层调用。
注意力层:
class Attention(tf.keras.Model):def __init__(self, input_shape): super(Attention, self).__init__() in_features=input_shape 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,use_bias=True,trainable=True)) query.add(tf.keras.layers.Dense(small_in_features,activation="tanh",trainable=True)) self.query= query self.key = tf.keras.layers.Dense(small_in_features,use_bias=True,trainable=True)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,perm=[0,2,1]) 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
Deepset层:
class DeepSetLayer(tf.keras.Model):def __init__(self, input_shape, out_features, attention, normalization, second_bias): """ DeepSets单层 :param in_features: 输入的特征数量 :param out_features: 输出的特征数量 :param attention: 是否使用注意力 :param normalization: 归一化方法 - 'fro' 或 'batchnorm' :param second_bias: 在第二个conv1d层中使用偏置 """ super(DeepSetLayer, self).__init__() in_features=input_shape[-1] self.attention = None if attention: self.Attention = Attention(in_features) self.layer1 = tf.keras.layers.Conv1D(in_features, out_features, 1,trainable=True) self.layer2 = tf.keras.layers.Conv1D(in_features, out_features, 1, use_bias=second_bias,trainable=True) self.normalization = normalization if normalization == 'batchnorm': self.bn = tf.keras.layers.BatchNormalization(out_features,trainable=True)def call(self, x): #tf.shape(x) = (B,C,N) # 注意力 if self.attention: x_T = tf.transpose(x,perm=[0,2,1]) # B,C,N -> B,N,C x = self.layer1(x) + self.layer2(tf.transpose(self.Attention(x_T),perm=[0,1,2])) print(x) else: x = self.layer1(x) + self.layer2(x - tf.math.reduce_mean(x,axis=2,keepdims=True)) # 归一化 if self.normalization == 'batchnorm': x = self.bn(x) else: x=tf.transpose(x,perm=[0,2,1]) print(tf.norm(x,axis=1, keepdims=True,)) print(x) x = x / tf.norm(x, axis=1, keepdims=True) # BxCxN / Bx1xN return x
现在我将使用这些自定义层构建一个模型:
phi=tf.keras.models.Sequential()phi.add(tf.keras.layers.Input((256,10)))phi.add(DeepSetLayer((256,10),25,True,True,True))
但是当我使用phi.summary()
调用层结构时,我得到了以下无法理解的错误:
ValueError: Weights for model sequential_84 have not yet been created. Weights are created when the Model is first called on inputs or `build()` is called with an `input_shape`.
我不确定我哪里做错了,但似乎我的层没有正确构建。
我该如何修复这个问题?
此外,输入形状为Inputshape=(None,256,10),但我的Deepset层将其变成了(None,232,10),这不是我想要的结果。我不明白为什么会减少一个维度。
这是在哪里发生的?
回答:
Q1.
在调用summary()之前尝试传递任何虚拟数据。错误消息的意思是它还不知道模型的某些部分,或者某些权重会在你实际使用模型处理实际数据时创建。
Q2.
Conv1D层的第一个参数是过滤器的数量(将是输出的通道数量),第二个参数是每个过滤器的大小。
在没有填充的情况下(在keras中,padding=’valid’),如果输入的形状是(B,N,C),输出形状将是
(B, (N-kernel_size+1)//(stride) , filters)
因此,在你的情况下,(256 – 25 + 1) // 1 = 232
并且你对filters的参数是input_shape[-1],即C(在这种情况下是10)