重塑使用 timeseries_dataset_from_array 预处理的 Tensorflow 数据集
Reshape a Tensorflow dataset preprocessed with timeseries_dataset_from_array
注意:我已经阅读了How to reshape BatchDataset class tensor?,但解决方案不适用于此处。
如 中所述,我需要从形状矩阵 (10000, 2000) 训练一个形状为 (16, 2000) 的所有滑动 windows 的神经网络。 (我的另一个post是100k,但是这里10k就可以了)。
import tensorflow
import numpy as np
X = np.array(range(20000000)).reshape(10000, 2000)
X = tensorflow.keras.preprocessing.timeseries_dataset_from_array(X, None, 16, sequence_stride=1, sampling_rate=1, batch_size=32)
for b in X:
print(b) # Tensor of shape (32, 16, 2000)
break
问题是我需要将它输入一个模型,该模型需要一个 (..., 16, 2000, 1) 形状。
model = Sequential()
model.add(Conv2D(16, kernel_size=(9, 9), activation='relu', input_shape=(16, 2000, 1), padding='same'))
...
model.fit(X, Y, epochs=8)
我试过了
X = tensorflow.reshape(X, (-1, 16, 2000, 1))
没有成功。
如何做到这一点,即输出形状为 (..., 16, 2000, 1)
的 timeseries_dataset_from_array
?
要对 tf.data.Dataset
的每个元素应用转换,您应该使用 tf.data.Dataset.map
function. In your case, you could define the function with a lambda
, using tf.expand_dims
:
ds = tensorflow.keras.preprocessing.timeseries_dataset_from_array(X, None, 16, sequence_stride=1, sampling_rate=1, batch_size=32)
ds_correct_shape = ds.map(lambda x: tf.expand_dims(x,axis=-1))
如果我们检查第一个元素的形状:
>>> for elem in ds_correct_shape.take(1):
print(f"{elem.shape=}")
elem.shape=TensorShape([32, 16, 2000, 1])
注意:我已经阅读了How to reshape BatchDataset class tensor?,但解决方案不适用于此处。
如
import tensorflow
import numpy as np
X = np.array(range(20000000)).reshape(10000, 2000)
X = tensorflow.keras.preprocessing.timeseries_dataset_from_array(X, None, 16, sequence_stride=1, sampling_rate=1, batch_size=32)
for b in X:
print(b) # Tensor of shape (32, 16, 2000)
break
问题是我需要将它输入一个模型,该模型需要一个 (..., 16, 2000, 1) 形状。
model = Sequential()
model.add(Conv2D(16, kernel_size=(9, 9), activation='relu', input_shape=(16, 2000, 1), padding='same'))
...
model.fit(X, Y, epochs=8)
我试过了
X = tensorflow.reshape(X, (-1, 16, 2000, 1))
没有成功。
如何做到这一点,即输出形状为 (..., 16, 2000, 1)
的 timeseries_dataset_from_array
?
要对 tf.data.Dataset
的每个元素应用转换,您应该使用 tf.data.Dataset.map
function. In your case, you could define the function with a lambda
, using tf.expand_dims
:
ds = tensorflow.keras.preprocessing.timeseries_dataset_from_array(X, None, 16, sequence_stride=1, sampling_rate=1, batch_size=32)
ds_correct_shape = ds.map(lambda x: tf.expand_dims(x,axis=-1))
如果我们检查第一个元素的形状:
>>> for elem in ds_correct_shape.take(1):
print(f"{elem.shape=}")
elem.shape=TensorShape([32, 16, 2000, 1])