Numpy:如何使用在另一个矩阵的行中找到的索引来索引一个矩阵的行?
Numpy: How can I index the rows of one matrix using indices found in the rows of another?
我有两个 (2000, 10) 矩阵:weight_values
包含一组值,weight_indexes
包含一组用作新矩阵索引的整数。
我想使用新的 (2000, 2000) 零矩阵中的 weight_indexes
到 select 个条目,然后将这些列设置为在值矩阵中找到的值。
例如,这样做可以得到我想要的东西:
weights = np.zeros((2000, 2000))
for i in range(weight_indexes.shape[0]):
weights[i, weight_indexes[i]] = weight_values[i]
但是,当我尝试使用数组索引执行此操作时,它不起作用。索引 weights
使用 weight_indexes
像这样:
weights[:, weight_indexes[:]]
...而不是 select 从 weights
中提取适当的列,这会创建一个新的 (2000, 2000, 10) 大小的矩阵。
有没有一些矢量化的方法可以在不使用循环的情况下做到这一点?
Python 奇特的索引一起广播。如果要在weights
的每一行中设置10个元素,请将i
广播为与weight_indexes
相同的形状:
weights[np.arange(len(weight_indexes))[:, None], weight_indexes] = weight_values
我有两个 (2000, 10) 矩阵:weight_values
包含一组值,weight_indexes
包含一组用作新矩阵索引的整数。
我想使用新的 (2000, 2000) 零矩阵中的 weight_indexes
到 select 个条目,然后将这些列设置为在值矩阵中找到的值。
例如,这样做可以得到我想要的东西:
weights = np.zeros((2000, 2000))
for i in range(weight_indexes.shape[0]):
weights[i, weight_indexes[i]] = weight_values[i]
但是,当我尝试使用数组索引执行此操作时,它不起作用。索引 weights
使用 weight_indexes
像这样:
weights[:, weight_indexes[:]]
...而不是 select 从 weights
中提取适当的列,这会创建一个新的 (2000, 2000, 10) 大小的矩阵。
有没有一些矢量化的方法可以在不使用循环的情况下做到这一点?
Python 奇特的索引一起广播。如果要在weights
的每一行中设置10个元素,请将i
广播为与weight_indexes
相同的形状:
weights[np.arange(len(weight_indexes))[:, None], weight_indexes] = weight_values