pytorch 常见函数理解

本文详细介绍了PyTorch中关键的张量操作,包括gather、squeeze、expand、sum、contiguous、softmax、max、argmax等函数的使用方法及应用场景,帮助读者深入理解并掌握这些操作的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gather

>>> a = torch.Tensor([[1,2],[3,4]])
>>> a
tensor([[ 1.,  2.],
        [ 3.,  4.]])
>>> torch.gather(a,1,torch.LongTensor([
... [0,0],
... [1,0]]))
tensor([[ 1.,  1.],
        [ 4.,  3.]])
#1代表按照第1维度进行计算
#第一维也就是按照行,第一行[0,0]代表,新的tensor的第一行的两个元素,分别是a第一行的的第0个和第0个元素
#第一维也就是按照行,第二行[1,0]代表,新的tensor的第二行的两个元素,分别是a第二行的第1个和第0个元素
>>> torch.gather(a,0,torch.LongTensor([
... [0,0],
... [1,0]]))
tensor([[ 1.,  2.],
        [ 3.,  2.]])
#0代表按照第0维度进行计算
#第0维也就是按照列,第二列[0,0]代表,新的tensor的第二列的两个元素,分别是a第二列的第0个和第0个元素

 

squeeze 

将维度为1的压缩掉。如size为(3,1,1,2),压缩之后为(3,2)

import torch
a=torch.randn(2,1,1,3)
print(a)
print(a.squeeze())

输出:

tensor([[[[-0.2320, 0.9513, 1.1613]]],


[[[ 0.0901, 0.9613, -0.9344]]]])

tensor([[-0.2320, 0.9513, 1.1613],
[ 0.0901, 0.9613, -0.9344]])


tensor([[-0.2320, 0.9513, 1.1613],
[ 0.0901, 0.9613, -0.9344]])

  

expand

扩展某个size为1的维度。如(2,2,1)扩展为(2,2,3)

import torch
x=torch.randn(2,2,1)
print(x)
y=x.expand(2,2,3)
print(y)

 


输出:

tensor([[[ 0.0608],
[ 2.2106]],

[[-1.9287],
[ 0.8748]]])
tensor([[[ 0.0608, 0.0608, 0.0608],
[ 2.2106, 2.2106, 2.2106]],

[[-1.9287, -1.9287, -1.9287],
[ 0.8748, 0.8748, 0.8748]]])

  

参考:https://blog.youkuaiyun.com/hbu_pig/article/details/81454503
 

sum

size为(m,n,d)的张量,dim=1时,输出为size为(m,d)的张量

import torch
a=torch.tensor([[[1,2,3],[4,8,12]],[[1,2,3],[4,8,12]]])
print(a.sum())
print(a.sum(dim=1))

输出:

tensor(60)
tensor([[ 5, 10, 15],
[ 5, 10, 15]])

  

contiguous

返回一个内存为连续的张量,如本身就是连续的,返回它自己。一般用在view()函数之前,因为view()要求调用张量是连续的。可以通过is_contiguous查看张量内存是否连续。

import torch
a=torch.tensor([[[1,2,3],[4,8,12]],[[1,2,3],[4,8,12]]])
print(a.is_contiguous)

print(a.contiguous().view(4,3))

输出:

<built-in method is_contiguous of Tensor object at 0x7f4b5e35afa0>
tensor([[ 1, 2, 3],
[ 4, 8, 12],
[ 1, 2, 3],
[ 4, 8, 12]])

  

softmax

假设数组V有C个元素。对其进行softmax等价于将V的每个元素的指数除以所有元素的指数之和。这会使值落在区间(0,1)上,并且和为1。

import torch
import torch.nn.functional as F

a=torch.tensor([[1.,1],[2,1],[3,1],[1,2],[1,3]])
b=F.softmax(a,dim=1)
print(b)

输出:

tensor([[ 0.5000, 0.5000],
[ 0.7311, 0.2689],
[ 0.8808, 0.1192],
[ 0.2689, 0.7311],
[ 0.1192, 0.8808]])

 

max

返回最大值,或指定维度的最大值以及index

import torch
a=torch.tensor([[.1,.2,.3],
[1.1,1.2,1.3],
[2.1,2.2,2.3],
[3.1,3.2,3.3]])
print(a.max(dim=1))
print(a.max())

输出:

(tensor([ 0.3000, 1.3000, 2.3000, 3.3000]), tensor([ 2, 2, 2, 2]))
tensor(3.3000)

  

argmax

返回最大值的index

import torch
a=torch.tensor([[.1,.2,.3],
[1.1,1.2,1.3],
[2.1,2.2,2.3],
[3.1,3.2,3.3]])
print(a.argmax(dim=1))
print(a.argmax(dim=0))
print(a.argmax())

输出:

tensor([ 2, 2, 2, 2])
tensor([ 3, 3, 3])
tensor(11)

  

  

 


 

### PyTorch 损失函数概述 在机器学习领域,尤其是深度学习框架如PyTorch中,损失函数扮演着至关重要的角色。这些函数用于评估模型预测值与实际目标之间的差异程度,并指导优化过程以最小化这种差距。 #### 常见的损失函数及其应用范围 1. **L1 Loss (Mean Absolute Error)** 此损失函数计算输入张量`input`和目标张量`target`之间元素级绝对差别的平均值。适用于回归问题,在某些情况下可以减少异常值的影响[^1]。 ```python import torch from torch.nn import L1Loss input_tensor = torch.tensor([[1., 2., 3., 4.]]) target_tensor = torch.tensor([[5., 6., 7., 8.]]) loss_function = L1Loss() result = loss_function(input_tensor, target_tensor) print(f"L1 Loss: {result.item()}") # 输出应接近于4. ``` 2. **MSE Loss (Mean Squared Error)** 该损失函数测量两个相同大小张量间对应位置上数值差异平方后的均值。由于其对较大错误更为敏感的特点,常被应用于需要精确度较高的场景下[^4]。 ```python from torch.nn import MSELoss mse_loss_fn = MSELoss() output_mse = mse_loss_fn(input_tensor, target_tensor) print(f"MSE Loss: {output_mse.item()}") ``` 除了上述两种外,还有其他多种类型的损失函数可供选择: - **Cross Entropy Loss**: 主要针对分类任务设计,能够有效处理多类别标签数据集。 - **BCEWithLogitsLoss / Binary CrossEntropy with Logits**: 结合sigmoid激活层与二元交叉熵一起使用的便捷形式,特别适合解决二分类问题。 为了更好地理解如何使用这些损失函数以及它们的具体实现细节,建议查阅官方文档或相关教程资料获取更多信息[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值