我已经尝试了几个小时来完成这个任务,但没有成功。
我想使用tf.data.Dataset
API将这些数据分成X和Y(并将Y传递给tf.to_categorical
),就像图片中展示的那样,但不幸的是,每次尝试使用它时都会遇到某种错误。
我该如何使用tf.data.Dataset
来:
- 将每一行分成x和y。
- 使用
tf.to_categorical
将Y转换为分类数据。 - 将数据集分成批次。
- 将数据集输入到我的模型中。
我当前的尝试如下:
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个元素,被解释为一个包含65个示例的批次,每个示例有一个特征(65×1张量)。这将批次大小固定为65。然后,模型的输出形状为65×32,954(我假设这是total_words
的值)。但是你的Y
向量,包含32,954个元素,再次被解释为一个包含32,954个示例的批次,每个示例有一个特征(32,954×1张量)。这两者不匹配,因此出现了错误。你可以通过在传递给fit
之前使用batch
创建一个新的数据集来解决这个问题。
无论如何,如果你的input_sequences
是一个NumPy数组,像看起来的那样,你用来生成数据集的方法并不是很好,因为使用生成器会非常慢。这是一个更好的方法来做同样的事情:
def map_sequence(sequence): # 使用tf.one_hot代替keras.utils.to_categorical # 因为我们现在在处理TensorFlow张量 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)