尝试做线性回归分类器给我“ValueError:期望2D数组,得到1D数组代替

2024-06-02 08:53:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经通过scikit学习了使用线性压缩的toturiol。当我试图编写自己的代码来实现它时,我得到一个错误 “”如果它包含单个示例。“.format(array)) ValueError:应为2D数组,改为1D数组: “#仅使用一项功能:” saemple代码正在发送一个1d数组 糖尿病×糖尿病数据[:,np.newaxis,2]

这就是我所尝试的: 1.使用列表而不是numpy数组 2.在示例代码中打印出X [[ 0.06169621] [-0.05147406] ..... ]] 然后我试着改变我的代码如下 xp=[[3449][1058][2201]] 出现一个错误,要求语句结尾。 然后我试着 xp=[[3449],[1058],[2201]] 相同的错误消息

我的代码

xs=np.array([ 3449 ,  1058,  2201,  2500,  1953,  1637,  1400,  1836,  1400,  4677,  1639,  2094,  1491], dtype=np.float64)
ys=np.array([529000,279090,479000,319000,369000,346000,425000,380000,425000,646900,349900,384900,284900], dtype=np.float64)

xp=[ 3449 ,  1058,  2201,  2500,  1953,  1637,  1400,  1836,  1400,  4677,  1639,  2094,  1491]
yp=[529000,279090,479000,319000,369000,346000,425000,380000,425000,646900,349900,384900,284900]

clf= linear_model.LinearRegression()

clf.fit(xp, yp)
g=clf.predict( 279090)
print("+++++++ guess +++++++")
print(g)
print("jjjjjjj")

Tags: 代码示例错误np线性数组scikitarray
2条回答

在使用xp = np.array([....])yp = np.array([....])将其转换为NumPy数组之后,可以将其重塑为具有单个列的二维数组

xp = xp.reshape(xp.shape[0],-1)
yp = yp.reshape(yp.shape[0],-1)

clf= linear_model.LinearRegression()

clf.fit(xp, yp)
g=clf.predict( 279090)
print("+++++++ guess +++++++")
print(g)
print("jjjjjjj")

# +++++++ guess +++++++
# [[24426732.22]]
# jjjjjjj

正如错误所述,fit函数需要一个2D数组,如果您只有一个特征,这意味着您有一个1D数组,那么可以使用reshape(1, -1)将其设置为2D数组 .
下面是一个工作示例:

xs=np.array([ 3449 ,  1058,  2201,  2500,  1953,  1637,  1400,  1836,  1400,  4677,  1639,  2094,  1491], dtype=np.float64)
ys=np.array([529000,279090,479000,319000,369000,346000,425000,380000,425000,646900,349900,384900,284900], dtype=np.float64)

xp=[ 3449 ,  1058,  2201,  2500,  1953,  1637,  1400,  1836,  1400,  4677,  1639,  2094,  1491]
yp=[529000,279090,479000,319000,369000,346000,425000,380000,425000,646900,349900,384900,284900]

xp = np.array(xp).reshape(1, -1)
yp = np.array(yp).reshape(1, -1)
clf= linear_model.LinearRegression()

clf.fit(xp, yp)
g=clf.predict(xs.reshape(1, -1))
print("+++++++ guess +++++++")
print(g)
print("jjjjjjj")

相关问题 更多 >