np数组的一维二维问题以及np.average里的weights问题

np数组的一维二维问题以及np.average里的weights问题

X = np.arange(10).reshape(5, 2)   # 5*2
# print(X.shape)
W = np.array([1,1,1,2,2]).reshape(-1, 1)   # 5*1
# print(W.shape)
# Mean = np.zeros((2, 1))
# print(W)
# print(Mean.shape)
# Mean = np.average(X, axis=1, weights=W)
print(np.average(X, axis=0, weights=W))

我想求X的加权均值,但出错了

TypeError: 1D weights expected when shapes of a and weights differ.

我百思不得其解,于是查看官方解释
numpy.average(a, axis=None, weights=None, returned=False)
里面的weights是这样描述的
weights : array_like, optional
An array of weights associated with the values in a. Each value ina contributes to the average according to its associated weight.The weights array can either be 1-D (in which case its length must bethe size of a along the given axis) or of the same shape as a.If weights=None, then all data in a are assumed to have aweight equal to one.
与a中的值相关联的一组权重。ina中的每个值根据其关联的权重对平均值做出贡献。权值数组可以是一维的(在这种情况下,它的长度必须是沿给定轴的a的大小),也可以是与a相同的形状。如果权值为None,则假设a中的所有数据的权值都为1。
但是我的W就是和a一样的维度啊。
终于,在询问了大佬后才知道

W = np.array([1,1,1,2,2]).reshape(-1, 1)   # 5*1
print(W)

输出结构

[[1]
 [1]
 [1]
 [2]
 [2]]
(5, 1)

很明显,我这个权重是二维的,中括号嵌套有两层。
而我如果要沿axies=0(列)求加权平均值且不和X的维度一样,就必须是一维的。因此,我改为一维向量

W = np.array([1,1,1,2,2])   # 必须是一维
print(W)
print(W.shape)

输出为

[1 1 1 2 2]
(5,)

而我也成功求到了沿着列的加权均值

X = np.arange(10).reshape(5, 2)   # 5*2
# print(X.shape)
W = np.array([1,1,1,2,2])   # 必须是一维
# print(W)
# print(W.shape)
# Mean = np.zeros((2, 1))
# print(W)
# print(Mean.shape)
# Mean = np.average(X, axis=1, weights=W)
print(np.average(X, axis=0, weights=W))

结果

[4.85714286 5.85714286]
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值