Sklearn拟合线性回归

时间:2019-12-16 16:53:33

标签: python scikit-learn linear-regression sklearn-pandas

我有这个问题:

  regression.fit(X_train, y_train)

我遇到以下错误:

ValueError: Expected 2D array, got 1D array instead:
array=[ 2.9  5.1  3.2  4.5  8.2  6.8  1.3 10.5  3.   2.2  5.9  6.   3.7  3.2
  9.   2.   1.1  7.1  4.9  4. ].
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 个答案:

答案 0 :(得分:0)

您还没有共享源代码,但这是我的2美分:

如果您有一个硬编码数组,而不是一维数组:

array=[ 2.9, 5.1, 3.2, 4.5, 8.2, 6.8, 1.3, 10.5, 3., 2.2, 5.9, 6., 3.7, 3.2, 9., 2., 1.1, 7.1, 4.9, 4.]

使用2D数组:

array=[[ 2.9, 5.1, 3.2, 4.5, 8.2, 6.8, 1.3, 10.5, 3., 2.2, 5.9, 6., 3.7, 3.2, 9., 2., 1.1, 7.1, 4.9, 4.]]

如果要将一维数组转换为二维数组,则只需使用numpy的reshape函数。例如,

>>> test_array = np.array([1, 2, 3, 4, 5])
>>> test_array
array([1, 2, 3, 4, 5])
>>> test_array = test_array.reshape(1, -1)
>>> test_array
array([[1, 2, 3, 4, 5]])