正在尝试学习 Python 中的 sklearn,但 Jupyter 笔记本报错显示 “ValueError: Expected 2D array, got scalar array instead:array=750.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.” 然而,我已经将 x 定义为 2D 数组,使用了 x.values.reshape(-1,1)。
您可以在此处找到 CSV 文件和错误代码的截图 -> https://github.com/CaptainRD/CSV-for-StackOverflow
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.linear_model import LinearRegression data = pd.read_csv('1.02. Multiple linear regression.csv') data.head() x = data[['SAT','Rand 1,2,3']] y = data['GPA'] reg = LinearRegression() reg.fit(x,y)r2 = reg.score(x,y) n = x.shape[0] p = x.shape[1] adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1) adjusted_r2 reg.predict(1750)
回答:
如您在代码中所见,您的 x 包含两个变量,SAT 和 Rand 1,2,3。这意味着,您需要为 predict 方法提供一个二维输入。例如:
reg.predict([[1750, 1]])
这将返回:
>>> array([1.88])
您遇到这个错误是因为您没有提供第二个值(对于 Rand 1,2,3 变量)。请注意,如果这个变量不重要,您应该将其从 x 数据中移除。