ValueError: Found array with dim 4. Estimator expected和ValueError: Expected 2D array, got 1D array i

python3中对numpy数组进行降维或升维

解决报错如:

1.ValueError: Found array with dim 4. Estimator expected

2.ValueError: Expected 2D array, got 1D array instead:

报错1ValueError: Found array with dim 4. Estimator expected——解决方式:
使用 np.concatenate

函数模型:concatenate((a1, a2, …), axis=0)

Parameters参数说明:
• 传入的参数(a1,a2,a3,…)必须是一个多个数组的元组或者列表
另外需要指定拼接的方向,默认axis = 0,也就是说对数组中0轴(X轴/或者说行)的对象进行拼接得到一个纵向组合的数组,(axis=1则是相反);注:一般axis = 0,就是对该轴向的数组进行操作,操作方向是另外一个轴,即axis=1。

import numpy as np
a = np.array([[1,2],[2,3]])
b = np .array([[4,5],[3,4]])
print(np.concatenate((a, b), axis=0))

print(np.concatenate((a), axis=0))

输出结果:(这样就可以将对数组进行降维了(剥除一组中括号[ ]))

[[1 2]
 [2 3]
 [4 5]
 [3 4]]
 
[1 2 2 3]

参考链接:https://blog.csdn.net/brucewong0516/article/details/79158758

报错2函数fit时出现ValueError: Expected 2D array, got 1D array instead:——解决方式:
这里我将函数报错时的代码片段截取出来,具体函数的数据就不截取了
方法1:使用中括号[ ]:
原代码:

import numpy as np  
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()  
knn.fit(x,y)                 
x_new = [50000,8,1.2]
y_pred = knn.predict(x_new)

会报错:

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.

使用np.array.reshape修改:

x_new = np.array([50000,8,1.2]).reshape(1,-1)

方法2.使用 np.array.reshape(1,-1)

x_new = np.array([[50000,8,1.2]])

python3新版的sklearn中,所有的数据都应该是二维矩阵,即np.array()中应该至少是包含两对中括号[ ]

参考链接:https://www.jianshu.com/p/60596270e94e

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值