当is:等价于Numpy中的索引的完全向量时?

2024-04-25 15:27:00 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我遇到了一些我不太懂的裸体运动。练习使用三维阵列中的一些随机样本数据:

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)

有人能解释一下这是怎么回事吗?你知道吗


Tags: inalphafortopicdocnprangerandom
1条回答
网友
1楼 · 发布于 2024-04-25 15:27:00

简而言之,:本质上说是“选择这个轴上的所有内容”,而传递一个索引列表说是“从这个轴上选择给定的索引”。你知道吗

当您只有一个索引列表时,这两个索引可以是等价的。使用小的2D矩阵更容易看到:

>>> 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(完全公开:这是我自己网站的链接)。你知道吗

相关问题 更多 >