我进行文本分类,我原本的标签是:
{‘Alarm-Update’,
‘Audio-Play’,
‘Calendar-Query’,
‘FilmTele-Play’,
‘HomeAppliance-Control’,
‘Music-Play’,
‘Other’,
‘Radio-Listen’,
‘TVProgram-Play’,
‘Travel-Query’,
‘Video-Play’,
‘Weather-Query’}
我通过
le = LabelEncoder()
train_y = le.fit_transform(train_y).reshape(-1,1)
train_y = ohe.fit_transform(train_y).toarray()
把标签变成了独热编码,现在要如何把标签变回去呢?
你可以使用 inverse_transform
函数将独热编码的标签转换为原始字符串标签。
具体代码如下:
import numpy as np
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
# 假设你已经得到了 train_y,它是原始的字符串标签列表
labels = ['Alarm-Update', 'Audio-Play', 'Calendar-Query', 'FilmTele-Play', 'HomeAppliance-Control', 'Music-Play', 'Other', 'Radio-Listen', 'TVProgram-Play', 'Travel-Query', 'Video-Play', 'Weather-Query']
# 对原始标签进行 LabelEncoder 编码
le = LabelEncoder()
le.fit(labels)
# 对训练集标签进行独热编码
train_y = le.transform(train_y)
ohe = OneHotEncoder()
train_y = ohe.fit_transform(train_y.reshape(-1, 1)).toarray()
# 将独热编码的标签转换为原始字符串标签
train_y_decode = np.argmax(train_y, axis=1)
train_y_decode = le.inverse_transform(train_y_decode)
# 输出转换后的标签
print(train_y_decode)
最终输出的 train_y_decode
就是转换后的字符串标签列表。