将 Tensorflow 模型批处理维度重塑为时间序列

Reshape Tensorflow model batch dimension into time series

我正在尝试沿批次维度重塑 Tensorflow 模型的输入。我想将一些批次样本组合成一个时间序列,这样我就可以将它送入 LSTM 层。

具体来说,我有 1024 个样本,我想将它们分成 64 个时间步长的组,结果是 16 批 64 个时间步长,每个时间步长具有原始的 24 个特征。

 #input tensor is (1024, 24)
 inputLayer = Input(shape=(24,))

 #I want it to be (16, 64, 24)
 reshapedLayer = layers.Reshape([64, 24])(inputLayer)
 lstmLayer = layers.LSTM(128, activation='relu')(reshapedLayer)

这可以编译但会引发运行时错误

tensorflow.python.framework.errors_impl.InvalidArgumentError:  
Input to reshape is a tensor with 24576 values, but the requested shape has 1572864

我明白错误告诉我的是什么,但我不确定修复它的正确方法。

也许这对你有用:

import tensorflow as tf

inputs = tf.keras.layers.Input(shape=(24,))

x = tf.reshape(inputs, (16, 64, 24))
x = tf.keras.layers.LSTM(128, activation='relu')(x)

model = tf.keras.Model(inputs=inputs, outputs=x)

# dummy data
inputs = tf.random.uniform(shape=(1024, 24))

outputs = model(inputs)

tf.reshape 替换 Reshape 图层。