在编写用于分析O’Reilly书籍中”California Housing”数据集的代码时,无法修复遇到的错误

在执行代码时(来自书籍“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))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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