新しいバージョンのsklearnを使用してValueErrorを報告します:予期された2D配列、代わりに1D配列を取得しました



Use New Version Sklearn Report Valueerror



1.私のPythonXiaobaiは次のコードを試したところ、エラーが発生しました。

from sklearn.linear_model import LinearRegression # Create and fit the model model = LinearRegression() X = [[6], [8], [10], [14], [18]] y = [[7], [9], [13], [17.5], [18]] model.fit(X, y) print('Predict the price of 12-inch pizza: $%.2f' % model.predict([12])[0])

2.エラーメッセージによると



ValueError: Expected 2D array, got 1D array instead: 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.

これは、入力した1次元データが認識されないためであることがわかります。彼は二次元データを期待しています。 1次元データを使用する必要がある場合は、reshape(-1,1)またはreshape(1、-1)を使用します。
3.ポイントは、それが追加された場所で形状変更が間違っていて、最終的に見つかったということです reshapeはnumpyライブラリの機能です このライブラリは、最初に導入し、最後に変更する必要があります。次の図に示すように、正しく実行できます。

from sklearn.linear_model import LinearRegression import numpy as np //Introduce the numpy library # Create and fit the model model = LinearRegression() X = [[6], [8], [10], [14], [18]] y = [[7], [9], [13], [17.5], [18]] model.fit(X, y) x_new=[12] x_new = np.array(x_new).reshape(1, -1) print('Predict the price of 12-inch pizza: $%.2f' % model.predict(x_new)[0])

4.まとめ



  1. numpyライブラリを紹介します
  2. テストされる1次元データx_newは、次のように処理されます。
    x_new = [12]
    x_new = np.array(x_new).reshape(1、-1)