简体   繁体   English

Tensorflow tf.keras.layers.Reshape RNN/LSTM

[英]Tensorflow tf.keras.layers.Reshape RNN/LSTM

I have a dataset with multi variables, I'm trying to reshape to feed in a LSTM Neural Nets, but I'm struggle with reshape layer without success.我有一个包含多个变量的数据集,我正在尝试重塑以输入 LSTM 神经网络,但我在重塑层时遇到了困难,但没有成功。

My dataset has the shape (1921535, 6) and every 341 timesteps correspond to one sample.我的数据集的形状为 (1921535, 6),每 341 个时间步对应一个样本。 I'd like to reshape in (23, 341, 6) and feed it in the Model.我想在 (23, 341, 6) 中重塑,并将其放入 Model 中。 Below my code.在我的代码下面。

def df_to_dataset(dataframe, batch_size):
   dataframe = dataframe.copy()
   labels = dataframe.pop('target')
   ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
   ds = ds.batch(batch_size)
   return ds

max_length = 341
batch_size = 23

train_ds = df_to_dataset(data, batch_size * max_length)

model = tf.keras.Sequential([
   tf.keras.layers.Reshape((batch_size, max_length, 6), input_shape=(batch_size * max_length, 6)),
   tf.keras.layers.LSTM(40, return_sequences=True),
   tf.keras.layers.LSTM(40),
   tf.keras.layers.Dense(1)
   ])

When I run the code I've receive the following error:当我运行代码时,我收到以下错误:

InvalidArgumentError: Input to reshape is a tensor with 54901 values, but the requested shape has 369075894 [Op:Reshape]

Thanks in advance提前致谢

I can not reproduce your error:我无法重现您的错误:

max_length = 341
batch_size = 23

model = tf.keras.Sequential([
   tf.keras.layers.Reshape((batch_size, max_length, 6), input_shape=(batch_size * max_length, 6)),
   tf.keras.layers.LSTM(40, return_sequences=True),
   tf.keras.layers.LSTM(40),
   tf.keras.layers.Dense(1)
   ])

Your code is incorrect: output of your Reshape layer has 4 dimensions (your 3 dims plus batch dimension), but LSTM expecting 3 dims.您的代码不正确:您的 Reshape 层的 output 有 4 个维度(您的 3 个维度加上批量维度),但 LSTM 需要 3 个维度。

I've solved the problem using Lambda layer with tf.reshape, I don't know why, but I can't use the Reshape Layer.我已经使用带有 tf.reshape 的 Lambda 层解决了这个问题,我不知道为什么,但我不能使用 Reshape 层。

model = tf.keras.Sequential([
   tf.keras.layers.Lambda(lambda x: tf.reshape(x, (-1, max_length, 6)),
   tf.keras.layers.LSTM(40, return_sequences=True),
   tf.keras.layers.LSTM(40),
   tf.keras.layers.Dense(1)
   ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM