【问题标题】:Transforming Dataframe for logistic regression (one hot encoding)为逻辑回归转换数据框(一种热编码)
【发布时间】:2020-08-31 17:52:01
【问题描述】:

我正在尝试在 python 中运行逻辑回归。我的数据由数字和分类数据组成。我想使用性别、年龄和食物偏好来预测某人是否喜欢猫。

我在想我需要对 Food_preference 进行一次热编码(见下文),但不确定具体该怎么做。能否请你帮忙?谢谢!

原始数据框

Name    Gender  Age Like_cats   Food_preference
John    M   30  Yes Apple
John    M   30  Yes Orange
John    M   30  Yes Steak
Amy F   20  No  Apple
Amy F   20  No  Grape

所需的数据帧

Name    Gender  Age Like_cats   Apple   Orange  Steak   Grape
John    M   30  Yes 1   1   1   0
Amy F   20  No  1   0   0   1

【问题讨论】:

    标签: python logistic-regression one-hot-encoding


    【解决方案1】:

    您可以使用 LabelEncoder 将字符串特征转换为数字特征。

    https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder

    这是一个与你的数据结构相同的工作代码:

    from sklearn.linear_model import LogisticRegression
    import pandas as pd
    from sklearn import preprocessing
    import numpy as np
    
    
    
    X = pd.DataFrame([['a', 0], ['b', 1], ['a', 5], ['b', 100]])
    y = [0, 1, 0, 1]
    
    X_n = [[]]*len(X.columns)
    
    i = 0
    for c in X.columns:
        if type(X[c].iloc[0]) == str: # if features are string encode them
            le = preprocessing.LabelEncoder()
            le.fit( list(set(X[c])) )
            X_n[i] = le.transform(X[c]) 
        else: # already numeric features
            X_n[i] = list(X[c])
        i += 1
    
    X_n = np.array(X_n).T # transposing to make rows as per sample feature
    print(X_n)
    
    clf = LogisticRegression(random_state=0).fit(X_n, y)
    

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 2016-01-07
      • 2019-12-09
      • 2019-08-17
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 2017-11-02
      相关资源
      最近更新 更多