[pytorch学习笔记] 2. tensor 张量

本文介绍了PyTorch中的张量操作,包括张量的初始化、属性、运算、连接以及与NumPy数组的相互转换。详细讲解了张量的创建方法,如直接从数据、numpy数组、其他张量以及使用随机数或常数初始化。此外,还阐述了张量的算术运算、单元素张量操作、in-place操作以及张量与NumPy数组之间的无缝桥接。内容适合初学者掌握PyTorch的基础知识。
摘要由CSDN通过智能技术生成

目录

介绍

张量初始化

1.张量可以直接从数据中创建。 数据类型是自动推断的。

2.张量通过numpy 中的数组进行初始化。

3.通过别的张量进行初始化

4.使用随机数或常数初始化:

Tensor 属性

张量运算

连接张量

算术运算

单元素张量

in-place 操作

与 NumPy 桥接

Tensor to NumPy array

NumPy array to Tensor

参考


介绍

Tensor 是一种特殊的数据结构,与数组和矩阵非常相似。 在 PyTorch 中,我们使用张量来编码模型的输入和输出,以及模型的参数。

张量类似于 NumPy 的 ndarray,除了张量可以在 GPU 或其他硬件加速器上运行。 事实上,张量和 NumPy 数组通常可以共享相同的底层内存,从而无需复制数据。 张量还针对自动微分进行了优化。

import torch
import numpy as np

张量初始化

张量有很多方式初始化。

1.张量可以直接从数据中创建。 数据类型是自动推断的。

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

2.张量通过numpy 中的数组进行初始化。

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

3.通过别的张量进行初始化

新张量保留参数张量的属性(形状、数据类型),除非显式覆盖。

x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")

output:
Ones Tensor:
 tensor([[1, 1],
        [1, 1]])

Random Tensor:
 tensor([[0.2047, 0.2984],
        [0.2160, 0.2763]])

4.使用随机数或常数初始化:

shape 是张量维度的元组。 在下面的函数中,它决定了输出张量的维度。

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")


out:
Random Tensor:
 tensor([[0.3999, 0.7222, 0.3077],
        [0.1161, 0.3216, 0.7987]])

Ones Tensor:
 tensor([[1., 1., 1.],
        [1., 1., 1.]])

Zeros Tensor:
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

Tensor 属性

张量属性描述了它们的形状、数据类型和存储它们的设备。

tensor = torch.rand(3,4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")

out:
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

张量运算

张量运算有 100 种,包括算术、线性代数、矩阵操作(转置、索引、切片)、采样等。

这些操作中的每一个都可以在 GPU 上运行(通常以比 CPU 更高的速度)。默认情况下,张量是在 CPU 上创建的。 我们需要使用 .to 方法(在检查 GPU 可用性之后)将张量显式移动到 GPU。(请记住,跨设备复制大张量在时间和内存方面可能会很昂贵!)

# We move our tensor to the GPU if available
if torch.cuda.is_available():
    tensor = tensor.to("cuda")

标准的类似 numpy 的索引和切片:

tensor = torch.ones(4, 4)
print(f"First row: {tensor[0]}")
print(f"First column: {tensor[:, 0]}")
print(f"Last column: {tensor[..., -1]}")
tensor[:,1] = 0
print(tensor)

out:
First row: tensor([1., 1., 1., 1.])
First column: tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

连接张量

使用 torch.cat 沿给定维度连接一系列张量。 

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)

out:
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

算术运算

# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)


# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

单元素张量

如果您有一个单元素张量,通过将张量的所有值聚合为一个值,可以使用 item() 将其转换为 Python 数值:

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))

out:
12.0 <class 'float'>

in-place 操作

将结果存储到操作数中的操作称为in-place 操作(就地操作)。 它们用 _ 后缀表示。 例如:x.copy_(y),x.t_(),会改变x。

print(f"{tensor} \n")
tensor.add_(5)
print(tensor)

out:
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

注意:就地操作可以节省一些内存,但在计算导数时可能会出现问题,因为会立即丢失历史记录。 因此,不鼓励使用它们。

与 NumPy 桥接

CPU 和 NumPy 数组上的张量可以共享它们的底层内存位置,改变一个会改变另一个。

Tensor to NumPy array

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")

out:
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

A change in the tensor reflects in the NumPy array.

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")

out:
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

NumPy array to Tensor

A change in the tensor reflects in the NumPy array.

n = np.ones(5)
t = torch.from_numpy(n)

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")

out:
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]

参考

官方文档:Tensors — PyTorch Tutorials 1.11.0+cu102 documentation

本文是对官方文档的翻译,第一遍基础知识建议大家看翻译,第二遍建议边用边查官方文档,大家一起加油啊~

这位老兄写的也很好,推荐大家看一下:[PyTorch 学习笔记] 1.2 Tensor(张量)介绍 - 知乎 (zhihu.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值