2017-10-18 47 views
0

最近我遇到了一些我不太明白的Numpy练习。练习以3D阵列使用一些随机样本数据:什么时候是:相当于Numpy中的完整索引向量?

import numpy as np 

alpha = np.full(2000, .1) 
beta = np.full(100, .1) 

wordsInTopic = np.random.dirichlet(alpha, 100) 

produced = np.zeros((50, 100, 2000)) 

for doc in range(0, 50): 

    topicsInDoc = np.random.dirichlet(beta) 
    wordsToTopic = np.random.multinomial(2000, topicsInDoc) 

    for topic in range(0, 100): 
     produced[doc, topic] = np.random.multinomial(wordsToTopic[topic], wordsInTopic[topic]) 

例如下面是等价的,因为预期:

print(produced[:, np.arange(0, 100, 1), :].shape) 
print(produced[:, :, :].shape) 

但以下是不:

print(produced[:, np.arange(0, 100, 1), produced.sum(0).argmax(1)].shape) 
print(produced[:, :, produced.sum(0).argmax(1)].shape) 

有人能解释这里发生了什么吗?

+0

':'指定沿轴的每个索引,就这些了。 –

+0

您正在触发前者的高级索引。去谷歌上查询。 – Divakar

回答

1

总之,:基本上说“选择这个轴的所有内容”,同时传递一个索引列表“从这个轴选择给定的索引”。

当您只有一个索引列表时,两者可以是等效的。它很容易看到一个小的,二维矩阵:

>>> X = np.random.randint(0, 10, size=(3, 3)) 
>>> X 
array([[2, 4, 8], 
     [0, 6, 9], 
     [4, 2, 5]]) 
>>> X[:, :] 
array([[2, 4, 8], 
     [0, 6, 9], 
     [4, 2, 5]]) 
>>> X[:, [0, 1, 2]] 
array([[2, 4, 8], 
     [0, 6, 9], 
     [4, 2, 5]]) 

这样才有意义。现在,当您使用两个索引列表时,numpy的语义表明这些索引是成对匹配的(或者更一般地说,它们一起广播)。考虑以下几点:

>>> X[[0, 1, 2], [0, 1, 2]] 
array([2, 6, 5]) 

它返回(0, 0)元素,该元素(1, 1)(2, 2)元素。这种索引(您通过索引列表)被称为花式索引,并且可以非常强大。你可以阅读更多花哨的索引,并看到一些例子,here(完全披露:这个链接到我自己的网站)。