【问题标题】:Theano advanced indexing for tensor, shared index用于张量、共享索引的 Theano 高级索引
【发布时间】:2015-07-09 22:13:25
【问题描述】:

我有一个张量 probsprobs.shape = (max_time, num_batches, num_labels)

我有一个张量targetstargets.shape = (max_seq_len, num_batches),其中的值是标签索引,即probs 中的第三维。

现在我想得到一个张量probs_yprobs.shape = (max_time, num_batches, max_seq_len),其中第三维是targets 中的索引。基本上

probs_y[:,i,:] = probs[:,i,targets[:,i]]

所有0 <= i < num_batches

我怎样才能做到这一点?

here 发布了类似的解决方案。

如果我理解正确的话,那里的解决方案是:

probs_y = probs[:,T.arange(targets.shape[1])[None,:],targets]

但这似乎不起作用。我得到: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices.

另外,时间T.arange 的创建不是有点昂贵吗?特别是当我尝试通过真正使其成为一个完整的密集整数数组来解决问题时。应该有更好的办法。

也许theano.map?但据我了解,这不会并行化代码,所以这也不是解决方案。

【问题讨论】:

  • 刚刚意识到我所做的与您的行不同的是我在T.arangetargets 中都调换了轴。这很奇怪。在这种情况下,您的也应该有效。
  • 好的,你这样做的方式也有效,我更新了我的答案。所以问题出在其他地方。 Theano 版本或与此特定操作无关的内容 - 尽管给出错误消息,但后者似乎不太可能。

标签: python theano


【解决方案1】:

这对我有用:

import theano
import theano.tensor as T

max_time, num_batches, num_labels = 3, 4, 6
max_seq_len = 5

probs_ = np.arange(max_time * num_batches * num_labels).reshape(
    max_time, num_batches, num_labels)

targets_ = np.arange(num_batches * max_seq_len).reshape(max_seq_len, 
    num_batches) % (num_batches - 1)  # mix stuff up

probs, targets = map(theano.shared, (probs_, targets_))

print probs_
print targets_

probs_y = probs[:, T.arange(targets.shape[1])[:, np.newaxis], targets.T]

print probs_y.eval()

以上使用了您的索引的转置版本。你的确切提议也有效

probs_y2 = probs[:, T.arange(targets.shape[1])[np.newaxis, :], targets]

print probs_y2.eval()
print (probs_y2.dimshuffle(0, 2, 1) - probs_y).eval()

所以也许你的问题出在其他地方。

至于速度,我不知道还有什么比这更快。 map,这是 scan 的一个专业化,几乎可以肯定不是。我不知道arange 实际构建到什么程度,而不是简单地迭代。

【讨论】:

  • 谢谢,我的例子实际上也有效。在我的测试代码中,probs 错误地仍然是numpy.ndarray。 :P
  • Aaaah OK - 我以前一定也这样做过,因为错误消息看起来很熟悉。
猜你喜欢
  • 2020-07-20
  • 2016-06-23
  • 2018-06-08
  • 2019-10-31
  • 2021-12-30
  • 2017-04-26
  • 2019-07-15
  • 2020-09-26
  • 1970-01-01
相关资源
最近更新 更多