将数组中列的元素规范化为1或-1,具体取决于其符号

时间:2022-03-07 04:18:39

I want to normalize the elements of columns in array ‘x’, which contains both positive and negative numbers, to -1, or 1.

我想将数组'x'中包含正数和负数的列的元素规范化为-1或1。

Negative elements of x should be normalized to x.min of each column where x.min becomes - 1, and positive elements of x should be normalized to x.max of each column where x.max becomes 1. Zero values should remain zero.

x的负元素应归一化为每列的x.min,其中x.min变为-1,x的正元素应归一化为x.max变为1的每列的x.max.零值应保持为零。

I can get part of the way there using:

我可以使用以下方式:

x = np.array([[ 1,  3,  1  ],
              [-2, -5, -0.5],
              [-3, -1,  1.5],   
              [ 2,  7,  2  ]])

x_norm = x / x.max(axis=0)

print(x_norm)
[[ 0.5         0.42857143  0.5       ]
 [-1.         -0.71428571 -0.25      ]
 [-1.5        -0.14285714  0.75      ]
 [ 1.          1.          1.        ]]

But really I want the result to be:

但我真的希望结果如下:

print(x_norm)
[[ 0.5         0.42857143  0.5       ]
 [-0.66       -1.         -1.        ]
 [-1.         -0.2         0.75      ]
 [ 1.          1.          1.        ]]

1 个解决方案

#1


6  

You can check the condition with np.where and apply two different normalizations based on the condition:

您可以使用np.where检查条件,并根据条件应用两种不同的规范化:

np.where(x<0, -x / x.min(axis=0), x / x.max(axis=0))
Out[6]: 
array([[ 0.5       ,  0.42857143,  0.5       ],
       [-0.66666667, -1.        , -1.        ],
       [-1.        , -0.2       ,  0.75      ],
       [ 1.        ,  1.        ,  1.        ]])

#1


6  

You can check the condition with np.where and apply two different normalizations based on the condition:

您可以使用np.where检查条件,并根据条件应用两种不同的规范化:

np.where(x<0, -x / x.min(axis=0), x / x.max(axis=0))
Out[6]: 
array([[ 0.5       ,  0.42857143,  0.5       ],
       [-0.66666667, -1.        , -1.        ],
       [-1.        , -0.2       ,  0.75      ],
       [ 1.        ,  1.        ,  1.        ]])