Warm tip: This article is reproduced from serverfault.com, please click

python-TensorFlow层将2D矩阵转换为一定长度的向量

(python - TensorFlow layer that converts a 2D matrix to a vector of certain length)

发布于 2020-11-28 14:44:00

我正在尝试建立一个神经网络,以矩阵的形式接收数据并输出一个矢量,但是我不知道该使用什么层来执行该操作。我的输入的形状为(10,4),而我想要的输出的形状为(3,)。我当前的模型如下:

model = tf.keras.Sequential([
    tf.keras.layers.Dense(256,activation="relu"),
    tf.keras.layers.Dense(256,activation="relu"),
    tf.keras.layers.Dense(1),
])

这至少会导致向量而不是矩阵,但是它具有(10,)而不是(3,)。我可能可以找到一种将其减少到(3,)的方法,但是我怀疑我是否正在使用这种方法做正确的事情。

Questioner
Lukas Gradl
Viewed
0
Akshay Sehgal 2020-11-28 22:54:12

假设你(10,4)是一个不代表10个长度序列的矩阵(你将需要一个LSTM)或一个图像(你将需要一个2D CNN),那么你可以简单地flatten()将输入矩阵传递给下几个稠密层,如以下。

from tensorflow.keras import layers, Model

inp = layers.Input((10,4)) #none,10,4
x = layers.Flatten()(inp)  #none,40
x = layers.Dense(256)(x)   #none,256
out = layers.Dense(3)(x)   #none,3

model = Model(inp, out)
model.summary()
Layer (type)                 Output Shape              Param #   
=================================================================
input_43 (InputLayer)        [(None, 10, 4)]           0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 40)                0         
_________________________________________________________________
dense_82 (Dense)             (None, 256)               10496     
_________________________________________________________________
dense_83 (Dense)             (None, 3)                 771       
=================================================================
Total params: 11,267
Trainable params: 11,267
Non-trainable params: 0