关于numpy矩阵和矩阵索引的数字类型

it2026-06-10  0

关于numpy矩阵和矩阵索引的数字类型

矩阵整体和矩阵元素1.起因2.测试两种方式的区别3.进一步测试4.结论

矩阵整体和矩阵元素

1.起因

在训练网络时,由于内存原因,把原始的图片归一化代码做了修改,不确定能否解决内存溢出的问题,但是发现了新的问题,其余部分不改变,仅做此修改,网络的训练效果顿时开始原地踏步。

images=images/255 #原始代码 for i in range(images.shape[0]): images[i]=images[i]/255 #更改后代码 #其中images为读入的2000*300*300的numpy数组

上图为原始代码实验结果。 上图为修改后代码实验结果,其中eopch由25改为10.

2.测试两种方式的区别

确定问题发生在上述代码段后,开始测试。

a=np.ones((1,3,3),dtype='uint8') b=np.ones((1,3,3),dtype='uint8') c=copy.deepcopy(a) for i in range(a.shape[0]): a[i]=a[i]/2 b=b/2 print('the c is :\n',c) print('the a is :\n',a) print('the b is :\n',b)`

得到结果如下

the c is : [[[1 1 1] [1 1 1] [1 1 1]]] the a is : [[[0 0 0] [0 0 0] [0 0 0]]] the b is : [[[0.5 0.5 0.5] [0.5 0.5 0.5] [0.5 0.5 0.5]]]

显然,索引矩阵元素进行除法操作时,矩阵元素和除数都是整型,得到结果也是整型,而对矩阵整体进行除法操作时,结果可能为浮点型。

3.进一步测试

对三阶矩阵索引时,a[i]为二阶矩阵,测试出现这种现象是否和矩阵的阶数有关。代码如下:

a=np.ones((1,3),dtype='uint8') b=np.ones((1,3),dtype='uint8') #,使用二阶矩阵测试,其他部分不变,输出结果如下 the c is : [[1 1 1]] the a is : [[0 0 0]] the b is : [[0.5 0.5 0.5]] #----------------------------- a=np.ones((1,1,3,3),dtype='uint8') b=np.ones((1,1,3,3),dtype='uint8') #使用四阶矩阵测试,其他部分不变,输出结果如下 the c is : [[[[1 1 1] [1 1 1] [1 1 1]]]] the a is : [[[[0 0 0] [0 0 0] [0 0 0]]]] the b is : [[[[0.5 0.5 0.5] [0.5 0.5 0.5] [0.5 0.5 0.5]]]]

发现不受矩阵阶数影响,下面测试改变除(乘)数的不同情况。

for i in range(a.shape[0]): a[i]=a[i]/2.0 b=b/2.0 #输出结果如下 the c is : [[1 1 1]] the a is: [[0 0 0]] the b is: [[0.5 0.5 0.5]]

即使将除数写为2.0,通过矩阵索引得到的结果依然是整型。

下面测试乘法

for i in range(a.shape[0]): a[i]=a[i]*1 b=b*1 #分别乘1,输出结果如下 the c is : [[1 1 1]] the a is : [[1 1 1]] the b is : [[1 1 1]] #-------------------------- for i in range(a.shape[0]): a[i]=a[i]*1.0 b=b*1.0 #分别乘1.0,输出结果如下 the c is : [[1 1 1]] the a is : [[1 1 1]] the b is : [[1. 1. 1.]]

如果被除数可以被整除,结论同上

a=4*np.ones((1,3),dtype='uint8') b=4*np.ones((1,3),dtype='uint8') c=copy.deepcopy(a) for i in range(a.shape[0]): a[i]=a[i]/2 b=b/2 #输出结果如下 the c is : [[4 4 4]]#乘4之后的结果,我们的被除数在这里是整型 the a is : [[2 2 2]] the b is : [[2. 2. 2.]]

4.结论

原始矩阵为整型矩阵索引整个矩阵除以整型整型浮点型除以浮点型整型浮点型乘整型整型整型乘浮点型整型浮点型

注:该结果不受矩阵阶数的影响

最新回复(0)