计算行向量和平均行向量之间的差异?

时间:2013-02-05 06:03:18

标签: python

假设矩阵是M =

[[.10, .32, .20, .40, .80], 
 [.23, .18, .56, .61, .12], 
 [.90, .30, .60, .50, .30], 
 [.34, .75, .91, .19, .21]]

平均行向量是rav =

[ 0.3925  0.3875  0.5675  0.425   0.3575]

我想从上面矩阵(M)中的每个行向量中减去平均行向量(rav) 即M(i)-rav。 我怎样才能以有效的方式做到这一点?

2 个答案:

答案 0 :(得分:1)

假设你正在使用numpy,这很简单:

M = np.asarray(M) # make sure M is an array...it presumably would be
rav = np.mean(M, axis=0)
diffs = M - rav

由于broadcasting而有效。

如果您使用普通列表,它会更复杂一点,代码会慢很多,但是这样的事情应该这样做:

# M is a list of num_rows lists of num_cols floats
rav = [sum(row[j] for row in M) / num_rows for j in range(num_cols)]
diffs = [[x - mean_x for x, mean_x in zip(row, rav)] for row in M]

答案 1 :(得分:1)

纯Python

>>> [[i-j for i,j in zip(m, rav)] for m in M]
[[-0.2925, -0.0675, -0.3675, -0.024999999999999967, 0.44250000000000006], [-0.1625, -0.20750000000000002, -0.007499999999999951, 0.185, -0.2375], [0.5075000000000001, -0.08750000000000002, 0.03249999999999997, 0.07500000000000001, -0.057499999999999996], [-0.05249999999999999, 0.3625, 0.3425, -0.235, -0.1475]]

如果你正在做一堆矩阵运算,那么使用numpy会更快。转换为numpy矩阵是非常昂贵的。