今天写代码的时候,计算加权平均,一直没有搞懂np.average是怎么运算的,做个笔记记录一下:
创建一个(3,4,5)维度的np数组,然后在创建一个[1,0.5,1]的权重数组,计算他们的加权平均:
import numpy as np
# 创建一个(3,4,5)的集合
data=np.array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]],
[[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49],
[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59]]])
# 创建一个权重对象
weights=[1,0.5,1]
logits = np.average(data, axis=0,weights=weights)
输出结果为:
array([[20., 21., 22., 23., 24.],
[25., 26., 27., 28., 29.],
[30., 31., 32., 33., 34.],
[35., 36., 37., 38., 39.]])
logits.shape为(4,5)