Tensorflow 粗糙张量作为LSTM的输入

Tensorflow 粗糙张量作为LSTM的输入,tensorflow,machine-learning,keras,Tensorflow,Machine Learning,Keras,学习参差不齐的张量以及如何将它们与tensorflow一起使用。 我的例子 xx = tf.ragged.constant([ [0.1, 0.2], [0.4, 0.7 , 0.5, 0.6] ]) yy = np.array([[0, 0, 1], [1,0,0]]) mdl = tf.keras.Sequential([ tf.keras

学习参差不齐的张量以及如何将它们与tensorflow一起使用。 我的例子

xx = tf.ragged.constant([
                        [0.1, 0.2],
                        [0.4, 0.7 , 0.5, 0.6]
                        ])
yy = np.array([[0, 0, 1], [1,0,0]])

mdl = tf.keras.Sequential([
    tf.keras.layers.InputLayer(input_shape=[None], batch_size=2, dtype=tf.float32, ragged=True),
    tf.keras.layers.LSTM(64),  
    tf.keras.layers.Dense(3, activation='softmax')
])

mdl.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              optimizer=tf.keras.optimizers.Adam(1e-4),
              metrics=['accuracy'])

mdl.summary()
history = mdl.fit(xx, yy, epochs=10)
错误

Input 0 of layer lstm_152 is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: [2, None]

我不确定我是否能像这样使用参差不齐的张量。我发现的所有示例在LSTM之前都有嵌入层,但我不想创建额外的嵌入层

我建议使用Input图层,而不是InputLayer,您通常不需要使用InputLayer,无论如何,问题是您的输入和LSTM图层输入形状的形状是错误的,这里是我所做的修改,并附有一些注释



我已经尝试过你的解决方案,考虑到可变长度ECG序列的参差不齐张量。我注意到batch_size=1,但在矩阵大小不兼容方面出现了一个错误。似乎下一个序列的长度比上一个序列的长度要长。问题是你能帮我吗?
# xx should be 3d for LSTM
xx = tf.ragged.constant([
                        [[0.1, 0.2]],
                        [[0.4, 0.7 , 0.5, 0.6]]
                        ])

"""
Labels represented as OneHotEncoding so you 
should use CategoricalCrossentropy instade of SparseCategoricalCrossentropy
"""

yy = np.array([[0, 0, 1], [1,0,0]])

# For ragged tensor , get maximum sequence length
max_seq = xx.bounding_shape()[-1]

mdl = tf.keras.Sequential([
    # Input Layer with shape = [Any,  maximum sequence length]                      
    tf.keras.layers.Input(shape=[None, max_seq], batch_size=2, dtype=tf.float32, ragged=True),
    tf.keras.layers.LSTM(64),
    tf.keras.layers.Dense(3, activation='softmax')
])

# CategoricalCrossentropy
mdl.compile(loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
              optimizer=tf.keras.optimizers.Adam(1e-4),
              metrics=['accuracy'])

mdl.summary()
history = mdl.fit(xx, yy, epochs=10)