锯齿张量作为LSTM的输入

了解锯齿张量以及如何在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层输入形状不匹配,以下是我所做的修改,并附有一些注释。


# xx应该为3维以适合LSTMxx = tf.ragged.constant([                        [[0.1, 0.2]],                        [[0.4, 0.7 , 0.5, 0.6]]                        ])"""标签表示为OneHotEncoding,所以你应该使用CategoricalCrossentropy而不是SparseCategoricalCrossentropy"""yy = np.array([[0, 0, 1], [1,0,0]])# 对于锯齿张量,获取最大序列长度max_seq = xx.bounding_shape()[-1]mdl = tf.keras.Sequential([    # 输入层形状为[任意, 最大序列长度]                          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')])# CategoricalCrossentropymdl.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)

Related Posts

关于k折交叉验证的直观问题

我在使用交叉验证检查预测能力时遇到了一些直观问题,我认…

调整numpy数组大小以使用sklearn的train_test_split函数?

我正在尝试使用sklearn中的test_train_…

如何转换二维张量和索引张量以便用于torch.nn.utils.rnn.pack_sequence

我有一组序列,格式如下: sequences = to…

模型预测值的含义是什么?

我在网上找到一个数字识别器的CNN模型并进行了训练,当…

如何告诉SciKit的LinearRegression模型预测值不能小于零?

我有以下代码,尝试根据非价格基础特征来估值股票。 pr…

在PyTorch中,如何将与cuda()相关的代码转换为CPU版本?

我有一些现有的PyTorch代码,其中包含cuda()…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注