Differences between index-assignment in Numpy and Theano's set_subtensor()

邮差的信 提交于 2019-12-12 21:06:49

问题


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

回答1:


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])


来源:https://stackoverflow.com/questions/32813590/differences-between-index-assignment-in-numpy-and-theanos-set-subtensor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!