首页 > 解决方案 > 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)

问题描述

虽然我从我的数据中预测一个样本,但它给出了重塑错误,但我的模型有相同的行数,什么是问题家伙,发现了类似的问题,但不同的原因无法解释。

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))

错误是

“如果它包含单个样本。”.format(array)) ValueError:预期的二维数组,得到标量数组:array=2.4。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1) 。

标签: pythonscikit-learnlinear-regression

解决方案


您应该将您的 X 重塑为 2D 数组而不是 1D 数组。拟合模型需要一个二维数组。i.e (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]]))

推荐阅读