PyTorch101 --PyTorch基本框架
一、Tensor 张量
定义:The number of dimensions is the rank of the tensor;例:tensor([1,2,3])的秩为1
the shape of a tensor is a tuple of integers giving the size of the array along each dimension 例:tensor([1,2,3])的shape为[3]
1.构建&访问tensor
1 | x=torch.tensor([[1,2,3],[4,5,6]])#构建tensor张量 |
2.帮助构建tensor的函数
常用的函数有:
- x=torch.zeros(*size) #全为0的tensor - x=torch.ones(*size)#全为1的tensor - x=torch.rand(*size)#为0-1随机数 - x=torch.full(*size*, *fill_value*, ***, *out* *=* *None*, *dtype* *=* None, *layout* *=* *torch.strided*, *device* *=* *None*, *requires_grad* *=* *False*)#→ Tensor - x=torch.from_numpy( ndarray ) #→ Tensor - x=torch.arange( *start=0* , *end* , *step=1* , * , out=None , *dtype=None* , layout *=torch.strided* , *device=None* , *require_grad=False* )#→Tensor <u>#左闭右开区间</u>(torch.range <u>#左闭右闭</u>)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
You can find a **full list of tensor creation operations** [in the documentation](https://www.google.com/url?q=https%3A%2F%2Fpytorch.org%2Fdocs%2Fstable%2Ftorch.html%23creation-ops).
#### 3.tensor的数据形式
tensor会根据数字自动设定形式,你也可以为其赋予特定格式如:int16、uint8、float32等等。
可以使用 .to( )来修改dtype,如:x0.to(torch.float32)
```python
x1=torch.zeros_like(x0) #构建一个size和dtype与x0一样的
x2=x0.new_zeros(4,5)#size自定,dtype和x0一样
x3=torch.ones(6,7).to(x0)#和上一行相同
常用的数据形式:
torch.float32: Standard floating-point type; used to store learnable parameters, network activations, etc. Nearly all arithmetic is done using this type.torch.int64: Typically used to store indicestorch.bool: Stores boolean values: 0 is false and 1 is truetorch.float16: Used for mixed-precision arithmetic, usually on NVIDIA GPUs with tensor cores . You won’t need to worry about this datatype in this course.
4.Tensor Indexing
tensor也能进行“切片”,多维度也行
- Title: PyTorch101 --PyTorch基本框架
- Author: Rongying Liu
- Created at : 2024-11-12 12:59:05
- Updated at : 2024-11-19 18:20:01
- Link: https://github.com/Roinnnn11/Roinnnn11.github.io/2024/11/12/CS231N/PyTorch101/
- License: This work is licensed under CC BY-NC-SA 4.0.
Comments