无法修复我在编写用于分析 O'Reilly 书中的 "California Housing" 数据集的代码时遇到的错误
Not able to fix the error I get while writing code for analyzing "California Housing" data set from O'Reilly book
执行代码时:(摘自《使用 Scikit-Learn、Keras 和 TensorFlow 进行机器学习实践:构建智能系统的概念、工具和技术》一书第 69 页
Aurelien Geron 的书")
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()
需要一个二维数组,而不是一维数组。实现此目的的一种方法是使用 .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))
执行代码时:(摘自《使用 Scikit-Learn、Keras 和 TensorFlow 进行机器学习实践:构建智能系统的概念、工具和技术》一书第 69 页 Aurelien Geron 的书")
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()
需要一个二维数组,而不是一维数组。实现此目的的一种方法是使用 .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))