对于 LSTM,我通过 tensorflow.keras.utils.timeseries_dataset_from_array()
创建时间序列。对于某些功能,我想通过 Keras 预处理层进行 one-hot 编码。
我有以下代码:
n_timesteps = 20
n_categorical_features = 1
from tensorflow.keras.layers import Input, IntegerLookup, CategoryEncoding
cat_inp = keras.layers.Input(shape=(n_timesteps, n_categorical_features), name = "categorical_input")
index = IntegerLookup()
index.adapt(X["br"])
encoder = CategoryEncoding(num_tokens=index.vocabulary_size(), output_mode = "one_hot")(cat_inp)
但是,最后一行给了我错误 ValueError: 调用层“category_encoding_22”(类型 CategoryEncoding)时遇到异常。当output_mode不是
'int'时,最大支持的输出rank为2。接收到output_mode one_hot和输入形状(None, 20, 1),这将导致输出rank 3。
问题似乎 CategoryEncoding 不支持我的输入张量的形状(None、n_timesteps、n_categorical_features)。
如何对 timeseries_dataset_from_array() 生成的输入张量进行一次性编码
?
最佳答案
请尝试使用TimeDistributed层:
encoder = tf.keras.layers.TimeDistributed(CategoryEncoding(num_tokens=index.vocabulary_size(), output_mode = "one_hot"))(cat_inp)
它将对时间序列中的每个项目应用 CategoryEncoding。请参阅https://keras.io/api/layers/recurrent_layers/time_distributed/ 了解更多信息。
关于python - 具有时间序列的 Keras CategoryEncoding 层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75370436/