栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

✨Pytorch 基础 1 -- Tensor

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

✨Pytorch 基础 1 -- Tensor

目录

Create Tensor 

Oprations on Tensor


Create Tensor 
#create tensors with specific dimension
a = torch.tensor(5, device = "cpu")
c = torch.empty(2, 3)
k = torch.ones(2, 2, dtype = torch.int). # torch.float16
t = torch.randn(2, 2)

#check the size:
k.size()

#create a tensor from list 
d = torch.tensor([1, 2, 3])

Oprations on Tensor
  1. Plus, Minus, Multiplication, Diviation
    z = x + y
    z = torch.add(x, y)
    z = y.add_(x)     # dash line means inplace operation 
    
    z = x - y 
    z = torch.sub(x, y)
    
    z = x*y
    z = torch.mul(x, y)
    
    z = x/y
    z = torch.div(x, y) 
  2. slicing & Reshape        
    #slicing:
    x = torch.randn(5, 3)
    print(x[:, 0]) # select all the rows and the first column 
    
    
    #When you have only one element in your tensor, you can use the .item() to get specific value 
    value = x[1,1].item()
    
    # reshape a tensor: the total number of elements must still be the same 
    x = torch.randn(4, 4)
    y = x.view(16)
    y = x.view(-1, 8) # specify the number of column but leave the number of rows caculated by python self
  3. Numpy — Tensor (can only operate on cpu)

    # a and b share cpu memory now, if we modify one of them, the other one will change accordingly
    
    a = torch.ones(5)
    b = a.numpy()
    
    a = np.ones(5)
    b = torch.from_numpy(a)
  4. Create a Tensor on GPU

    # How to create a Tensor on GPU 
    if torch.cuda.is_available():
    	device = torch.device("cuda")
    x = torch.randn(5, device = device)
    y = torch.randn(5)
    y.to(device)
    
    # numpy can't handle gpu tensor 
    print(y.numpy())    ----- Erro 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/341458.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号