我已经尝试了几个小时才能成功完成此任务。
我想tf.to_categorical
使用tf.data.Dataset
API将数据拆分为X和Y(然后将Y传递给),但是不幸的是,我每次尝试使用它的尝试都以某种错误告终。
如何使用tf.data.Dataset
:
tf.to_categorical
。我目前的尝试:
def map_sequence():
for sequence in input_sequences:
yield sequence[:-1], keras.utils.to_categorical(sequence[-1], total_words)
dataset = tf.data.Dataset.from_generator(map_sequence,
(tf.int32, tf.int32),
(tf.TensorShape(title_length-1), tf.TensorShape(total_words)))
但是,当我尝试使用以下代码训练模型时:
inputs = keras.layers.Input(shape=(title_length-1, ))
x = keras.layers.Embedding(total_words, 32)(inputs)
x = keras.layers.Bidirectional(keras.layers.LSTM(64, return_sequences=True))(x)
x = keras.layers.Bidirectional(keras.layers.LSTM(64))(x)
predictions = keras.layers.Dense(total_words, activation='softmax')(x)
model = keras.Model(inputs=inputs, outputs=predictions)
model.compile('Adam', 'categorical_crossentropy', metrics=['acc'])
model.fit(dataset)
我收到此错误: ValueError: Shapes (32954, 1) and (65, 32954) are incompatible
我认为您有一个与此问题类似的问题。Keras期望您给出的用于生产批次的数据集,而不是单个示例。由于您一次给它两个一维向量,因此Keras解释说,每个向量都是一批具有一个特征的示例。因此,X
具有65个元素的数据将被解释为一批具有单个特征(65x1张量)的65个示例。这样可以将批量大小固定为65。模型的输出将具有65x32,954的形状(我假设是的值total_words
)。但是Y
,具有32,954个元素的向量再次被解释为一批具有一个特征(32,954x1张量)的32,954。这两件事不匹配,因此出现错误。您只需通过使用batch
在传递给之前fit
。
无论如何,如果您input_sequences
似乎是一个NumPy数组,则生成数据集的方法并不是很好,因为使用生成器会非常慢。这是执行此操作的更好方法:
def map_sequence(sequence):
# Using tf.one_hot instead of keras.utils.to_categorical
# because we are working with TensorFlow tensors now
return sequence[:-1], tf.one_hot(sequence[-1], total_words)
dataset = tf.data.Dataset.from_tensor_slices(input_sequences)
dataset = dataset.map(map_sequence)
dataset = dataset.batch(batch_size)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句