Differences between index-assignment in Numpy and

2019-07-17 08:30发布

I am trying to do index-assignment in Theano using set_subtensor(), but it is giving different results to Numpy's index-assignment. Am I doing something wrong, or is this a difference in how set_subtensor and Numpy's index-assignment work?

What I want to do:

X = np.zeros((2, 2))
X[[[0, 1], [0, 1]]] = np.array([1, 2])

X is now:
[[ 1.  0.]
 [ 0.  2.]]

Trying to do the same thing in Theano:

X = theano.shared(value=np.zeros((2, 2)))
X = T.set_subtensor(X[[[0, 1], [0, 1]]], np.array([1, 2]))
X.eval()

Raises this error

ValueError: array is not broadcastable to correct shape

标签: theano
1条回答
唯我独甜
2楼-- · 2019-07-17 09:00

This highlights a subtle difference between numpy and Theano but it can be worked around easily.

Advanced indexing can be enabled in numpy by using a list of positions or a tuple of positions. In Theano, one can only use a tuple of positions.

So changing

X = T.set_subtensor(X[[[0, 1], [0, 1]]], np.array([1, 2]))

to

X = T.set_subtensor(X[([0, 1], [0, 1])], np.array([1, 2]))

solves the problem in Theano.

One continues to get the same result in numpy if one changes

X[[[0, 1], [0, 1]]] = np.array([1, 2])

to

X[([0, 1], [0, 1])] = np.array([1, 2])
查看更多
登录 后发表回答