如何对timeseries_dataset_from_array生成的时序张量做独热编码?
解决时序序列分类特征的独热编码问题
你的错误源于CategoryEncoding层在one_hot输出模式下,默认仅支持处理2D输入张量,而你的输入是3D结构((None, 20, 1),对应批次、时间步、单分类特征),编码后会产生3D输出,超出了该层的限制。以下是两种可行的解决方案:
方法一:用TimeDistributed层适配时序结构
TimeDistributed层可以将编码逻辑独立应用到每个时间步的特征上,让CategoryEncoding处理每个时间步的2D切片((None, 1)),最终输出符合LSTM要求的3D张量。
n_timesteps = 20 n_categorical_features = 1 from tensorflow import keras from tensorflow.keras.layers import Input, IntegerLookup, CategoryEncoding, TimeDistributed # 定义3D输入(批次、时间步、分类特征数) cat_inp = keras.layers.Input(shape=(n_timesteps, n_categorical_features), name="categorical_input") # 初始化并适配整数查找层 index = IntegerLookup() index.adapt(X["br"]) # 先对输入做整数映射 lookup_output = IntegerLookup(vocabulary=index.get_vocabulary())(cat_inp) # 用TimeDistributed包裹编码层,处理每个时间步的特征 one_hot_encoded = TimeDistributed( CategoryEncoding(num_tokens=index.vocabulary_size(), output_mode="one_hot") )(lookup_output) # 此时one_hot_encoded的形状为(None, 20, num_classes),可直接输入LSTM层
方法二:Reshape调整张量维度
先将3D张量压缩为2D,完成编码后再恢复为3D结构,适配时序需求:
n_timesteps = 20 n_categorical_features = 1 from tensorflow import keras from tensorflow.keras.layers import Input, IntegerLookup, CategoryEncoding, Reshape cat_inp = keras.layers.Input(shape=(n_timesteps, n_categorical_features), name="categorical_input") index = IntegerLookup() index.adapt(X["br"]) # 将3D张量转为2D:(None, 20) reshaped_input = Reshape((n_timesteps,))(cat_inp) # 整数映射+独热编码 lookup_output = IntegerLookup(vocabulary=index.get_vocabulary())(reshaped_input) one_hot_encoded = CategoryEncoding( num_tokens=index.vocabulary_size(), output_mode="one_hot" )(lookup_output) # 恢复为3D时序结构:(None, 20, num_classes) final_output = Reshape((n_timesteps, index.vocabulary_size()))(one_hot_encoded)
两种方法最终都会生成形状为(None, n_timesteps, num_classes)的张量,完全兼容LSTM模型的输入要求。
内容的提问来源于stack exchange,提问作者Requin
相关产品推荐
相关产品推荐

