温馨提示×

pytorch张量如何创建

小樊
109
2024-12-25 20:46:28
栏目: 深度学习

在PyTorch中,有多种方法可以创建张量。以下是一些常用的方法:

  1. 使用torch.Tensor()构造函数创建张量:
import torch # 创建一个2x3的浮点型张量,初始值为0 tensor1 = torch.Tensor(2, 3) print(tensor1) # 创建一个3x4的整数型张量,初始值为0 tensor2 = torch.Tensor(3, 4, dtype=torch.int) print(tensor2) 
  1. 使用torch.zeros()torch.ones()torch.rand()函数创建全零、全一和随机张量:
import torch # 创建一个2x3的全零张量 tensor_zeros = torch.zeros(2, 3) print(tensor_zeros) # 创建一个2x3的全一张量 tensor_ones = torch.ones(2, 3) print(tensor_ones) # 创建一个2x3的随机张量,数值范围在0到1之间 tensor_rand = torch.rand(2, 3) print(tensor_rand) 
  1. 使用torch.arange()torch.linspace()函数创建等差和等比数列张量:
import torch # 创建一个从0开始,步长为1的2x3等差数列张量 tensor_arange = torch.arange(2).repeat(3, 1) print(tensor_arange) # 创建一个从0开始,到1之间,共5个元素的2x3等比数列张量 tensor_linspace = torch.linspace(0, 1, 5).view(2, 3) print(tensor_linspace) 
  1. 使用torch.eye()函数创建单位矩阵张量:
import torch # 创建一个3x3的单位矩阵张量 tensor_eye = torch.eye(3) print(tensor_eye) 
  1. 使用torch.tensor()函数从现有数据创建张量:
import torch # 从列表创建一个2x3的张量 data = [[1, 2, 3], [4, 5, 6]] tensor_from_list = torch.tensor(data) print(tensor_from_list) # 从NumPy数组创建一个2x3的张量 import numpy as np numpy_array = np.array([[1, 2, 3], [4, 5, 6]]) tensor_from_numpy = torch.tensor(numpy_array) print(tensor_from_numpy) 

以上就是PyTorch中创建张量的一些常用方法。

0