6.4 张量转换

6.4.1 张量元素类型转换

1)Tensor.type(dtype)修改张量的类型

import torch

tensor1 = torch.tensor([1, 2, 3])
print(tensor1, tensor1.dtype)

# 使用type方法修改张量的类型
tensor1 = tensor1.type(torch.float32)
print(tensor1, tensor1.dtype)

2)Tensor.double()等修改张量的类型

import torch

tensor1 = torch.tensor([1, 2, 3])
print(tensor1, tensor1.dtype)

# 使用double方法修改张量的类型
tensor1 = tensor1.double()
print(tensor1)
# 使用long方法修改张量的类型
tensor1 = tensor1.long()
print(tensor1, tensor1.dtype)

6.4.2 Tensor与ndarray转换

1)Tensor.numpy()将Tensor转换为ndarray,共享内存。使用copy()避免共享内存

import torch

# 使用numpy()方法将Tensor转换为ndarray,共享内存
tensor1 = torch.rand(3, 2)
numpy_array = tensor1.numpy()
print(tensor1)
print(numpy_array)
print(type(tensor1), type(numpy_array))
print()
tensor1[:, 0] = 4
print(tensor1)
print(numpy_array)
print()

# 使用copy()方法避免共享内存
numpy_array = tensor1.numpy().copy()
tensor1[:, 0] = -1
print(tensor1)
print(numpy_array)

2)torch.from_numpy(ndarray)将ndarray转换为Tensor,共享内存。使用copy()避免共享内存

import torch
import numpy as np

# 使用from_numpy()方法将ndarray转换为Tensor,共享内存
numpy_array = np.random.randn(3)
tensor1 = torch.from_numpy(numpy_array)
print(numpy_array)
print(tensor1)
print()
numpy_array[0] = 100
print(numpy_array)
print(tensor1)
print()

# 使用copy()方法避免共享内存
tensor1 = torch.from_numpy(numpy_array.copy())
numpy_array[0] = -1
print(numpy_array)
print(tensor1)

3)torch.tensor(ndarray)将ndarray转换为Tensor,不共享内存

import torch
import numpy as np

# 使用torch.tensor()将ndarray转换为Tensor
numpy_array = np.random.randn(3)
tensor1 = torch.tensor(numpy_array)
print(numpy_array)
print(tensor1)
print()
numpy_array[0] = 100
print(numpy_array)
print(tensor1)

6.3.4 Tensor与标量转换

若张量中只有1个元素,Tensor.item()可提取张量中元素为标量。

import torch

tensor1 = torch.tensor(1)
print(tensor1)
print(tensor1.item())

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发
头像-大赛人网
欢迎您留下宝贵的见解!
提交
头像-大赛人网

昵称

取消
昵称

    请登录后查看评论内容