大佬教程收集整理的这篇文章主要介绍了如何创建 n 维稀疏张量? (pytorch),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将张量初始化为稀疏张量。
当张量的维数为 2 时,我可以使用 torch.nn.init.sparse(tensor,sparsity=0.1)
import torch
dim = torch.Size([3,2])
w = torch.Tensor(dim)
torch.nn.init.sparse_(w,sparsity=0.1)
结果
tensor([[ 0.0000,0.0147],[-0.0190,0.0004],[-0.0004,0.0000]])
但是当张量维度 > 2 时,这个函数不起作用。
v = torch.Tensor(torch.Size([5,5,30,2]))
torch.nn.init.sparse_(v,sparsity=0.1)
结果
ValueError: Only tensors with 2 dimensions are supported
我需要这个是因为我想用它来初始化卷积权重。
torch.nn.init.sparse_()
函数的定义如下
def sparse_(tensor,sparsity,std=0.01):
r"""Fills the 2D input `Tensor` as a sparse matrix,where the
non-zero elements will be drawn from the normal diStribution
:math:`\mathcal{N}(0,0.01)`,as described in `Deep learning via
Hessian-free optimization` - martens,J. (2010).
Args:
tensor: an n-dimensional `torch.Tensor`
sparsity: The fraction of elements in each column to be set to zero
std: the standard deviation of the normal diStribution used to generate
the non-zero values
Examples:
>>> w = torch.empty(3,5)
>>> nn.init.sparse_(w,sparsity=0.1)
"""
if tensor.ndimension() != 2:
raise ValueError("Only tensors with 2 dimensions are supported")
rows,cols = tensor.shape
num_zeros = int(math.ceil(sparsity * rows))
with torch.no_grad():
tensor.normal_(0,std)
for col_IDx in range(cols):
row_inDices = torch.randperm(rows)
zero_inDices = row_inDices[:num_zeros]
tensor[zero_inDices,col_IDx] = 0
return tensor
如何制作 n 维稀疏张量?
pytorch 有没有办法创建这种张量?
或者我可以换一种方式吗?
该函数是以下方法的实现:
我们发现的最好的随机初始化方案是我们自己的设计之一,“稀疏初始化”。在这个方案中,我们硬限制了 每个非零传入连接权重的数量 单位(我们在实验中使用了 15 个)并将偏差设置为 0(或 0.5 为 tanh 单位)。
高阶张量不支持它的原因是因为它在每列中保持相同比例的零,并且不清楚对于高阶张量来说这个条件应该保持在哪些[子集]维度上。
>您可以使用 dropout 或等效函数实现此初始化策略,例如:
def sparse_(tensor,sparsity,std=0.01):
with torch.no_grad():
tensor.normal_(0,std)
tensor = F.dropout(tensor,sparsity)
return tensor
如果您希望强制执行列、通道等方面的零比例(而不仅仅是总比例),您可以实现与原始函数类似的逻辑。
以上是大佬教程为你收集整理的如何创建 n 维稀疏张量? (pytorch)全部内容,希望文章能够帮你解决如何创建 n 维稀疏张量? (pytorch)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。