1. Tensor
- Tensor 相当于 NumPy 的 ndarrays;
- Tensor 可以使用 GPU 进行计算;
1. 不初始化,构建5x3矩阵
from __future__ import print_function
import torch
def not_init_array(row, column):
x = torch.empty([row, column], dtype=float)
return x
if __name__ == "__main__":
print(not_init_array([5, 3]))
结果:
tensor([[4.9407e-324, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, 0.0000e+00, 1.1032e-311],
[1.1032e-311, 9.8813e-324, 9.8813e-324],
[1.4822e-323, 0.0000e+00, 0.0000e+00],
[ 0.0000e+00, 1.4822e-323, 4.9407e-324]], dtype=torch.float64)
[注]:在不指定 dtype 类型时,默认值为float32;
2. 构造一个随机初始化矩阵
import torch
def rand_array():
x = torch.rand([5, 3], dtype=torch.float, requires_grad=False)
return x
if __name__ == "__main__":
print(rand_array())
结果:
tensor([[0.4543, 0.7095, 0.5544],
[0.3758, 0.7982, 0.6718],
[0.2281, 0.5241, 0.0279],
[0.0862, 0.5257, 0.9148],
[0.0312, 0.8112, 0.6917]], dtype=torch.float64)
[注]:requires_grad为梯度计算,一般开关默认为False,需要进行梯度计算时,将其设置为True;
3. 构建全0矩阵,数据类型为long
import torch
def zeros_array(row, colum):
x = torch.zeros([row, colum], dtype=torch.long)
return x
if __name__ == "__main__":
print(zeros_array(4, 4))
print(zeros_array().dtype)
结果:
tensor([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])
torch.int64
4. 构建一个张量,直接使用数据
import torch
def tensor():
x = torch.tensor([8, 255, 255])
return x
if __name__ == "__main__":
print(tensor())
结果:
tensor([ 8, 255, 255])
5. 创建一个tensor基于已经存在的tensor
import torch
def new_basic_tensor(row, column):
x = torch.ones([row, column], dtype=torch.double) # x是一个tensor类型数据
y = torch.randn_like(x, dtype=torch.float)
return x, y
if __name__ == "__main__":
res1, res2 = new_basic_tensor(3, 3)
print(res1)
print(res2)
print(res2.size()) # 获取维度信息
结果:
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
tensor([[ 0.0287, 1.3357, 1.1125],
[-2.9300, 0.7372, -0.4044],
[ 0.1549, -1.3047, -1.4294]])
torch.Size([3, 3])
[注]:torch.Size 是一个元组,支持左右元组操作;
2. Tensor加法运算
1. 直接相加 tensor1 + tensor2
import torch
def t1_add_t2(row, column):
x = torch.ones([row, column], dtype=torch.float)
print(f"tensor x = {x}")
y = torch.rand([row, column], dtype=torch.float)
print(f"tensor y = {y}")
return x + y
if __name__ == "__main__":
print(f"tensor x+y = {t1_add_t2(3, 3)}")
结果:
tensor x = tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]), dtype = torch.float32
tensor y = tensor([[0.9242, 0.8121, 0.2289],
[0.0412, 0.1470, 0.9535],
[0.7616, 0.2433, 0.5139]]), dtype = torch.float32
tensor x+y = tensor([[1.9242, 1.8121, 1.2289],
[1.0412, 1.1470, 1.9535],
[1.7616, 1.2433, 1.5139]])
2. 使用torch.add()函数
import torch
def add():
x = torch.ones([3, 3])
y = torch.ones([3, 3])
return torch.add(x, y)
if __name__ == "__main__":
print(add())
结果:
tensor([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]])
3. 在add()函数上提供一个输出tensor作为参数
import torch
def add():
x = torch.rand(3, 3)
print(f"tensor x = {x}")
y = torch.ones(3, 3)
print(f"tensor y = {y}")
result = torch.empty(3, 3)
return torch.add(x, y, out=result)
if __name__ == "__main__":
print(add())
结果:
tensor x = tensor([[0.8031, 0.1675, 0.4783],
[0.4975, 0.5951, 0.7130],
[0.0187, 0.2694, 0.1196]])
tensor y = tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
tensor([[1.8031, 1.1675, 1.4783],
[1.4975, 1.5951, 1.7130],
[1.0187, 1.2694, 1.1196]])
4. 加法:in-place方法
import torch
def in_place():
x = torch.ones(5, 3)
y = torch.ones_like(x)
return y.add_(x) # 这里使用的是 in_place加法,y.add_(x) 等价 torch.add(x, y)
if __name__ == "__main__":
print(in_place())
结果:
tensor([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]])
**[注]:任何使 张量(Tensor) 发生变化的操作都有一个前缀。eg:x.copy(y)、x.t_(),将会改变前缀 x. **
3. Tensor的其他操作方式
1. 使用索引操作
- Tensor 可以使用标准的 NumPy 类似的 索引 操作;
import torch
def index_array():
x = torch.rand(5, 3)
print(f"tensor x = {x}")
return x
if __name__ == "__main__":
# 打印该矩阵列下标=1的所有数
print(index_array()[:, 1])
结果:
tensor x = tensor([[0.2170, 0.0599, 0.4345],
[0.4617, 0.3926, 0.6175],
[0.6764, 0.9664, 0.7748],
[0.0180, 0.3388, 0.9173],
[0.4653, 0.5886, 0.1087]])
tensor([0.0599, 0.3926, 0.9664, 0.3388, 0.5886])
2. 改变Tensor大小形状
- 使用 torch.view 方法实现改变 Tensor 大小形状;
import torch
def resize_array():
x = torch.randn(4, 4)
print(x)
y = torch.view(16) # 将(4, 4)矩阵改为(1, 16)矩阵,也就是一维矩阵
print(y)
z = torch.view(-1, 8) # 将(4, 4)矩阵通过-1自动计算确定行数,列数为8
print(z)
return x.size(), y.size(), z.size()
if __name__ == "__main__":
print(resize_array())
结果:
tensor([[ 0.2900, 0.8518, -3.5446, -0.3621],
[-0.4792, -1.0429, 1.0261, -0.0310],
[ 0.4935, 0.7629, -0.5164, 0.1652],
[-0.8043, 0.2716, -0.1145, 0.2164]])
tensor([ 0.2900, 0.8518, -3.5446, -0.3621, -0.4792, -1.0429, 1.0261, -0.0310,
0.4935, 0.7629, -0.5164, 0.1652, -0.8043, 0.2716, -0.1145, 0.2164])
tensor([[ 0.2900, 0.8518, -3.5446, -0.3621, -0.4792, -1.0429, 1.0261, -0.0310],
[ 0.4935, 0.7629, -0.5164, 0.1652, -0.8043, 0.2716, -0.1145, 0.2164]])
(torch.Size([4, 4]), torch.Size([16]), torch.Size([2, 8]))
3. 获取一个元素tensor的value值
- 若有一个元素 tensor,使用 .item() 来获取 value;
import torch
def get_value():
x = torch.rand(1)
print(x)
return x
if __name__ == "__main__":
print(get_value.item())
结果:
tensor([0.8983])
0.8982625007629395