【发布时间】:2019-01-18 15:25:58
【问题描述】:
尝试在 Titanic 数据集上应用 OneHotEncoding。 sklearn 版本是 0.19.2。 Labelencoded 首先和现在尝试 Onehot 编码时,它抛出错误'Could not convert str to float: C148'
首先,Labelencoded 'Sex' 和 'Embarked' 功能,这已成功完成。现在,当尝试进行 One 热编码时,“客舱”功能中的值被引发了异常,而这根本不应该被编码。此外,C148 是几乎出现在数据集末尾的值。
#Label Encoding
encoder= LabelEncoder()
df2['Embarked']=df2['Embarked'].fillna(method='backfill')
array1= df2.values
array1[:,4]=encoder.fit_transform(array1[:,4])
array1[:,11]=encoder.fit_transform(array1[:,11])
df_encoded1= pd.DataFrame(array1)
#One hot encoding
from sklearn.preprocessing import OneHotEncoder
hotencoder= OneHotEncoder(categorical_features=[4,11])
array1= hotencoder.fit_transform(array1)
ValueError Traceback (most recent call last)
<ipython-input-45-c14deb702f63> in <module>()
----> 1 array1= hotencoder.transform(array1)
~\AppData\Local\Continuum\anaconda3\lib\site-
packages\sklearn\preprocessing\data.py in transform(self, X)
2073 """
2074 return _transform_selected(X, self._transform,
-> 2075 self.categorical_features,
copy=True)
2076
2077
~\AppData\Local\Continuum\anaconda3\lib\site-
packages\sklearn\preprocessing\data.py in _transform_selected(X, transform,
selected, copy)
1807 X : array or sparse matrix, shape=(n_samples, n_features_new)
1808 """
-> 1809 X = check_array(X, accept_sparse='csc', copy=copy,
dtype=FLOAT_DTYPES)
1810
1811 if isinstance(selected, six.string_types) and selected == "all":
~\AppData\Local\Continuum\anaconda3\lib\site-
packages\sklearn\utils\validation.py in check_array(array, accept_sparse,
dtype, order, copy, force_all_finite, ensure_2d, allow_nd,
ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
431 force_all_finite)
432 else:
--> 433 array = np.array(array, dtype=dtype, order=order,
copy=copy)
434
435 if ensure_2d:
ValueError: could not convert string to float: 'C148'
除了上述错误的解决方案,还请告诉我如何更新到最新版本的 sklearn。我尝试使用 pip install -U scikit-learn 更新 sklearn,但它再次安装了 0.19.2 版本。
【问题讨论】:
-
pip install -U sklearnScikit-learn 更新,那么它应该可以工作了。
标签: scikit-learn one-hot-encoding