逆变换函数没有返回正确的值

Inverse transform function is not returning correct value

我正在关注 https://www.analyticsvidhya.com/blog/2019/04/predicting-movie-genres-nlp-multi-label-classification/

中的多标签电影类型教程

我正在使用该教程为投诉登记创建预测标签。在我的例子中,我将 'Genre' 标记为 Complaint Register,例如 1 个投诉可以有多个 label/tag 流派)。例如:投诉 #1 有多种类型 = War运行ty, Air Conditioning.

我正处于调用 multilablebinarizer() 函数来标记电影的阶段 'Genre'

我的问题如下:

独特流派总数 = 55(请参见下面的屏幕截图) image.png

I 运行 Multilabel_binarizer 函数和 t运行sform "Genre" 目标变量为 y。

问题:

  1. 我遇到y只有(166,49)。如果我的理解是正确的,只有 49 种流派而不是 55 种独特的流派

  2. 我遇到错误信息: C:\Users\LAUJ3\Documents\Python Project\env\lib\site-packages\sklearn\multiclass.py:74: UserWarning: Label not 47 is present in all tr​​aining examples. warnings.warn("Label %s is present in all training examples." %

  3. multilabel_binarizer结果的inverse_transfrom函数没有意义。期望看到流派标签而不是乱码 multilabel_binarizer.inverse_transform(y_pred)[3]

    y_pred[3] 输出[57]: 阵列([1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0])

    multilabel_binarizer.inverse_transform(y_pred)[3] Out[58]: (' ', ',', 'a', 'c', 'e', 'g', 'i', 'n', 'o', 'r', 't')

我不知道出了什么问题。提前感谢您的帮助。

Screenshot

from sklearn.preprocessing import MultiLabelBinarizer

mlb =  MultiLabelBinarizer()
mlb.fit_transform(df['genre'])

print(mlb.classes_)
#op
[' ' '"' '&' "'" ',' '-' '/' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' ':'
'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R'
'S' 'T' 'V' 'W' 'Z' '[' '\' ']' '_' 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i'
'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z' '{'
'}']

你得到的字符是 class,因为 df['genre'] 的内容是字符串

#printing type of df['genre']
print(type(df['genre'][0]))
#op
<class 'str'>

将 genre 列转换为 dict 并提取值

df['genre'] = df['genre'].apply(lambda x :[value for value in eval(x).values()])
print(type(df['genre'][0]))
#op
<class 'list'>

现在您可以应用 MultilabelBinarizer 做 df['genre'] 列,现在 inverse_transform 将为您工作

mlb.fit_transform(df['genre'])
print(mlb.classes_[0:10]) # taking only 10 element from array since there is 363 different classes

#op
array(['Absurdism', 'Acid western', 'Action', 'Action Comedy',
   'Action Thrillers', 'Action/Adventure', 'Addiction Drama', 'Adult',
   'Adventure', 'Adventure Comedy'], dtype=object)

更新代码

#replace  df['genre'] = df['genre'].apply(lambda x :[value for value in eval(x).values()])
df['Genre'] = df['Genre'].apply(lambda x: x.split(',')) 
mlb.fit_transform(df1['Genre'])

print(mlb.classes_)
#op
array([' Curtain/Blinds', ' Delays', ' Electricial Compliance',
   ' Granny Flat', ' Heating/Cooling', ' Payment', ' Refund',
   ' Unlicensed', ' Warranty', 'Airconditioning', 'Heating/Cooling',
   'Warranty'], dtype=object

在早期的数据中,它使用字典格式的字符串,但在您的数据中,字符串是逗号分隔的,您不需要使用 eval 函数,简单的拆分就可以了