【问题标题】:How to get true labels from LabelEncoder如何从 LabelEncoder 获取真实标签
【发布时间】:2022-01-06 03:49:09
【问题描述】:

我有以下代码 sn-p:

df = pd.read_csv("data.csv")

X = df.drop(['label'], axis=1)
Y= df['label']

le = LabelEncoder()
Y = le.fit_transform(Y)
mapping = dict(zip(le.classes_, range(len(le.classes_))))

x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=7,stratify=Y)

##xgb model
model = XGBClassifier()
model.fit(x_train, y_train)

#predict
y_pred = model.predict(x_train)

这里y_pred 给出了编码标签。编码前如何获取真实标签?

【问题讨论】:

    标签: python scikit-learn label-encoding


    【解决方案1】:

    使用原始标签和编码标签创建一个字典,使用该字典将 y_pred 映射到真实标签

    【讨论】:

      【解决方案2】:

      你可以使用

      le.inverse_transform(y_pred)
      

      其中le 是拟合的LabelEncoder

      le = LabelEncoder().fit(y)
      

      请参阅documentation

      import numpy as np
      from sklearn.model_selection import train_test_split
      from sklearn.preprocessing import LabelEncoder
      from xgboost import XGBClassifier
      
      x = np.random.normal(0, 1, (20, 2))
      y = np.array(['a', 'b'] * 10)
      print(y)
      # ['a' 'b' 'a' 'b' 'a' 'b' 'a' 'b' 'a' 'b' 'a' 'b' 'a' 'b' 'a' 'b' 'a' 'b' 'a' 'b']
      
      le = LabelEncoder().fit(y)
      y_enc = le.transform(y)
      print(y_enc)
      # [0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
      
      x_train, x_test, y_train, y_test = train_test_split(x, y_enc, test_size=0.33, random_state=7, stratify=y_enc)
      
      model = XGBClassifier()
      model.fit(x_train, y_train)
      
      y_pred_enc = model.predict(x_train)
      print(y_pred_enc)
      # [1 0 0 0 0 0 0 0 1 1 1 0 1]
      
      y_pred = le.inverse_transform(y_pred_enc)
      print(y_pred)
      # ['b' 'a' 'a' 'a' 'a' 'a' 'a' 'a' 'b' 'b' 'b' 'a' 'b']
      

      【讨论】:

        猜你喜欢
        • 2018-01-11
        • 2019-05-25
        • 2020-03-07
        • 1970-01-01
        • 2018-02-27
        • 1970-01-01
        • 1970-01-01
        • 2013-05-24
        • 1970-01-01
        相关资源
        最近更新 更多