pytorch numpy关于维度的代码参考

numpy篇 https://blog.csdn.net/blog_empire/article/details/39298557

一,维度增减

1、直接修改shape

y=np.arange(1, 11)#shape:(10,)

y.shape=(10,1)

print(y)

2、用np.newaxis(np.newaxis == None)

np.newaxis放的位置不一样,效果不一样

y=np.arange(1, 11)#shape:(10,)

y=y[:,np.newaxis]

print(y)

3、使用np.expand_dims()

y=np.arange(1, 11)#shape:(10,)

y=np.expand_dims(y,axis = 1)

print(y)

4、只有np.squeeze() 没有np.unsqueeze()

y=np.arange(1, 11)#shape:(10,)

y=np.expand_dims(y,axis = 1)

y=np.squeeze(y,axis = 1)

print(y)

二、维度拼接

1、 np.c_[]按行拼接,np.r_[]按列拼接

a = np.random.randn(2,3)

b = np.random.randn(2,3)

c = np.c_[a,b]

print(c)

2、np.hstack,np.vstack,np.dstack,np.stack

a = np.random.randn(2,3)

b = np.random.randn(2,3)

c = np.hstack((a,b))#注意参数

print(c)

#注意:np.stack和np.hstack,np.vstack有很大的不同,np.stack是增加了维度的拼接

 arrays = [np.random.randn(3, 4) for _ in range(10)]     # 利用列表生成式生成一个10*3*4的列表

np.stack(arrays, axis=0).shape         # (10, 3, 4)

3、np.concatenate

a = np.random.randn(2,3)

b = np.random.randn(2,3)

c = np.concatenate((a, b), axis=1)

print(c)

4、类似python list append使用np.append()

此外还有np.delete(),np.insert()

三、自身数据维度内交换

1、np.transpose交换多维度数据

a = np.random.randn(2,3,4)

print(a.shape)

b = np.transpose(a,(2,0,1))

print(b.shape)

2、交换二维数据可用np.transpose或者T()

a = np.random.randn(2,3)

print(a)

b = a.T    #np.transpose(a)

print(b)

四、以某种维度查看数据,和维度交换是不一样的,数据在内存中结构不变

1、np.reshape()

a = np.random.randn(2,3)

print(a)

b = np.reshape(a,(3,2))

print(b)

2、以一维数据形式查看x.ravel(),x.flatten()

a = np.random.randn(2,3)

print(a)

b = a.flatten()

print(b)

 

pytorch篇

一,维度增减

1、torch.squeeze,torch.unsqueeze

a = torch.randn(2,3)

print(a.size())

b = torch.unsqueeze(a,2) #后面的参数2代表在index为2的维度增加一维

print(b.size())

二、维度拼接

1、torch.cat()

a = torch.randn(2,3)

b = torch.randn(2,3)

print(a)

c = torch.cat((a,b),1)

print(c)

2、torch.stack()

a = torch.randn(2,3)

b = torch.randn(2,3)

print(a)

c = torch.stack((a,b),0)

print(c.size())

print(c)

3、expand,repeat,narrow等

三、自身数据维度内交换

1、torch.transpose只能交换二维数据

a = torch.randn(2,3)

print(a)

b = a.transpose(1,0)

print(b)

2、torch.permute交换多维数据

a = torch.randn(2,3,4)

print(a)

b = a.permute(2,1,0)

print(b)

四、以某种维度查看数据,和维度交换是不一样的,数据在内存中结构不变

1、tensor.view()

view只能用在contiguous的variable上。如果在view之前用了transpose,permute等,需要用contiguous()来返回一个contiguous copy

a = torch.randn(2,3)

print(a)

b = a.view(3,2)

print(b)

2、torch.reshape(),这个与numpy.reshape 的功能类似。它大致相当于tensor.contiguous().view()

一些小技巧代码片段

一,numpy

>>> n_x3 = np.array(x3)
>>> n_x3
array([0.1, 0.2, 0.3])
>>> n_x4 = n_x3[[2,2,1,1,1,2,0]]    ##############numpy用idx给扩展赋值 idx可以用list或者np array扩展都行
>>> n_x4
array([0.3, 0.3, 0.2, 0.2, 0.2, 0.3, 0.1])

 

 

 

二,torch

