zoukankan      html  css  js  c++  java
  • Tensor和NumPy相互转换

      Tensor 和 NumPy 相互转换常使用 numpy()from_numpy() 。需要注意的是: 这两个函数所产生的 Tensor 和 NumPy 中的数组共享相同的内存(所以他们之间的转换很快),改变其中一个时另一个也会改变!
     
    Tensor 转 Numpy 数组
    a = torch.ones(3)
    b = a.numpy()
    print(a)
    print(b)
    
    tensor([1., 1., 1.])
    [1. 1. 1.]
    
    a +=  1
    print(a)
    print(b)
    
    a = a + 1
    print(a)
    print(b)
    
    tensor([3., 3., 3.])
    [3. 3. 3.]
    tensor([4., 4., 4.])
    [3. 3. 3.]
    
    a = torch.ones(3)
    b = a.numpy()
    print(a)
    print(b)
    b += 1
    print(a)
    print(b)
    b = b+1
    print(a)
    print(b)
    
    tensor([1., 1., 1.])
    [1. 1. 1.]
    tensor([2., 2., 2.])
    [2. 2. 2.]
    tensor([2., 2., 2.])
    [3. 3. 3.]

     

    NumPy 数组转 Tensor
    import numpy as np
    a = np.ones(3)
    b = torch.from_numpy(a)
    print(a, b)
    a += 1
    print(a, b)
    b += 1
    print(a, b)
    
    [1. 1. 1.] tensor([1., 1., 1.], dtype=torch.float64)
    [2. 2. 2.] tensor([2., 2., 2.], dtype=torch.float64)
    [3. 3. 3.] tensor([3., 3., 3.], dtype=torch.float64)

     

      使用 torch.tensor() 将 NumPy 数组转换成 Tensor(不再共享内存)
    c = torch.tensor(a)
    a += 1
    print(a, c)
    
    [4. 4. 4.] tensor([3., 3., 3.], dtype=torch.float64)
     
     
     
     

    因上求缘,果上努力~~~~ 作者:希望每天涨粉,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/15427954.html

  • 相关阅读:
    java 字符串截取
    字符编码Unicode-正则表达式验证
    APP数据加密解密
    ThreadLocal线程局部变量
    用Eclipse进行远程Debug代码
    JPA对应关系
    JPA名称规则
    dubbo环境搭建
    历史表更新数据
    api加密算法
  • 原文地址:https://www.cnblogs.com/BlairGrowing/p/15427954.html
Copyright © 2011-2022 走看看