在对字符串数据进行分类时出现ValueError

我在尝试解决Kaggle上的泰坦尼克号问题(https://www.kaggle.com/c/titanic)。我试图使用sklearn.preprocessing库中的LabelEncoderOneHotEncoder类对”Sex”列进行分类编码。以下是我的代码:

# 导入数据分析库import pandas as pdimport numpy as npimport random as rnd# 导入数据可视化库import seaborn as snsimport matplotlib.pyplot as plt# 导入机器学习库from sklearn.linear_model import LogisticRegressionfrom sklearn.svm import SVC, LinearSVCfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.naive_bayes import GaussianNBfrom sklearn.linear_model import Perceptronfrom sklearn.linear_model import SGDClassifierfrom sklearn.tree import DecisionTreeClassifier# 获取数据集train = pd.read_csv('./input/train.csv')test = pd.read_csv('./input/test.csv')combine = [train, test]# 特征可视化g = sns.FacetGrid(train, col='Survived')g.map(plt.hist, 'Age', bins=20)grid = sns.FacetGrid(train, col='Survived', row='Pclass', size=2.2, aspect=1.6)grid.map(plt.hist, 'Age', alpha=.5, bins=20)grid.add_legend()g = sns.FacetGrid(train, col='Survived')g.map(plt.hist, 'Parch', bins=20)g = sns.FacetGrid(train, col='Survived')g.map(plt.hist, 'SibSp', bins=20)g = sns.FacetGrid(train, col='Survived')g.map(plt.hist, 'Fare', bins=20)g = sns.FacetGrid(train, col='Survived')g.map(plt.hist, 'Sex', bins=20)# 处理缺失值train.fillna(train.median(), inplace = True)# 对Embarked和Sex特征进行分类# train['Embarked'] = train['Embarked'].map( {'S': 0, 'C': 1, 'Q': 2} )# train['Sex'] = train['Sex'].map( {'male': 0, 'female': 1} )# 数据预处理X_train = train.iloc[:, [0, 2, 4, 5, 6, 7, 9]].valuesy_train = train.iloc[:, [1]].valuesX_test  = test.iloc[:, [1, 3, 4, 5, 6, 8]].valuesfrom sklearn.preprocessing import Imputer, LabelEncoder, OneHotEncoder, StandardScalerlabelencoder_X=LabelEncoder()X_train[:, 0]=labelencoder_X.fit_transform(X_train[:, 0])onehotencoder=OneHotEncoder(categorical_features=[0])X_train=onehotencoder.fit_transform(X_train).toarray()

当我执行最后5行代码时,出现了以下错误:

Traceback (most recent call last):  File "<ipython-input-58-770fc19a6644>", line 5, in <module>    X_train=onehotencoder.fit_transform(X_train).toarray()  File "C:\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py", line 2019, in fit_transform    self.categorical_features, copy=True)  File "C:\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py", line 1809, in _transform_selected    X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)  File "C:\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 433, in check_array    array = np.array(array, dtype=dtype, order=order, copy=copy)ValueError: could not convert string to float: 'male'

我的错误是什么?有没有其他有效的编码分类数据的技术?


回答:

OneHotEncoder期望接收整数值——这就是它对'male'(字符串)值提出抱怨的原因。

你可以先使用LabelEncoder将非数值值编码成数字,然后再应用OneHotEncoder

或者使用LabelBinarizer对单个非数值列进行OneHot编码

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注