Tensor(张量)数据转换
在深度学习和科学计算中,Tensor(张量) 是多维数组的泛化形式,是存储和处理数据的基本数据结构。Tensor 数据转换是指在不同框架(如 PyTorch、TensorFlow、NumPy 等)之间或同一框架内部对 Tensor 进行**类型、形状、设备(CPU/GPU)**等方面的转换。
以下是常见的 Tensor 数据转换操作及其在不同框架中的实现方式。
1、 Tensor 的类型转换
Tensor 的数据类型(如 float32、int64 等)可以根据需要进行转换。
PyTorch
PyTorch Tensor 支持多种数据类型(如 float32、int64 等),可以通过 .to() 或直接调用类型转换方法进行转换。
import torch
# 创建一个整数类型的 Tensor
tensor = torch.tensor([1, 2, 3], dtype=torch.int32)
# 转换为浮点类型
tensor_float = tensor.float() # 或者使用 tensor.to(torch.float32)
print(tensor_float)
# 转换为双精度浮点类型
tensor_double = tensor.double() # 或者使用 tensor.to(torch.float64)
print(tensor_double)
# 转换为布尔类型
tensor_bool = tensor.bool() # 非零值为 True,零值为 False
print(tensor_bool)
TensorFlow
import tensorflow as tf
# 创建一个整数类型的 Tensor
tensor = tf.constant([1, 2, 3], dtype=tf.int32)
# 转换为浮点类型
tensor_float = tf.cast(tensor, tf.float32)
print(tensor_float)
NumPy
import numpy as np
# 创建一个整数类型的数组
array = np.array([1, 2, 3], dtype=np.int32)
# 转换为浮点类型
array_float = array.astype(np.float32)
print(array_float)
2、Tensor 的形状转换
Tensor 的形状可以通过重塑(reshape)、转置(transpose)等操作进行转换。
PyTorch
PyTorch 提供了多种方法来改变 Tensor 的形状,包括 reshape()、view()、transpose() 等。
import torch
# 创建一个 2x3 的 Tensor
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 使用 reshape 改变形状
tensor_reshaped = tensor.reshape(3, 2) # 变为 3x2
print(tensor_reshaped)
# 使用 view 改变形状(view 要求内存连续)
tensor_viewed = tensor.view(3, 2) # 变为 3x2
print(tensor_viewed)
# 转置操作
tensor_transposed = tensor.t() # 变为 3x2
print(tensor_transposed)
# 扩展维度
tensor_unsqueezed = tensor.unsqueeze(0) # 在第 0 维增加一个维度
print(tensor_unsqueezed.shape) # 输出: torch.Size([1, 2, 3])
# 压缩维度
tensor_squeezed = tensor_unsqueezed.squeeze(0) # 移除第 0 维
print(tensor_squeezed.shape) # 输出: torch.Size([2, 3])
TensorFlow
import tensorflow as tf
# 创建一个 2x3 的 Tensor
tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
# 重塑为 3x2
tensor_reshaped = tf.reshape(tensor, [3, 2])
print(tensor_reshaped)
# 转置
tensor_transposed = tf.transpose(tensor)
print(tensor_transposed)
NumPy
import numpy as np
# 创建一个 2x3 的数组
array = np.array([[1, 2, 3], [4, 5, 6]])
# 重塑为 3x2
array_reshaped = array.reshape(3, 2)
print(array_reshaped)
# 转置
array_transposed = array.T
print(array_transposed)
3、Tensor 的设备转换
在深度学习中,Tensor 可以在 CPU 和 GPU 之间进行转换以加速计算。
PyTorch
import torch
# 创建一个 Tensor(默认在 CPU 上)
tensor = torch.tensor([1, 2, 3])
# 检查 GPU 是否可用
if torch.cuda.is_available():
# 将 Tensor 移动到 GPU
tensor_gpu = tensor.to('cuda') # 或者使用 tensor.cuda()
print(tensor_gpu)
# 将 Tensor 移回 CPU
tensor_cpu = tensor_gpu.to('cpu') # 或者使用 tensor_gpu.cpu()
print(tensor_cpu)
else:
print("GPU 不可用")
TensorFlow
import tensorflow as tf
# 创建一个 Tensor(默认在 CPU 上)
tensor = tf.constant([1, 2, 3])
# 将 Tensor 移动到 GPU
if tf.config.list_physical_devices('GPU'):
with tf.device('GPU:0'):
tensor_gpu = tf.identity(tensor)
print(tensor_gpu)
# 将 Tensor 移回 CPU
with tf.device('CPU:0'):
tensor_cpu = tf.identity(tensor_gpu)
print(tensor_cpu)
4、Tensor 与 NumPy 数组的转换
PyTorch
import torch
import numpy as np
# 从 NumPy 数组创建 Tensor
array = np.array([1, 2, 3])
tensor = torch.from_numpy(array)
print(tensor)
# 从 Tensor 转换为 NumPy 数组
array_back = tensor.numpy()
print(array_back)
TensorFlow
import tensorflow as tf
import numpy as np
# 从 NumPy 数组创建 Tensor
array = np.array([1, 2, 3])
tensor = tf.convert_to_tensor(array)
print(tensor)
# 从 Tensor 转换为 NumPy 数组
array_back = tensor.numpy()
print(array_back)
5、Tensor与图像
5.1、图片转Tensor
import torch
from PIL import Image
from torchvision import transforms
def test001():
imgpath = r"./105429.jpg"
# 1. 读取图片
img = Image.open(imgpath)
# 使用transforms.ToTensor()将图片转换为张量
transform = transforms.ToTensor()
img_tensor = transform(img)
print(img_tensor)
if __name__ == "__main__":
test001()
5.2、Tensor转图片
import torch
from PIL import Image
from torchvision import transforms
def test002():
# 1. 随机一个数据表示图片
img_tensor = torch.randn(3, 224, 224)
# 2. 创建一个transforms
transform = transforms.ToPILImage()
# 3. 转换为图片
img = transform(img_tensor)
img.show()
# 4. 保存图片
img.save("./test.jpg")
if __name__ == "__main__":
test002()