pytorch的tensor转换成numpy,不同方式

pytorch的tensor转换成numpy,不同方式

第一种方式,tensor.data创建一个新的tensor

import torch
import numpy

tensor = torch.ones(3,4)
n = tensor.data
n = n+1
print(tensor)
print(n)

输出

tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
tensor([[2., 2., 2., 2.],
        [2., 2., 2., 2.],
        [2., 2., 2., 2.]])

方式二,用+=相当于是in-place操作(原地操作),会改变原来tensor的值

import torch
import numpy

tensor = torch.ones(3,4)
n = tensor.data
n += 1
print(tensor)
print(n)

输出

tensor([[2., 2., 2., 2.],
        [2., 2., 2., 2.],
        [2., 2., 2., 2.]])
tensor([[2., 2., 2., 2.],
        [2., 2., 2., 2.],
        [2., 2., 2., 2.]])

方式三,把tensor转换成numpy格式,tensor和numpy是共享内存的
有三种方式
tensor.numpy(),
tensor.data.numpy(),
tensor.detach().numpy()

import torch
import numpy

tensor = torch.ones(3,4)
n = tensor.detach().numpy()
n = n+1
print(tensor)
print(n)

输出

tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
[[2. 2. 2. 2.]
 [2. 2. 2. 2.]
 [2. 2. 2. 2.]]

方式四,用numpy和+=,改变了原来的tensor值

import torch
import numpy

tensor = torch.ones(3,4)
n = tensor.detach().numpy()
n += 1
print(tensor)
print(n)

输出

tensor([[2., 2., 2., 2.],
        [2., 2., 2., 2.],
        [2., 2., 2., 2.]])
[[2. 2. 2. 2.]
 [2. 2. 2. 2.]
 [2. 2. 2. 2.]]

方式五,numpy不能从gpu上的tensor创建,要用tensor.cpu().numpy()
这样之后numpy和tensor之间就不是共享内存了,原地操作(in-place)改变numpy不会改变tensor

import torch
import numpy

tensor = torch.ones(3,4)

t=tensor.cuda()
t += 1
n2 = t.cpu().numpy()
n2 += 1
print(tensor)
print(t)
print(n2)

输出

tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
tensor([[2., 2., 2., 2.],
        [2., 2., 2., 2.],
        [2., 2., 2., 2.]], device='cuda:0')
[[3. 3. 3. 3.]
 [3. 3. 3. 3.]
 [3. 3. 3. 3.]]

你可能感兴趣的:(pytorch的tensor,pytorch)