python零碎知识点(2019-8-19)

1 .item()

一个元素张量可以用item()得到元素值,请注意这里的print(x)和print(x.item())值是不一样的,一个是打印张量,一个是打印元素:

    x = torch.randn(2, 2)
    print(x[1, 1])
    print(x[1, 1].item())
#结果
tensor(0.4279)
0.4278833866119385

2. np.random.uniform() 与 np.random.randn()

   hr = np.random.uniform(0,2,(10,10,3))   从一个均匀分布([low, high):半开区间)中进行采样
    # 
    hr = np.random.randn(10,10,3)  返回一个样本,具有标准正太分布
    # 
    hr = np.random.rand(10,10,3) 返回一个或一组服从“0~1”均匀分布的随机样本值。随机样本取值范围是[0,1),不包括1

3. getattr()

获取对象object的属性或者方法

class test:
    name='alex'
    def run(self):
        pass
t=test()
print(getattr(t,'name'))        #alex
print(getattr(t,'run'))         #<bound method test.run of <__main__.test object at 0x0121FFB0>>
print(getattr(t,'age',12))      #12

4. Numpy 和Torch的shape()和size()

img = np.random.randn(100,100,3)
print(img.shape)    # 这里shape不带括号
print(img.shape[2])
print(img.size)		# 30000
print(np.size(img,2))   # 3

print(img.size[0])  # TypeError: 'int' object is not subscriptable
#因为size = 30000是一个整数类型,故不能使用下标来表示;若是list,tuple等类型,则可用下标
#还有一种会出现的情况,一维的数组却使用了二维形式的下标;如a=[1],则a[0][0]则报错

#torch的size用法与numpy不太相同
img1 = torch.randn(3,100,100)
print(img1.shape)       # torch.Size([3, 100, 100]) shape不带括号
print(img1.shape[2])    # 100      用法与numpy相同
print(img1.size())      # torch.Size([3, 100, 100]) 此处与numpy不同
print(img1.size(1))     # 打印img1第1维的长度
# 此处size和shape的用法相同

5. view和permute的区别

torch.reshape(),这个与numpy.reshape 的功能类似.reshape()可以替代view。它大致相当于tensor.contiguous().view()。一般来说可以用reshape替代 .contiguous().view()了
contiguous:view只能用在contiguous的variable上。如果在view之前用了transpose, permute等,需要用contiguous()来返回一个contiguous copy。
一种可能的解释是:
有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()操作依赖于内存是整块的,
这时只需要执行contiguous()这个函数,把tensor变成在内存中连续分布的形式

a = torch.tensor([1,2,3,4,5,6])
b =a.view(2,3)		# 按照行优先的顺序排成一个一维的数据
c = a.reshape(2,3)	

print(b)
print(c)
print(b.contiguous().permute(1,0))  # 维度转换(转置),行变成列,列变成行
print(a.view(3,2))

输出:
在这里插入图片描述
比较有用的链接:
pytorch中的cat、stack、tranpose、permute、unsqeeze的用法。https://www.cnblogs.com/yifdu25/p/9399047.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值