You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将一维NumPy标签编码为二维(解决分类编码报错)

问题解决步骤

一、处理标签编码错误

你碰到的ValueError是因为标签是字符串格式(比如'a10'),而to_categorical只能处理整数类型标签,解决分两步:

  1. 用LabelEncoder把字符串标签映射为连续整数ID
  2. 再用to_categorical转成二维独热编码

代码示例:

from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.utils import to_categorical

num_classes = 27

# 第一步:字符串标签转整数ID
le = LabelEncoder()
y_train_int = le.fit_transform(y_train)
y_test_int = le.transform(y_test)

# 第二步:整数ID转独热编码
y_train = to_categorical(y_train_int, num_classes)
y_test = to_categorical(y_test_int, num_classes)

# 此时y_train.shape为(431,27),y_test.shape为(430,27)

二、修正模型输入的错误

你的模型输入定义存在问题:

inputs = keras.Input(shape=(x_train.shape[0], x_train.shape[1]))

这里x_train.shape[0]是样本总数(431),不是单个样本的特征维度。结合你用LSTM层的情况,LSTM要求输入为**(时间步, 特征数)**的三维格式(整体输入shape为(样本数, 时间步, 特征数)),需要先调整数据维度:

1. 先重构输入数据维度

根据你的骨骼数据实际结构,把二维的x_train/x_test转成三维。比如假设779是29个时间步 × 27个关节特征(你需要根据自己的数据逻辑调整时间步和特征数):

# 重构训练集和测试集维度
x_train = x_train.reshape(431, 29, 27)
x_test = x_test.reshape(430, 29, 27)

2. 修正模型输入层

对应调整输入层的shape:

inputs = keras.Input(shape=(29, 27))

3. 修正Attention层调用

return_attention_scores=True是层的参数,不是输入列表的一部分,正确写法:

attention = keras.layers.Attention(return_attention_scores=True)([lstm, lstm])

内容的提问来源于stack exchange,提问作者mahshid a.j

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:15:26