【PyTorch学习3】张量相关类型转换

本文详细介绍了如何在PyTorch中将张量转换为numpy数组,以及反之,特别关注了共享内存和深拷贝的区别。还涵盖了如何处理单元素张量并将其转换为数字。
摘要由CSDN通过智能技术生成

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()适合张量中只包含一个元素
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值