gpt4 book ai didi

python - 将张量中的一些元素随机设置为零(计算时间短)

转载 作者:行者123 更新时间:2023-12-04 14:59:12 27 4
gpt4 key购买 nike

我有一个形状张量 (3072,1000)它代表我的神经网络中的权重。我想要:

  • 随机将其 60% 的元素设置为零。
  • 更新权重后,保持 60% 的元素为零但再次随机,即与之前的元素不同。

  • 注:我的网络不是通常使用反向传播算法的人工神经网络,但它是大脑中神经元的生物物理模型,所以我使用了特殊的权重更新规则。因此,我认为 pytorch 中的就绪函数(如果有)可能没有帮助。
    我尝试了以下代码,它正在工作,但需要很长时间,因为每次更新我的权重张量后,我都必须运行该代码以再次将权重张量设置为 60% 零
    row_indices = np.random.choice(np.size(mytensor.weight, 0),
    replace=False,size=int(np.size(mytensor.weight, 0)* 0.6))
    column_indices = np.random.choice(np. size(mytensor.weight, 1),
    replace=False, size=int(np. size(mytensor.weight, 1) * 0.6))
    for r in row_indices:
    for c in column_indices:
    (mytensor.weight)[r][c] = 0

    最佳答案

    您可以使用 dropout 功能:

    import torch.nn.functional as F

    my_tensor.weight = F.dropout(my_tensor.weight, p=0.6)

    关于python - 将张量中的一些元素随机设置为零(计算时间短),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67282712/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com