python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python broadcast和numpy.sum()函数

python之broadcast和numpy.sum()函数用法及说明

作者:ImposterSyndrome

这篇文章主要介绍了python之broadcast和numpy.sum()函数用法及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

python broadcast和numpy.sum()函数

import numpy as np
a = np.random.random_sample((3,1,3))
b  = np.random.random_sample((2,3))
c = a-b
c = np.square(c)
c = np.sum(c,axis=2)
c= np.sqrt(c)
a1 = a[1,:,:]
b1 = b[1,:]
print(a1,'5')
print(b1,'6')
print(np.square(a1-b1).shape)
print(np.sum(np.square(a1-b1),axis=1),'7')
print(np.sqrt(np.sum(np.square(a1-b1),axis=1)))

python 的broadcast机制,适用于当两个array的形状不一样时,可以通过broadcast进行自动的补齐,从而可以减少使用循环所带来的代码量以及提高效率。

它的补齐规则如下:

1.如果两个数组数据维度相同,如(3,1,2)与(1,2,2),且其中某个维度的rank是1,那么会将rank低的数据进行复制,直到两个数组的维度以及rank均相同

2.如果两个数组的维度不同,如(3,1,2)与(2,2),那么维度低的数组会加一,直到其维度与高维度的相匹配,加一的条件在于(1,2)与(2,2)可以进行broadcast,与情况一相同

numpy.sum()

a.shape = (1,2,3,4)

numpy.sum(a,axis = 0).shape = (2,3,4)
numpy .sum(a, axis =1).shape = (1,3,4)

numpy-numpy.sum()中‘keepdims‘参数的作用

在numpy的许多函数中,会出现'keepdims'参数,以numpy.sum()为例:

官方文档中给出的解释:

numpy.sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>, where=<no value>)
'''
keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.
If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be. If the sub-class' method does not implement keepdims any exceptions will be raised.
'''

看的一脸懵,还是跑个代码来得实在:

a = np.array([[0, 0, 0],
       [0, 1, 0],
       [0, 2, 0],
       [1, 0, 0],
       [1, 1, 0]])
print(a)
'''
输出:
[[0 0 0]
 [0 1 0]
 [0 2 0]
 [1 0 0]
 [1 1 0]]
'''
a_sum_true = np.sum(a, keepdims=True)
print(a_sum_true)
print(a_sum_true.shape)
a_sum_false = np.sum(a, keepdims=False)
print(a_sum_false)
print(a_sum_false.shape)
'''
输出:
[[6]]
(1, 1)
6
()
'''
a_sum_axis1_true = np.sum(a, axis=1, keepdims=True)
print(a_sum_axis1_true)
print(a_sum_axis1_true.shape)
a_sum_axis1_false = np.sum(a, axis=1, keepdims=False)
print(a_sum_axis1_false)
print(a_sum_axis1_false.shape)
'''
输出:
[[0]
 [1]
 [2]
 [1]
 [2]]
(5, 1)
[0 1 2 1 2]
(5,)
'''
a_sum_axis0_true = np.sum(a, axis=0, keepdims=True)
print(a_sum_axis0_true)
print(a_sum_axis0_true.shape)
a_sum_axis0_false = np.sum(a, axis=0, keepdims=False)
print(a_sum_axis0_false)
print(a_sum_axis0_false.shape)
'''
输出:
[[2 4 0]]
(1, 3)
[2 4 0]
(3,)
'''

如果并不指定'axis'参数,输出的结果是相同的,区别在于当' keepdims = True'时,输出的是2D结果。

如果指定'axis'参数,输出的结果也是相同的,区别在于'keepdims = True'时,输出的是2D结果。

可以理解为'keepdims = True'参数是为了保持结果的维度与原始array相同。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文