How to row-normalize a feature matrix? Broadcasting error

Viewed 52

I have a feature matrix that I want to row normalize.

This is what I have done based on min-max scaling and I am getting an error. Can anyone help me with this error.

a = np.random.randint(10, size=(4,5))
s=a.max(axis=1) - a.min(axis=1)
np.amax(a,axis=1)
print(s)

(a - a.min(axis=1))/(a.max(axis=1) - a.min(axis=1))\

>>[7 6 4 5]
      4 print(s)
      5 
----> 6 (a - a.min(axis=1))/(a.max(axis=1) - a.min(axis=1))

ValueError: operands could not be broadcast together with shapes (4,5) (4,)

2 Answers

Try to work with transposed matrix:

b = a.T
m = (b - b.min(axis=0)) / (b.max(axis=0) - b.min(axis=0))
m = m.T
>>> a
array([[2, 3, 2, 8, 3],   # min=2 -> 0, max=8 -> 1
       [3, 3, 9, 2, 1],   # min=1 -> 0, max=9 -> 1
       [1, 9, 8, 4, 7],   # min=1 -> 0, max=9 -> 1
       [6, 8, 7, 9, 4]])  # min=4 -> 0, max=9 -> 1

>>> m
array([[0.        , 0.16666667, 0.        , 1.        , 0.16666667],
       [0.25      , 0.25      , 1.        , 0.125     , 0.        ],
       [0.        , 1.        , 0.875     , 0.375     , 0.75      ],
       [0.4       , 0.8       , 0.6       , 1.        , 0.        ]])

I have an alternative solution , I am not sure if this one is correct.Would be great if someone can comment on it.

def row_normalize(mf):
  row_sums = np.array(mf.sum(1))
  new_matrix = mf / row_sums[:, np.newaxis]
  return new_matrix
Related