如果您的数据只有一个特征,则可以使用array.reshape(-1,1)来调整其形状,如果数据包含单个样本,则可以使用array.reshape(1,-1)。

18

当我从我的数据中预测一个样本时,它会出现重塑错误,但是我的模型具有相等数量的行。这是我的代码:

import pandas as pd
from sklearn.linear_model import LinearRegression
import numpy as np
x = np.array([2.0 , 2.4, 1.5, 3.5, 3.5, 3.5, 3.5, 3.7, 3.7])
y = np.array([196, 221, 136, 255, 244, 230, 232, 255, 267])

lr = LinearRegression()
lr.fit(x,y)

print(lr.predict(2.4))

错误在于

if it contains a single sample.".format(array))
ValueError: Expected 2D array, got scalar array instead:
array=2.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.

如果您想知道为什么拟合模型需要2D模型,请点击此处 - Dozzy Norm
3个回答

28

你需要将X重新塑形为2D数组而不是1D数组。适配模型需要使用2D数组。即(n_samples,n_features)

x = np.array([2.0 , 2.4, 1.5, 3.5, 3.5, 3.5, 3.5, 3.7, 3.7])
y = np.array([196, 221, 136, 255, 244, 230, 232, 255, 267])

lr = LinearRegression()
lr.fit(x.reshape(-1, 1), y)

print(lr.predict([[2.4]]))

3
谢谢,但是reshape是什么意思?为什么不使用它会导致错误? - user11585758
3
在拟合模型时,你的X需要是一个二维数组,即(n_samples,n_features)。使用.reshape(1, -1)会将一维数据变为二维。你可以查看这个问题('https://dev59.com/82Ml5IYBdhLWcg3wHTqg') ,了解更多相关信息。 - Abhi

0

这个错误基本上是说要将扁平的特征数组转换为列数组。reshape(-1, 1) 可以完成这个工作;也可以使用 [:, None]

特征数组 X 的第二维度必须与传递给 predict() 的任何内容的第二维度匹配。由于 X 被强制转换为 2D 数组,因此传递给 predict() 的数组也应该是 2D 的。

x = np.array([2.0 , 2.4, 1.5, 3.5, 3.5, 3.5, 3.5, 3.7, 3.7])
y = np.array([196, 221, 136, 255, 244, 230, 232, 255, 267])
X = x[:, None]         # X.ndim should be 2

lr = LinearRegression()
lr.fit(X, y)

prediction = lr.predict([[2.4]])

如果您的输入是 pandas 列,则使用双方括号([[]])获取一个 2D 特征数组。
df = pd.DataFrame({'feature': x, 'target': y})
lr = LinearRegression()
lr.fit(df['feature'], df['target'])            # <---- error
lr.fit(df[['feature']], df['target'])          # <---- OK
#        ^^         ^^                           <---- double brackets 
为什么X需要是二维的?

如果我们查看scikit-learn中任何模型的fit()源代码,其中的第一件事之一就是通过validate_data()方法验证输入,该方法调用check_array()来验证Xcheck_array()检查了许多内容,其中包括X是否为二维的。X必须是二维的,因为最终LinearRegression().fit()调用scipy.linalg.lstsq来解决最小二乘问题,而lstsq需要X是二维的才能执行矩阵乘法。

对于分类器而言,需要第二个维度来获取特征数量,这对于正确形状的模型系数至关重要。


0
你可以使用lr.predict([[2.4]])代替lr.predict(2.4)

欢迎来到SO。你提供的东西是什么,而https://stackoverflow.com/a/58663856/12846804在你之前发布了4年的时间里没有提供的? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接