1. tensor转numpy
# 1. 张量转为numpy数组
data_tensor1 = torch.tensor([2,3,4]) # tensor([2, 3, 4])
data_numpy1 = data_tensor1.numpy() # [2 3 4]
# data_tensor1,data_numpy1 共享内存
data_tensor1[1] = 9 # data_tensor1—tensor([2, 9, 4]) data_numpy1—[2 9 4]
data_numpy1[0] = 6 # data_tensor1—tensor([6, 9, 4]) data_numpy1—[6 9 4]
# 2. 使用copy函数使之不共享内存
data_tensor2 = torch.tensor([7,8,9]) # tensor([7, 8, 9])
data_numpy2 = data_tensor2.numpy().copy() # [7 8 9]
data_tensor2[1] = 9 # data_tensor2—tensor([7, 9, 9]) data_numpy2—[7 8 9]
data_numpy2[0] = 6 # data_tensor2—tensor([7, 9, 9]) data_numpy2—[6 8 9]
2. numpy转tensor
使用torch.from_numpy()生成张量,tensor与numpy共享内存——浅拷贝
# 3. numpy转tensor
data_numpy3 = numpy.array([4,5,6]) # [4 5 6]
data_tensor3 = torch.from_numpy(data_numpy3) # tensor([4, 5, 6], dtype=torch.int32)
# # data_tensor3,data_numpy3 共享内存
data_numpy3[0] = 10 # data_tensor3—tensor([10, 5, 6], dtype=torch.int32) data_numpy3—[10 5 6]
data_tensor3[1] = 2 # data_tensor3—tensor([10, 2, 6], dtype=torch.int32) data_numpy3—[10 2 6]
拷贝numpy数组再转化成tensor,使之不共享内存
data_numpy4 = numpy.array([1,4,7]) # [1 4 7]
data_tensor4 = torch.from_numpy(data_numpy4.copy()) # tensor([1, 4, 7], dtype=torch.int32)
data_numpy4[0] = 2 # data_tensor4—tensor([1, 4, 7], dtype=torch.int32) data_numpy4—[2 4 7]
data_tensor4[1] = 11 # data_tensor4—tensor([1, 11, 7], dtype=torch.int32) data_numpy4—[2 4 7]
使用torch.tensor()生成张量,tensor与numpy不共享内存——深拷贝
# 5. numpy转tensor方法2
data_numpy5 = numpy.array([3,6,9]) # tensor([3, 6, 9], dtype=torch.int32)
data_tensor5 = torch.tensor(data_numpy5) # [3 6 9]
data_numpy5[0] = 1 # data_tensor5—tensor([3, 6, 9], dtype=torch.int32) data_numpy5—[1 6 9]
data_tensor5[1] = 2 # data_tensor5—tensor([3, 2, 9], dtype=torch.int32) data_numpy5—[1 6 9]
3. 单元素张量转换为数字
# 6. 张量转为数字
t1 = torch.tensor(2) # tensor(2) shape: torch.Size([])—0维
t2 = torch.tensor([3]) # tensor([3]) shape: torch.Size([1])—1维
t3 = torch.tensor([[4]]) # tensor([[4]]) shape: torch.Size([1, 1])—2维
n1 = t1.item() # 2
n2 = t2.item() # 3
n3 = t3.item() # 4
# .item()适合张量中只包含一个元素