如何对矩阵的每一列进行缩放

4

这是我如何扩展单个向量的方法:

vector = np.array([-4, -3, -2, -1, 0])

# pass the vector, current range of values, the desired range, and it returns the scaled vector
scaledVector = np.interp(vector, (vector.min(), vector.max()), (-1, +1)) # results in [-1.  -0.5  0.   0.5  1. ]

如何将上述方法应用于给定矩阵的每一列?
matrix = np.array(
      [[-4, -4, 0, 0, 0],
      [-3, -3, 1, -15, 0],
      [-2, -2, 8, -1, 0],
      [-1, -1, 11, 12, 0],
      [0, 0, 50, 69, 80]])

scaledMatrix = [insert code that scales each column of the matrix]

请注意,scaledMatrix的前两列应该等于第一个例子中的scaledVector。对于上面的matrix,正确计算的scaledMatrix如下:
[[-1.         -1.         -1.         -0.64285714 -1.        ]
 [-0.5        -0.5        -0.96       -1.         -1.        ]
 [ 0.          0.         -0.68       -0.66666667 -1.        ]
 [ 0.5         0.5        -0.56       -0.35714286 -1.        ]
 [ 1.          1.          1.          1.          1.        ]]

我目前的方法(错误):

np.interp(matrix, (np.min(matrix), np.max(matrix)), (-1, +1))

看起来在scaledMatrix的第四列中有一个错误。P. Camilleri有正确的值。 - bfris
你对于一个常量列会有什么期望? - P. Camilleri
1个回答

2

如果您想手动完成并了解正在发生的事情:

首先,逐列减去最小值,使每列最小值为0。

然后通过列幅度(最大值-最小值)除以来使每列最大值为1。

现在每列的值都在0到1之间。如果您希望它在-1到1之间,则乘以2,然后减去1:

In [3]: mins = np.min(matrix, axis=0)

In [4]: maxs = np.max(matrix, axis=0)

In [5]: (matrix - mins[None, :]) / (maxs[None, :] - mins[None, :])
Out[5]: 
array([[ 0.        ,  0.        ,  0.        ,  0.17857143,  0.        ],
       [ 0.25      ,  0.25      ,  0.02      ,  0.        ,  0.        ],
       [ 0.5       ,  0.5       ,  0.16      ,  0.16666667,  0.        ],
       [ 0.75      ,  0.75      ,  0.22      ,  0.32142857,  0.        ],
       [ 1.        ,  1.        ,  1.        ,  1.        ,  1.        ]])

In [6]: 2 * _ - 1
Out[6]: 
array([[-1.        , -1.        , -1.        , -0.64285714, -1.        ],
       [-0.5       , -0.5       , -0.96      , -1.        , -1.        ],
       [ 0.        ,  0.        , -0.68      , -0.66666667, -1.        ],
       [ 0.5       ,  0.5       , -0.56      , -0.35714286, -1.        ],
       [ 1.        ,  1.        ,  1.        ,  1.        ,  1.        ]])

我使用[None, :]来告诉numpy,我在讨论“行向量”,而不是列向量。

否则,可以使用优秀的sklearn包,它的preprocessing模块有很多有用的转换器:

In [13]: from sklearn.preprocessing import MinMaxScaler

In [14]: scaler = MinMaxScaler(feature_range=(-1, 1))

In [15]: scaler.fit(matrix)
Out[15]: MinMaxScaler(copy=True, feature_range=(-1, 1))

In [16]: scaler.transform(matrix)
Out[16]: 
array([[-1.        , -1.        , -1.        , -0.64285714, -1.        ],
       [-0.5       , -0.5       , -0.96      , -1.        , -1.        ],
       [ 0.        ,  0.        , -0.68      , -0.66666667, -1.        ],
       [ 0.5       ,  0.5       , -0.56      , -0.35714286, -1.        ],
       [ 1.        ,  1.        ,  1.        ,  1.        ,  1.        ]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接