✨Pytorch 基础 1 -- Tensor

本文主要介绍了PyTorch中Tensor的创建及基本操作,包括加减乘除、切片和重塑,还提到了如何在GPU上创建Tensor进行运算,是深度学习和人工智能从业者了解PyTorch的入门指南。
摘要由CSDN通过智能技术生成

目录

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 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值