>>> t_x = torch.from_numpy(x)
>>> t_x
tensor([[ 1.5228, -1.5240, -1.3225,  0.5608, -0.8209,  0.0349],
        [-1.0126, -1.1155, -1.1779, -0.0450, -0.6270,  0.5286],
        [ 0.0656,  0.2860,  0.4819, -0.7166, -0.0462,  0.3427]],
       dtype=torch.float64)
>>> x1 = t_x.select(1,0)    ##########tensor.select(dim,index)用法
>>> x1
tensor([ 1.5228, -1.0126,  0.0656], dtype=torch.float64)
>>> x1.lt(0)    ###############tensor.lt  gt  ge用法
tensor([0, 1, 0], dtype=torch.uint8)    #########产生的是掩码0,1
>>> x1.gt(0)
tensor([1, 0, 1], dtype=torch.uint8)
>>> x1.ge(0)
tensor([1, 0, 1], dtype=torch.uint8)
>>> idx = x1.gt(0)    ##############用tensor掩码给相应位置赋值
>>> x1[idx] = 1
>>> x1
tensor([ 1.0000, -1.0126,  1.0000], dtype=torch.float64)

>>> x2 = x1[(2,2,1,1,2,0,0,1)]    ##############不能用tuple
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: too many indices for tensor of dimension 1
>>> x2 = x1[[2,2,1,1,2,0,0,1]]    ##############tensor用list idx给扩展赋值
>>> x2
tensor([ 1.0000,  1.0000, -1.0126, -1.0126,  1.0000,  1.0000,  1.0000, -1.0126],
       dtype=torch.float64)

 

一,numpy.where

numpy.where() 有两种用法:

1. np.where(condition, x, y)

满足条件(condition),输出x,不满足输出y。


如果是一维数组,相当于[xv if c else yv for (c,xv,yv) in zip(condition,x,y)]

>>> aa = np.arange(10)
>>> np.where(aa,1,-1)
array([-1,  1,  1,  1,  1,  1,  1,  1,  1,  1])  # 0为False,所以第一个输出-1
>>> np.where(aa > 5,1,-1)
array([-1, -1, -1, -1, -1, -1,  1,  1,  1,  1])

>>> np.where([[True,False], [True,True]],    # 官网上的例子
             [[1,2], [3,4]],
             [[9,8], [7,6]])
array([[1, 8],
       [3, 4]])

上面这个例子的条件为[[True,False], [True,False]],分别对应最后输出结果的四个值。第一个值从[1,9]中选,因为条件为True,所以是选1。第二个值从[2,8]中选,因为条件为False,所以选8,后面以此类推。类似的问题可以再看个例子:

>>> a = 10
>>> np.where([[a > 5,a < 5], [a == 10,a == 7]],
             [["chosen","not chosen"], ["chosen","not chosen"]],
             [["not chosen","chosen"], ["not chosen","chosen"]])

array([['chosen', 'chosen'],
       ['chosen', 'chosen']], dtype='<U10')


 

2. np.where(condition)

只有条件 (condition),没有x和y,则输出满足条件 (即非0) 元素的坐标 (等价于numpy.nonzero)。这里的坐标以tuple的形式给出,通常原数组有多少维,输出的tuple中就包含几个数组,分别对应符合条件元素的各维坐标。

>>> a = np.array([2,4,6,8,10])
>>> np.where(a > 5)             # 返回索引
(array([2, 3, 4]),)   
>>> a[np.where(a > 5)]              # 等价于 a[a>5]
array([ 6,  8, 10])

>>> np.where([[0, 1], [1, 0]])
(array([0, 1]), array([1, 0]))

上面这个例子条件中[[0,1],[1,0]]的真值为两个1,各自的第一维坐标为[0,1],第二维坐标为[1,0] 。


下面看个复杂点的例子:

>>> a = np.arange(27).reshape(3,3,3)
>>> a
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

>>> np.where(a > 5)
(array([0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2]),
 array([2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2]),
 array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]))


# 符合条件的元素为
       [ 6,  7,  8]],

      [[ 9, 10, 11],
       [12, 13, 14],
       [15, 16, 17]],

      [[18, 19, 20],
       [21, 22, 23],
       [24, 25, 26]]]

所以np.where会输出每个元素的对应的坐标,因为原数组有三维,所以tuple中有三个数组。

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值