深度学习-Pytorch模型运算的基本数据类型
用pytorch构建模型,并训练模型,得到一个优化的模型,那么模型构造的数据类型怎样的?
数据分析
数据分析-Pandas如何转换产生新列
数据分析-Pandas如何统计数据概况
数据分析-Pandas如何轻松处理时间序列数据
数据分析-Pandas如何选择数据子集
数据分析-Pandas如何重塑数据表-CSDN博客
经典算法
经典算法-遗传算法的python实现
经典算法-模拟退火算法的python实现
经典算法-粒子群算法的python实现-CSDN博客
pytorch中常常遇到的,最基本的数据类型就是tensors。
Tensors
Tensors是一种特殊的数据结构,与数组和矩阵非常相似。 在 PyTorch 中,我们使用张量对模型的输入和输出以及模型的参数进行处理。
Tensors也类似于 NumPy 的 ndarrays,不同之处在于
- Tensors还可以加载到 GPU 或其他硬件加速器上运行。事实上,Tensors和 NumPy 数组通常可以共享相同的底层内存,无需复制数据。
- 另外,Tensors还针对自动微分进行了优化(将在稍后的 Autograd 部分看到更多相关内容)。
如果您熟悉 ndarrays,那么您将可以再熟悉下 Tensor API 。如果没有,请继续!
import torch
import numpy as np
初始化Tensors
Tensors可以通过多种方式初始化。请看以下示例:
从数据生成
Tensors可以直接从数据创建。数据类型是自动生成的。
data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)
从 NumPy 数组生成
Tensors可以从 NumPy 数组创建(反之亦然 - 参见 Bridge with NumPy)。
np_array = np.array(data)
x_np = torch.from_numpy(np_array)
从另一个Tensor
新tensor将保留参数tensor的属性(形状、数据类型),除非显式覆盖。
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")
Ones Tensor:tensor([[1, 1],[1, 1]])Random Tensor:tensor([[0.8823, 0.9150],[0.3829, 0.9593]])
用随机值或常量值:
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}")
Random Tensor:tensor([[0.3904, 0.6009, 0.2566],[0.7936, 0.9408, 0.1332]])Ones Tensor:tensor([[1., 1., 1.],[1., 1., 1.]])Zeros Tensor:tensor([[0., 0., 0.],[0., 0., 0.]])
Tensors的属性
Tensors属性描述它们的形状、数据类型和存储它们的设备。
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}")
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu
Tensors的操作
超过 100 种tensors运算,包括算术、线性代数、矩阵操作(转置、 索引、切片)、采样等。
默认情况下,Tensors是在 CPU 上创建的,在GPU运行需要显式地使用 .to 函数,将tensor移动到 GPU(当然首先是检查 GPU 可用性之后)。请记住,跨设备复制大量Tensors ,在时间和内存方面可能很费的!
.to
# We move our tensor to the GPU if available
if torch.cuda.is_available():tensor = tensor.to("cuda")
tensors中的一些操作,和NumPy API类似,比如索引和切片
索引和切片:
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)
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.]])
连接Tensors
可以使用按给定维度,连接一系列张量。 参见 torch.stack, 另一个张量连接运算符,它与 略有不同。torch.cat
t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
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
# ``tensor.T`` returns the transpose of a tensor
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)y3 = torch.rand_like(y1)
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)
tensor([[1., 0., 1., 1.],[1., 0., 1., 1.],[1., 0., 1., 1.],[1., 0., 1., 1.]])
单元素Tensor
如果你有一个单元素张量,例如通过聚合所有 一个张量的值变成一个值,可以将其转换为Python 数值使用:item()
agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
12.0 <class 'float'>
in place操作
将结果存储到操作数中的操作,称为in place操作。它们用后缀表示。 例如:,,将更改。_x.copy_(y)
x.t_() x
print(f"{tensor} \n")
tensor.add_(5)
print(tensor)
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.]])
注意
in place运算可以节省一些内存,但在计算导数时可能会出现问题,因为会立即丢失运算的历史记录。因此,不鼓励使用它们。
觉得有用 收藏 收藏 收藏
点个赞 点个赞 点个赞
End
GPT专栏文章:
GPT实战系列-ChatGLM3本地部署CUDA11+1080Ti+显卡24G实战方案
GPT实战系列-LangChain + ChatGLM3构建天气查询助手
大模型查询工具助手之股票免费查询接口
GPT实战系列-简单聊聊LangChain
GPT实战系列-大模型为我所用之借用ChatGLM3构建查询助手
GPT实战系列-P-Tuning本地化训练ChatGLM2等LLM模型,到底做了什么?(二)
GPT实战系列-P-Tuning本地化训练ChatGLM2等LLM模型,到底做了什么?(一)
GPT实战系列-ChatGLM2模型的微调训练参数解读
GPT实战系列-如何用自己数据微调ChatGLM2模型训练
GPT实战系列-ChatGLM2部署Ubuntu+Cuda11+显存24G实战方案
GPT实战系列-Baichuan2本地化部署实战方案
GPT实战系列-Baichuan2等大模型的计算精度与量化
GPT实战系列-GPT训练的Pretraining,SFT,Reward Modeling,RLHF
GPT实战系列-探究GPT等大模型的文本生成-CSDN博客