datascana
datascana

Reputation: 641

Calculate matrix column mean

I've got this matrix:

      [[[ 0.49757494  0.50242506]
      [ 0.50340754  0.49659246]
      [ 0.50785456  0.49214544]
         ..., 
      [ 0.50817149  0.49182851]
      [ 0.50658656  0.49341344]
      [ 0.49419885  0.50580115]]

      [[ 0.117       0.883     ]
      [ 0.604       0.396     ]
      [ 1.          0.        ]
         ..., 
      [ 0.98559675  0.01440325]
      [ 0.948       0.052     ]
      [ 0.012       0.988     ]]

      [[ 0.21099179  0.78900821]
      [ 0.75212493  0.24787507]
      [ 0.96653919  0.03346081]
           ..., 
      [ 0.97485074  0.02514926]
      [ 0.95051503  0.04948497]
      [ 0.05409603  0.94590397]]]

If the weights are w1,w2,w3, how can I calculate the mean of first column and second column for each matrix (3 by 2) ? So I can get like:

      [[[(X1        Y1]
        ...,
      [X2           Y2]
      [[X3          Y3]
        ...,

Thanks in advance.

EDIT: input shape is (3, 37375, 2), and I would like to have instead of a (3,2), a (1,2). I would like to get the mean for each column, example:

   (0.497*w1 + 0.503*w2 + 0.507*w3)/ (w1 + w2 + w3)     <--- First column

Upvotes: 1

Views: 1201

Answers (1)

Daniel F
Daniel F

Reputation: 14399

Assuming your input shape is (3,n,2) and you want the shape to be (n,3,2) you will want first to do

in=in.reshape((-1,3,2))

If you have a weighting vector w

w = np.random.rand(3)

Then you can do weighted average over the first axis with np.average (yielding (n,2)

out1 = np.average(in, weights = w, axis = 1)

Or you can do a weighted sum

out1 = np.sum(t*w[None,:, None], axis = 1) / np.sum(w)

Upvotes: 2

Related Questions