Home > other >  Normalize positive and negative values separately
Normalize positive and negative values separately

Time:09-14

I have a matrix where I want the positive values to be normalized by dividing by the max positive value such that the maximum value is 1, and the negative values to be normalized by the min negative value such that the most negative value is -1. For example,

[[   1.    4. -100.]
 [   3.   10.   -8.]]

becomes

[[ 0.1 0.4 -1. ] [ 0.3 1. -0.08]].

I tried

def sym_min_max_norm(mat):
    res = np.divide(mat, np.max(mat), where = mat > 0)
    res = np.divide(res, -np.min(res), where = res < 0)
    return res

but this doesn't seem to work. Maybe I'm using the where condition wrong in np.divide?

CodePudding user response:

Assuming that the source array is a, you can get the result running:

result = np.where(a >= 0, a/np.max(a), -a/np.min(a))

Just a single-liner.

CodePudding user response:

The following code gives me the correct result, but I'm not sure why the original solution didn't work.

def sym_min_max_norm(mt):
    pos = mt > 0
    neg = mt < 0
    res = mt * (pos/np.max(mt) - neg/np.min(mt))
    return res
  • Related