在执行代码时(来自书籍“Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems”第69页)
housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat)housing_cat_encoded[:10]
我遇到了以下错误:
ValueError: Expected 2D array, got 1D array instead:array=['<1H OCEAN' '<1H OCEAN' 'NEAR OCEAN' ... 'INLAND' '<1H OCEAN' 'NEAR BAY'].Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
如何修复这个问题?
回答:
在这种情况下,错误描述了问题并提供了一种解决方法。函数.fit_transform()
期望接收一个2D数组,而不是1D数组。一种解决方法是使用.reshape()
。由于我们传递的是单列(特征),因此应使用-1,1
。
housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat.reshape(-1,1))
如果housing_cat
是一个pandas系列,那么你可能需要使用:
housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat.values.reshape(-1,1))