I have a numpy matrix with shape (x,y)
. I want to get a tensor which is a vertical stack of y
vectors with shape (x,1)
. Lets say I have the following matrix:
array([[ 1., 2.],
[ 1., 2.],
[ 1., 2.]])
when I do np.reshape(2,3,1)
. I will get:
array([[[ 1.],
[ 2.],
[ 1.]],
[[ 2.],
[ 1.],
[ 2.]]])
but I want this:
array([[[ 1.],
[ 1.],
[ 1.]],
[[ 2.],
[ 2.],
[ 2.]]])
In [135]: arr=np.array([[1,2],[1,2],[1,2]])
In [136]: arr.shape
Out[136]: (3, 2)
In [137]: arr.transpose()
Out[137]:
array([[1, 1, 1],
[2, 2, 2]])
In [138]: arr.transpose()[:,:,None]
Out[138]:
array([[[1],
[1],
[1]],
[[2],
[2],
[2]]])
You want a shape (2,3,1). Starting with (3,2), that means you have to switch the 2 axes, and add one. That can be done in either order. Here I choose transpose to do the switch, and [:,:,None]
to add the dimension.
arr.reshape(3,2,1).swapaxes(0,1)
also works. More obscurely, np.stack(arr[:,:,None],1)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.