python中 .reshape 的用法:reshape(1,-1)

1、numpy中reshape函数的几种常见相关用法

reshape(1,-1)转化成1行:

reshape(2,-1)转换成两行:

reshape(-1,1)转换成1列:

reshape(-1,2)转化成两列

reshape(2,8)转化成两行八列

test = [[1,2,3],[2,3,4]]
test_x = np.reshape(test_x, (2, 1, 3)) # 转二维为三维

2、该篇博客的起源是sklearn时fit的报错

error:

x = np.array([6, 8, 10, 14, 18])
y = np.array([7, 9, 13, 17.5, 18])
model.fit(x, y)

运行后显示: ValueError: Expected 2D array, got 1D array instead
大概意思是期望2维数组,但输入的却是一维数组
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.

solve:

x= np.array([6, 8, 10, 14, 18]).reshape(-1, 1)
y = np.array([7, 9, 13, 17.5, 18]).reshape(-1, 1)
model.fit(x, y)

这是由于在sklearn中,所有的数据都应该是二维矩阵,哪怕它只是单独一行或一列(比如前面做预测时,仅仅只用了一个样本数据),所以需要使用numpy库的.reshape(1,-1)进行转换,而reshape的意思以及常用用法即上述内容。

猜你喜欢

转载自blog.csdn.net/qq_44391957/article/details/120090486