本文介绍了在theano中使用索引矩阵索引张量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个theano张量A,使得A.shape =(40,20,5),一个theano矩阵B,使得B.shape =(40,20).我可以执行单行运算来获得矩阵C,其中C.shape =(40,20)并且C(i,j)= A [i,j,B [i,j]]用theano语法?

本质上,我想使用B作为索引矩阵;使用theano最有效/最优雅的方法是什么?

解决方案

您可以在numpy中执行以下操作:

import numpy as np

A = np.arange(4 * 2 * 5).reshape(4, 2, 5)
B = np.arange(4 * 2).reshape(4, 2) % 5

C = A[np.arange(A.shape[0])[:, np.newaxis], np.arange(A.shape[1]), B]

因此,您可以在theano中执行相同的操作:

import theano
import theano.tensor as T

AA = T.tensor3()
BB = T.imatrix()

CC = AA[T.arange(AA.shape[0]).reshape((-1, 1)), T.arange(AA.shape[1]), BB]

f = theano.function([AA, BB], CC)

f(A.astype(theano.config.floatX), B)

I have a theano tensor A such that A.shape = (40, 20, 5) and a theano matrix B such that B.shape = (40, 20). Is there a one-line operation I can perform to get a matrix C, where C.shape = (40, 20) and C(i,j) = A[i, j, B[i,j]] with theano syntax?

Essentially, I want to use B as an indexing matrix; what is the most efficient/elegant to do this using theano?

解决方案

You can do the following in numpy:

import numpy as np

A = np.arange(4 * 2 * 5).reshape(4, 2, 5)
B = np.arange(4 * 2).reshape(4, 2) % 5

C = A[np.arange(A.shape[0])[:, np.newaxis], np.arange(A.shape[1]), B]

So you can do the same thing in theano:

import theano
import theano.tensor as T

AA = T.tensor3()
BB = T.imatrix()

CC = AA[T.arange(AA.shape[0]).reshape((-1, 1)), T.arange(AA.shape[1]), BB]

f = theano.function([AA, BB], CC)

f(A.astype(theano.config.floatX), B)

这篇关于在theano中使用索引矩阵索引张量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 16:14