python、numpy 、pytorch高级切片索引,[]放数组。

您所在的位置:网站首页 python数组索引图 python、numpy 、pytorch高级切片索引,[]放数组。

python、numpy 、pytorch高级切片索引,[]放数组。

#python、numpy 、pytorch高级切片索引,[]放数组。| 来源: 网络整理| 查看: 265

python、numpy 、pytorch高级切片索引,[]里面放数组。

只实验了二维数组,表示对同一个维度进行多次切片,二维数组每行的值为每次的切片索引,有n行就切片n次,同时把该维度切成n个维度。 numpy和pytorch结果一样,只放了numpy代码。

直接上结果:

import numpy as np a=np.random.randn(2,3,4) b=[[1,2],[0,1]] c=a[:,b,:] print(a) print("c--------") print(c)

结果:

[[[-1.49800039 0.58922711 0.93803902 0.87814673] [ 0.31813503 0.61408442 -0.43424169 0.01723555] [ 0.88257481 0.43878342 0.25124952 0.28165291]] [[ 0.50707757 -1.04502387 1.02290272 -1.34753527] [-2.84167515 1.777284 -0.49271416 0.23517798] [ 1.75211101 -0.49689842 -1.84401291 -1.82799111]]] c-------- [[[[ 0.31813503 0.61408442 -0.43424169 0.01723555] [ 0.88257481 0.43878342 0.25124952 0.28165291]] [[-1.49800039 0.58922711 0.93803902 0.87814673] [ 0.31813503 0.61408442 -0.43424169 0.01723555]]] [[[-2.84167515 1.777284 -0.49271416 0.23517798] [ 1.75211101 -0.49689842 -1.84401291 -1.82799111]] [[ 0.50707757 -1.04502387 1.02290272 -1.34753527] [-2.84167515 1.777284 -0.49271416 0.23517798]]]]

打印形状

print(a.shape) print("c--------") print(c.shape) (2, 3, 4) c-------- (2, 2, 2, 4)

补充:后面看代码发现不对劲,又加个新的实验:

import numpy as np a=np.random.randn(2,3,4) b=[[1,2],[0,1]] d=[[0],[1]] c=a[d,b,:] print(a) print("c--------") print(c) [[[-1.35228819 1.63435636 -0.34565672 0.84414161] [-0.14872702 -1.03662345 -0.40969845 -0.90026686] [-0.52720655 0.82482226 0.07821771 1.49102265]] [[-1.71620832 -1.10852628 -0.94867257 -2.42966257] [ 1.57493612 1.64461755 -0.33925698 -0.63227565] [-0.9511253 1.36616056 -0.37967324 1.91686236]]] c-------- [[[-0.14872702 -1.03662345 -0.40969845 -0.90026686] [-0.52720655 0.82482226 0.07821771 1.49102265]] [[-1.71620832 -1.10852628 -0.94867257 -2.42966257] [ 1.57493612 1.64461755 -0.33925698 -0.63227565]]] print(a.shape) print("c--------") print(c.shape) (2, 3, 4) c-------- (2, 2, 4)

两个维度里两个数组,结果最后维度数量不变。可以理解为后面二维数组的每行只去切前面二维数组的那行,如b[1,2]去切第一维的索引1,如d的[0]。然后b的[0,1]去切第一维的索引[1],如d的[1]。所以当b的行数等于d的行数,就会出现这种效果。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3