您可以简单地为此使用Dense 层。如果不需要偏置项,可以设置use_bias=False。
import tensorflow as tf
from tensorflow import keras
K = keras.backend
history_topics = keras.layers.Input(shape=(29, 64), name='history')
history_topics_proj = keras.layers.Dense(5, use_bias=False)(history_topics)
history_topics_trans = keras.layers.Lambda(
lambda x: tf.transpose(x, perm=[0,2,1]))(history_topics_proj)
model = keras.models.Model(inputs=[history_topics], outputs=[history_topics_trans])
model.summary()
这是输出:
Model: "model"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
history (InputLayer) [(None, 29, 64)] 0
_________________________________________________________________
dense_2 (Dense) (None, 29, 5) 320
_________________________________________________________________
lambda_2 (Lambda) (None, 5, 29) 0
=================================================================
Total params: 320
Trainable params: 320
Non-trainable params: 0
_________________________________________________________________
您可以像这样查看Dense 层的权重:
dense_layer = keras.layers.Dense(5, use_bias=False)
... # use the layer, so its weights get constructed
[weights] = dense_layer.get_weights()
如果您想要偏见条款,请不要设置use_bias=False。在这种情况下,get_weights() 将返回权重矩阵和偏置向量:
dense_layer = keras.layers.Dense(5)
... # use the layer, so its weights get constructed
[weights, bias] = dense_layer.get_weights()
一个 Keras 层是懒惰构建的,第一次实际使用它。如果您尝试在构建权重之前获取权重,您将得到一个空列表。要强制创建权重,可以在某些数据上调用图层,或者直接调用build() 方法:
dense_layer.build(input_shape=[None, None, 64])
请注意,input_shape 参数应称为 batch_input_shape,因为它包含输入的完整形状,包括批次维度。
get_weights() 方法返回一个 NumPy 数组。如果您喜欢获取符号张量,例如直接使用模型中的权重,则应使用 variables 实例变量:
>>> dense_layer.variables
[<tf.Variable 'kernel_5:0' shape=(64, 5) dtype=float32>]