我在 sklearn 中使用非负矩阵分解(NMF)进行无监督类别预测(带有用于检查准确性的标签),但遇到了输入类别和转换类别之间没有清晰映射的问题。
例如,如果我的类别是“A”、“B”和“C”(n_components=3),我不知道转换后的类别将按哪个顺序。我可以手动打印与每个输出特征关联的数据确定它最接近哪个输入,但我正在寻找一个自动解决方案。
是否有一个方便的方法,或者我是否需要执行猜测和检查以查看哪种类别顺序可以最大化准确性(对于大量类别来说非常慢)?
找到了解决方案,比猜测和检查快得多。简单地对该类别的所有已知实例的模型预测数字类别进行平均即可给出近似映射,然后可以将其转换为整数:
values = []
for c in ['A', 'B', 'C', 'D', 'E']: # Example Categories
# Get samples from one category at a time
idxs = train['Category'] == c
# Get the average (numeric) output category for those samples
values.append(np.mean(np.argmax(model.transform(data['Train'][idxs]), 1)))
# Rounding may be unreliable, so sort pairs of value and category by ascending order
# and use their indexes instead to guarantee no duplicates
pairs = list(zip(values, cats))
pairs.sort()
# The category mapping is {category: index}
catmap = {k: i for i, k in enumerate([p[1] for p in pairs])}
输出示例:
{'B': 0, 'A': 1, 'C': 2, 'E': 3, 'D': 4}