【问题标题】:How to manipulate the trainable tensor multiply operation in keras?如何在 keras 中操作可训练的张量乘法运算?
【发布时间】:2019-09-30 02:49:25
【问题描述】:

我倾向于建立一个模型,模型的一个输入是一个形状为(?, 29, 64) 的张量。 这是我模型代码中的定义:

history_topics = Input(shape=(29, 64, ), name = 'history')

然后我将其转置为形状为(?,64,29) 的新张量

history_topics_trans = Lambda(lambda x: K.tf.transpose(x,perm=[0,2,1]))(history_topics)

然后,我想初始化一个名为da的新可训练张量,形状为(5, 64),并将da乘以history_topics_trans得到 一个新的张量,形状为(?,5,29)

那么如何实现呢?谢谢。

【问题讨论】:

  • 欢迎来到 StackOverflow 陈亚楠!

标签: python tensorflow keras


【解决方案1】:

您可以简单地为此使用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>]

【讨论】:

  • 谢谢。 history_topics_proj = Dense(5, use_bias=False, name='proj')(history_topics)
  • 名为'proj'的密集层的形状是什么,是形状为(64, 5)的张量吗?
  • 你好亚南。图层本身没有形状。它是一个包含零个或多个权重的对象,每个权重都有一个形状。 Dense 层有一个权重矩阵(在本例中为 64x5),有时还有一个偏置向量(在本例中为无,因为 use_bias=False)。此外,当该层处理一些输入时,它会输出一些具有形状的东西。在这种情况下,输入是 3D,形状为 [m, 29, 64],其中 m 是批量大小。输出是该输入与权重矩阵相乘的结果,对于批次中的每个实例,以及每个主题。输出形状:[m, 29, 5]。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
相关资源
最近更新 更多