简体   繁体   English

使用numpy将向量转换为遮罩矩阵

[英]Convert a vector to a mask matrix using numpy

Assume we have the following vector: 假设我们有以下向量:

v = np.array([4, 0, 1])

The goal is to create the 5 x 3 matrix M as follows: 目的是创建5 x 3矩阵M ,如下所示:

[[0 1 0]
 [0 0 1]
 [0 0 0]
 [0 0 0]
 [1 0 0]]

Only one element in each column is equal to 1 for the corresponding index in v . v相应索引的每一列中只有一个元素等于1。 For example, since v[0] is 4 then M[4, 0] == 1 , and since v[2] is 1 then M[1, 2] == 1 . 例如,由于v[0]为4,则M[4, 0] == 1 ,由于v[2]为1,则M[1, 2] == 1

How can I build such a matrix in Python using scipy and numpy? 如何使用scipy和numpy在Python中建立这样的矩阵? In MATLAB you can do this with the sparse and full functions in a single line. 在MATLAB中,您可以在一行中使用sparse函数和full函数来执行此操作。 I'd prefer not to use a for loop since I am looking for a vectorized implementation of this. 我不希望使用for循环,因为我正在寻找对此的矢量化实现。

You can do: 你可以做:

from scipy import sparse

inds = np.array([4, 0, 1])
values = np.ones_like(inds)       # [1, 1, 1]
index = np.arange(inds.shape[0])  # 3
m = sparse.csc_matrix((values, (inds, index)), shape=(5, 3))

Output: 输出:

>>> m.todense()
matrix([[0, 1, 0],
        [0, 0, 1],
        [0, 0, 0],
        [0, 0, 0],
        [1, 0, 0]])

If you want a dense array output, you could just use two integer arrays to index the rows/cols of the nonzero elements: 如果需要密集的数组输出,则可以使用两个整数数组来索引非零元素的行/列:

v = np.array([4, 0, 1])
x = np.zeros((5, 3), np.int)
x[v, np.arange(3)] = 1

print(x)
# [[0 1 0]
#  [0 0 1]
#  [0 0 0]
#  [0 0 0]
#  [1 0 0]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM