How can repeated labels become reversible dictionary codes?

unique can return the distinct values and an inverse index. Gathering from the distinct values with that index reconstructs the input.

numpy.unique in practice

Labels B,A,B need two dictionary entries and three codes. Encoding train and test sets independently can assign different codes, so reuse the training dictionary.

import numpy as np
u,i=np.unique(['B','A','B'],return_inverse=True)
[u.tolist(),i.tolist()]

Result [["A", "B"], [1, 0, 1]]

中文

怎样给重复标签生成可还原的字典编码?

unique 可同时返回不同值和逆向索引。用逆向索引读取不同值即可还原原序列。

numpy.unique 算例

标签 B、A、B 可压成两个词和三个编号。分开编码训练与测试时编号可能改变,应复用训练字典。

import numpy as np
u,i=np.unique(['B','A','B'],return_inverse=True)
[u.tolist(),i.tolist()]

结果 [["A", "B"], [1, 0, 1]]

References / 参考来源

Keep reading / 继续阅读