使用get_dummies将分类值转换为数字?

时间:2019-10-29 14:46:20

标签: python pandas machine-learning scikit-learn svm

我正在制作一个简单的可复制示例,以了解培训和测试的工作原理:

示例

我想根据原产地Ages来预测Location

import pandas as pd

# create a simple dataset of people
data = {'Name': ["John", "Anna", "Peter", "Linda","John","John","John"],
        'Location' : ["Paris","Paris","Paris","Paris", "New York", "Berlin", "London"],
        'Age' : [24, 23, 21, 24,36,34,36]
       }

df = pd.DataFrame(data)

在下面的这一部分,城市名称存在问题,因此我决定使用虚拟变量,但是带有get_dummies的行是不正确的。我认为它需要同时将NameLocation字符串都转换为伪变量,这就是我尝试过的方法,但是正确的方法是什么?

from sklearn.model_selection import train_test_split
X = df.drop('Age', axis=1)
y = df['Age']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)

from sklearn.svm import SVC
svclassifier = SVC(kernel='linear')
X_train = pd.get_dummies(df.columns)  #<---- here is the issue probably
svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)

2 个答案:

答案 0 :(得分:1)

svclassifier.fit(X_train, y_train)将数组作为输入,但是您将输入一个熊猫DataFrame。尝试使用sklearn.preprocessing.LabelEncoder代替pd.get_dummies

编辑:带有LabelEncoderOneHotEncoder的示例:

# create a simple dataset of people
data = {'Name': ["John", "Anna", "Peter", "Linda","John","John","John"],
        'Location' : ["Paris","Paris","Paris","Paris", "New York", "Berlin", "London"],
        'Age' : [24, 23, 21, 24,36,34,36]
       }

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.svm import SVC
import numpy as np

X = data['Location']
y = data['Age']

# Label
print("Label Encoded")
le = LabelEncoder()
le.fit(X)
X_enc = le.transform(X)

X_train, X_test, y_train, y_test = train_test_split(X_enc, y, test_size = 0.20, random_state=42)

svclassifier = SVC(kernel='linear')
svclassifier.fit(np.reshape(X_train,(X_train.shape[0],1)), y_train)
y_pred = svclassifier.predict(np.reshape(X_test, (X_test.shape[0],1)))
print(f"y_pred: {y_pred}, y_test: {y_test}")

# OneHot
print("OneHot Encoded")
ohe = OneHotEncoder()
ohe.fit(np.reshape(X,(len(X),1)))
X_oh = ohe.transform(np.reshape(X,(len(X),1)))

X_train, X_test, y_train, y_test = train_test_split(X_oh, y, test_size = 0.20, random_state=42)

svclassifier = SVC(kernel='linear')
svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)
print(f"y_pred: {y_pred}, y_test: {y_test}")

礼物:

Label Encoded
y_pred: [24 24], y_test: [24, 23]
OneHot Encoded
y_pred: [24 24], y_test: [24, 23]

还不错。

答案 1 :(得分:1)

您没有定义特征(X)和目标(y)。您的X是模型学习预测目标y的地方。由于您的功能是名称位置(属于分类功能),因此您需要使用自动编码器,例如get_dummies。

from sklearn.model_selection import train_test_split
#features
X = pd.get_dummies(df[['Name','Location']])

#Target
y = df['Age']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)

from sklearn.svm import SVC

svclassifier = SVC(kernel='linear')
svclassifier.fit(X_train, y_train)
y_pred = svclassifier.predict(X_test)