【问题标题】:Can’t inverse encoded categorical variables不能逆编码的分类变量
【发布时间】:2018-08-19 13:21:02
【问题描述】:

我的数据框中有一个分类变量 (A,B,C)。然后,我对其进行编码(使其成为数字)以传递到神经网络。

但是,我的最终可视化图表显示了分类变量的编码值,我在将其映射回其原始值时遇到了困难。

我首先使用此命令将我的分类变量(数据类型=对象)编码为数值:

encoders = {}
for x in df.columns:
    if df[x].dtypes=='object':
      le = preprocessing.LabelEncoder()
      df[x]=le.fit_transform(df[x].astype(str))
      encoders[x] = le     

corr = df.corr()

然后,我正在使用此代码对那些进行解码(就在最终可视化之前):

for x, le in encoders.items():
    df[x] = le.inverse_transform(df[x])

    # Visualization: plotting categorical variables (A,B,C) in scatterplot using Seaborn.
    sns.lmplot(x="A", y="B", data=df, fit_reg=False, hue='C',legend=False)
    display()

...但是可视化仍然显示编码值而不是分类值(参见下面的屏幕截图)。没有进行映射。为什么?

【问题讨论】:

  • 你为什么不做 df[x+"_encoded"]=le.fit_transform(df[x].astype(str)),对编码值做任何你需要做的事情,然后绘图时从 df[x] 获取原始标签?

标签: python python-3.x


【解决方案1】:

您必须存储原始LabelEncoder。映射存储在该类中。所以类似于

encoders = {}
for x in df.columns:
    if df[x].dtypes=='object':
       le = preprocessing.LabelEncoder()
       df[x]=le.fit_transform(df[x].astype(str))
       encoders[x] = le

for x, le in encoders.items():
    df[x] = le.inverse_transform(df[x])

或者更好的是,不要用编码的标签覆盖标签,而是在数据框中创建一个新列。

【讨论】:

  • 一旦编码,列的类型不会改变吗?那么仍然检查列是否为object 类型是否有意义
  • @SruthiV 我尝试了这两个代码(您的和 users26 ...)。他们都没有工作。可能是解码代码的位置吗?我更新了上面的代码示例。请指教。
  • @user2653663 我试过你的代码,但它对我不起作用。可能是安置?我编辑了我的原始帖子并附上了视觉效果。请指教。
猜你喜欢
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多