给数组一个新的形状而不改变其数据
1.引入numpy,名称为np
2.接下来创建一个数组a,可以看到这是一个一维的数组
3.使用reshape()方法来更改数组的形状,可以看到看数组d成为了一个二维数组
4.通过reshape生成的新数组和原始数组公用一个内存,也就是说,假如更改一个数组的元素,另一个数组也将发生改变
5.同理还可以得到一个三维数组
6.形状变化的原则是数组元素不能发生改变,比如这样写就是错误的,因为数组元素发生了变化
根据Numpy文档(https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy-reshape)的解释: newshape : int or tuple of ints The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions. 大意是说,数组新的shape属性应该要与原来的配套,如果等于-1的话,那么Numpy会根据剩下的维度计算出数组的另外一个newshape属性值。 举几个例子或许就清楚了,有一个数组z,它的shape属性是(4, 4) z = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) z.shape (4, 4) z.reshape(-1) array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
z.reshape(-1, 1),是说,我们不知道新z的行数是多少,但是想让z变成只有一列,行数不知的新数组,通过z.reshape(-1,1),Numpy自动计算出有12行,新的数组shape属性为(16, 1),与原来的(4, 4)配套。z.reshape(-1,1) array([[ 1], [ 2], [ 3], [ 4], [ 5], [ 6], [ 7], [ 8], [ 9], [10], [11], [12], [13], [14], [15], [16]])
z.reshape(-1, 2),行数未知,列数等于2,reshape后的shape等于(8, 2) z.reshape(-1, 2) array([[ 1, 2], [ 3, 4], [ 5, 6], [ 7, 8], [ 9, 10], [11, 12], [13, 14], [15, 16]])
同理,只给定行数,列数未知,也可以设置newshape等于-1,Numpy也可以自动计算出新数组的列数。
问题4 reshape(-1,10)和reshape(10,-1)的区别:
总结: 这在CV中经常用到的!
好比这里为什么会reshape成train_set_x_orig.shape[0].就是为上面举得例子n1=np.random. rand(2,2,3,5)
n2 = n1.reshape(2,-1)
n3 = n2.T的目的是为了和X进行点积。