TensorFlow 模型中的矩阵乘法

问题描述 投票:0回答:2

我想在 TF 模型中使用矩阵乘法。我的模型是一个输入形状 = (1,9) 的神经网络。我想自己得到这个向量的乘积(即我想得到一个矩阵乘积等于转置输入向量本身的乘积,所以它的形状等于(9,9))。

代码示例:

inputs = tf.keras.layers.Input(shape=(1,9))
outputs = tf.keras.layers.Dense(1, activation='linear')(tf.transpose(inputs) @ inputs)
    
model = tf.keras.Model(inputs, outputs)

adam = keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)

model.compile(optimizer=adam, loss='mse', metrics=['mae'])

但是我对这种结果的形状有疑问。对于上面的代码,我得到了下一个架构:

如果我理解正确,输入层中的第一维(无)对应于输入数据批次的大小。当我使用转置操作时,它适用于这个形状的所有维度。所以我在转置和乘法后得到形状为 (9,1,9) 的结果。但我认为,这是不正确的。因为我想批量获取所有向量的转置输入向量的乘积(即我想要得到的结果的正确形状是(无,9、9))。

将这个乘积作为模型的输入(在这个模型之外计算这个乘法)是不合适的。因为我想在我的模型中有原始输入向量和乘法的结果来做一些操作(上面的架构不完整并作为例子使用)。

我怎样才能得到正确的结果?如果我们想将此操作批量应用于所有向量(矩阵),那么在 TF 中乘以矩阵和向量的正确方法是什么?

python tensorflow neural-network tensorflow2.0 matrix-multiplication
2个回答
1
投票

尝试

tf.linalg.matmul
,因为它会尊重批量维度:

import tensorflow as tf

inputs = tf.keras.layers.Input(shape=(1,9))
outputs = tf.keras.layers.Dense(1, activation='linear')(tf.linalg.matmul(inputs, inputs, transpose_a=True))
    
model = tf.keras.Model(inputs, outputs)

adam = keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)

model.compile(optimizer=adam, loss='mse', metrics=['mae'])
print(model.summary())
Model: "model_3"
__________________________________________________________________________________________________
 Layer (type)                   Output Shape         Param #     Connected to                     
==================================================================================================
 input_5 (InputLayer)           [(None, 1, 9)]       0           []                               
                                                                                                  
 tf.linalg.matmul_3 (TFOpLambda  (None, 9, 9)        0           ['input_5[0][0]',                
 )                                                                'input_5[0][0]']                
                                                                                                  
 dense_4 (Dense)                (None, 9, 1)         10          ['tf.linalg.matmul_3[0][0]']     
                                                                                                  
==================================================================================================
Total params: 10
Trainable params: 10
Non-trainable params: 0
__________________________________________________________________________________________________
None

-1
投票

我从你的问题中读到,在 NN 内部进行矩阵乘法,其中数字乘法很容易! 它是一个序列到一个序列,我们有很多例子(那些带有目标乘法字典的句子输入) 不需要指定形状输出,但序列输出仍然是答案!

  1. 使用 TF.where 或更大! 输入:
    array_1 = [ 0, 1, 1, 0 ]
    array_2 = np.concatenate((array_1, array_1), axis = 0)
    temp = [ 0, 1, 1, 0 ]
    
    print( np.asarray( tf.where([ temp == [0, 1, 1, 0] ], array_2, 0 ) ) )
    
    input('...')

输出:

[0 1 1 0 0 1 1 0]
  1. 使用 tfa.seq2seq.BasicDecoder 求和 输入:
    index = 1
    next_char = tf.strings.substr(
        input_word, index, len(input_word[0].numpy()) - index, unit="UTF8_CHAR", name=None
    )
    output, state, lengths = decoder(
        next_char, start_tokens=start_tokens, end_token=end_token, initial_state=initial_state)
    
    print('next_char[0].numpy(): ' + str(next_char[0].numpy()))

输出:

input_word[0].numpy() length: tf.Tensor([b'Gl\xc3\xbccklicherweise '], shape=(1,), dtype=string)
input_word[0].numpy() length: 18
next_char[0].numpy(): b'Gl\xc3\xbccklicherweise '
next_char[0].numpy(): b'l\xc3\xbccklicherweise '
next_char[0].numpy(): b'\xc3\xbccklicherweise '
next_char[0].numpy(): b'cklicherweise '
next_char[0].numpy(): b'klicherweise '
next_char[0].numpy(): b'licherweise '

sum = G + L + L + ...
  1. 模型乘法,你使用密集输入,输出是所需目标的序列,如图所示。
© www.soinside.com 2019 - 2024. All rights reserved.