了解锯齿张量以及如何在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)