002-tensors basic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# PyTorch 张量基础

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

## 基本操作

### 创建张量
```python
import torch
import numpy as np

# 从随机数据和全1数据创建张量
shape = (2, 3)
rand_tensor = torch.rand(shape) # 随机张量
ones_tensor = torch.ones(shape) # 全1张量

张量属性

1
2
3
print(f"Shape of tensor: {rand_tensor.shape}")  # 形状
print(f"Datatype of tensor: {rand_tensor.dtype}") # 数据类型
print(f"Device tensor is stored on: {rand_tensor.device}") # 存储设备

索引和切片

1
2
tensor = torch.ones(4, 4)
tensor[:, 1] = 0 # 将第1列所有元素设为0

张量连接

1
t1 = torch.cat([tensor, tensor, tensor], dim=1)  # 沿维度1连接

张量运算

元素级乘法

1
2
3
# 两种等价写法
print(tensor.mul(tensor)) # 方法形式
print(tensor * tensor) # 运算符形式

矩阵乘法

1
2
3
# 两种等价写法
print(tensor.matmul(tensor.T)) # 方法形式
print(tensor @ tensor.T) # 运算符形式

原地操作(In-place)

1
tensor.add_(5)  # 带_后缀的操作会修改原张量

注意:原地操作可以节省内存,但在计算导数时可能会出现问题,因此不鼓励使用。

与NumPy互转

张量转NumPy数组

1
2
t = torch.ones(5)
n = t.numpy() # 转为NumPy数组

NumPy数组转张量

1
2
n = np.ones(5)
t = torch.from_numpy(n) # 转为PyTorch张量