torch1.13.0+cpu中tensor的常用属性与方法

一、构建tensor

1
2
3
4
#一、构建tensor
###PyTorch常用数据类型
#官方教程: https://pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html
#官方API文档: https://pytorch.org/docs/stable/index.html
1
2
3
4
5
6
7
8
###张量(Tensor):PyTorch网络运算中的基本数据结构(类似ndarray )
###创建张量
import torch
a = torch.tensor(0.1) #此张量只有一个标量元素0.1
b = torch.tensor(0.3, dtype=torch.float64)
#执行运算
result = a + b
print(result)
tensor(0.4000, dtype=torch.float64)
1
2
3
4
5
6
7
###创建特定的张量
import torch
# 全1张量
ones = torch.ones((3, 2))
# 等差序列张量
range_tensor = torch.arange(1, 11, 1)
print('ones:', ones, '\n', 'range_tensor:', range_tensor)
ones: tensor([[1., 1.],
        [1., 1.],
        [1., 1.]]) 
 range_tensor: tensor([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
1
2
3
4
5
6
7
8
9
10
11
###tensor与ndarray相互转化
import torch
output = torch.zeros((2, 2), dtype=torch.float32)
print("1--->", output)
print("2--->output: {}".format(type(output)))

n_output = output.numpy()
print("3--->n_output: {}".format(type(n_output)))

t_output = torch.from_numpy(n_output) # 将ndarray转为tensor
print("4--->t_output: {}".format(type(t_output)))
1---> tensor([[0., 0.],
        [0., 0.]])
2--->output: <class 'torch.Tensor'>
3--->n_output: <class 'numpy.ndarray'>
4--->t_output: <class 'torch.Tensor'>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#从变量继承属性创建张量、从numpy创建张量
###官方教程: https://pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html
import torch
import numpy as np
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data) #直接从数据创建一个tensor,数据类型可以被自动推断出来
print("1--->x_data:", x_data)
print("x_data type:{}".format(type(x_data)))
np_array = np.array(data) #直接从数据创建一个numpy变量
print("2--->np_array", np_array)
x_np = torch.from_numpy(np_array) #从numpy变量创建一个tensor
print("3--->x_np", x_np)
print("x_np type:{}".format(type(x_np)))

x_ones = torch.ones_like(x_data) # 根据x_data的创建一个新tensor,新tensor的属性(此处因为没有指定数据类型,所以新tensor数据类型跟x_data也一样。其他属性也是类似规律)跟x_data一样,但数值可以指定为全是1
print(f"Ones Tensor: \n {x_ones} \n")
x_rand = torch.rand_like(x_data, dtype=torch.float) # 根据x_data的创建一个新tensor,形状与原tensor一样,但指定了新的数据类型为torch.float、且它的元素值都是一些随机生成的数
print(f"Random Tensor: \n {x_rand} \n")
1--->x_data: tensor([[1, 2],
        [3, 4]])
x_data type:<class 'torch.Tensor'>
2--->np_array [[1 2]
 [3 4]]
3--->x_np tensor([[1, 2],
        [3, 4]], dtype=torch.int32)
x_np type:<class 'torch.Tensor'>
Ones Tensor: 
 tensor([[1, 1],
        [1, 1]]) 

Random Tensor: 
 tensor([[0.0282, 0.8095],
        [0.2707, 0.1938]]) 

1
2
3
4
5
6
7
8
9
10
#创建随机数张量
###官方教程: https://pytorch.org/tutorials/beginner/basics/tensorqs_tutorial.html
import torch
import numpy as np
tensor = torch.rand(4, 4)
print(f"First row: {tensor[1]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)
First row: tensor([0.1094, 0.4258, 0.9837, 0.3118])
First column: tensor([0.3335, 0.1094, 0.4532, 0.2374])
Last column: tensor([0.7949, 0.3118, 0.5406, 0.5577])
tensor([[0.3335, 0.0000, 0.1649, 0.7949],
        [0.1094, 0.0000, 0.9837, 0.3118],
        [0.4532, 0.0000, 0.6070, 0.5406],
        [0.2374, 0.0000, 0.7951, 0.5577]])
1

1

1
#二、tensor属性
1
2
3
4
5
6
7
8
9
10
11
#tensor.data用法
import torch
t = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
print(t)
print(t.data) #在 PyTorch 中,torch.tensor.data 是一个 属性,用于访问张量的底层数据(即存储张量值的实际内存)。它返回一个与原始张量共享相同存储的新张量,但 不参与自动求导(即不跟踪计算历史)。
print(t.data.numpy()) #numpy() 方法将 PyTorch 张量转换为 NumPy 数组。转换后的 NumPy 数组与原始张量共享存储,因此修改 NumPy 数组会影响原始张量。
print(t.data.numpy().argmax(axis=1)) #argmax() 是 NumPy 数组的方法,用于返回沿指定轴的最大值的索引。axis=1 表示沿着第 1 轴(即行方向)查找最大值的索引。

x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
print(x)
print(x.data)
tensor([[1., 2.],
        [3., 4.]])
tensor([[1., 2.],
        [3., 4.]])
[[1. 2.]
 [3. 4.]]
[1 1]
tensor([1., 2., 3.], requires_grad=True)
tensor([1., 2., 3.])
1

1
#三、tensor方法 
1
2
3
4
5
6
#在 PyTorch 中,torch.tensor.mean() 是一个用于计算张量中所有元素平均值的方法。它可以沿着指定的维度计算平均值,也可以计算整个张量的平均值。
import torch
import numpy as np
tensor = torch.tensor([[2, 3], [4, 5], [6, 7]], dtype=torch.float64)
print(tensor)
tensor.mean()
tensor([[2., 3.],
        [4., 5.],
        [6., 7.]], dtype=torch.float64)





tensor(4.5000, dtype=torch.float64)
1

1

1


torch1.13.0+cpu中tensor的常用属性与方法
https://jiangsanyin.github.io/2025/02/28/torch1-13-0-cpu中tensor的常用属性与方法/
作者
sanyinjiang
发布于
2025年2月28日
许可协议