天天看点

Expected 2D array, got scalar array instead: array=10.

问题:

进行最小二乘法通过给定值预测结果时

 model.predict(10)  出现参数类型错误

Expected 2D array, got scalar array instead: array=10.

解决方法:

注释掉上面黄色背景的一行

使用下面这种格式进行预测

import numpy as np

new_x = 8
new_x = np.array(new_x).reshape(1, -1)
pre_y = model.predict(new_x)
print(f"预测结果是:{pre_y}")
           

使用最小二乘法求线性关系中未知系数的实例

源代码如下:

#使用最小二乘法求线性关系中的未知系数


#导入解析excel数据模块
from pyexpat import features
import pandas as pd

#导入数据绘图模块
import matplotlib.pyplot as plt

#导入支持求解最小二乘法的模块
from sklearn.linear_model import LinearRegression

#导入数字处理集
import numpy as np

data = pd.read_excel("./商场-人流量-销售额.xlsx")
print(data)
# data

data.plot.scatter(x='日均人流量(千人)', y='日均销售额(千元)')
plt.show()
#做散点图

features = data['日均人流量(千人)'].values.reshape(-1,1)
target = data['日均销售额(千元)']

regression = LinearRegression()                 #线性回归
model = regression.fit(features,target)         #对数据进行线性拟合

# model.intercept_
print(f"截距b是:{model.intercept_}")
print(f"系数a是:{model.coef_}")
# print(model.predict(10))
#输入参数类型错误,提示array=10,二维数组,一维数组

new_x = 8
new_x = np.array(new_x).reshape(1, -1)
pre_y = model.predict(new_x)
print(f"预测结果是:{pre_y}")



           

源数据

格式为 xlsx,命名为:商场-人流量-销售额

Expected 2D array, got scalar array instead: array=10.