PyTorch Tensors: Creation & Manipulation Guide

To create and manipulate tensors in PyTorch, you first need to import the torch library. Here are some commonly used methods for creating and manipulating tensors.

  1. Create a tensor:
import torch

# 创建一个空的张量
empty_tensor = torch.Tensor()

# 创建一个包含随机数据的张量
random_tensor = torch.rand(2, 3)

# 创建一个全零的张量
zero_tensor = torch.zeros(2, 3)

# 创建一个全一的张量
ones_tensor = torch.ones(2, 3)

# 从Python列表创建张量
list_tensor = torch.tensor([1, 2, 3])

# 从Numpy数组创建张量
import numpy as np
numpy_array = np.array([1, 2, 3])
numpy_tensor = torch.from_numpy(numpy_array)
  1. Tensor operations
# 张量的加法
tensor1 = torch.tensor([1, 2, 3])
tensor2 = torch.tensor([4, 5, 6])
result = tensor1 + tensor2

# 张量的乘法
result = tensor1 * tensor2

# 张量的索引和切片
tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(tensor[0, 1])  # 输出 2
print(tensor[:, 1])  # 输出 [2, 5]

# 张量的形状变换
tensor = torch.tensor([[1, 2], [3, 4]])
reshaped_tensor = tensor.view(1, 4)

# 张量的转置
tensor = torch.tensor([[1, 2], [3, 4]])
transposed_tensor = tensor.t()

# 张量的求和和平均值
tensor = torch.tensor([[1, 2], [3, 4]])
sum_tensor = torch.sum(tensor)
mean_tensor = torch.mean(tensor)

These are some common methods for creating and manipulating tensors, PyTorch also offers many other functions for handling tensors. Detailed documentation can be found on the official PyTorch website.

bannerAds