快捷方式

ParameterDict

class torch.nn.ParameterDict(parameters=None)[source][source]

在一个字典中保存参数。

ParameterDict 可以像普通的 Python 字典一样进行索引,但其包含的 Parameters 会被正确注册,并对所有 Module 方法可见。其他对象则像普通 Python 字典一样处理。

ParameterDict 是一个有序字典。update() 方法与其他无序映射类型(例如 Python 的普通 dict)一起使用时,不会保留合并映射的顺序。另一方面,OrderedDict 或另一个 ParameterDict 将保留其顺序。

请注意,构造函数、字典元素的赋值以及 update() 方法会将任何 Tensor 转换为 Parameter

参数

values (iterable, optional) – (string : Any) 的映射(字典)或类型为 (string, Any) 的键值对可迭代对象

示例

class MyModule(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.params = nn.ParameterDict({
                'left': nn.Parameter(torch.randn(5, 10)),
                'right': nn.Parameter(torch.randn(5, 10))
        })

    def forward(self, x, choice):
        x = self.params[choice].mm(x)
        return x
clear()[source][source]

从 ParameterDict 中移除所有项。

copy()[source][source]

返回此 ParameterDict 实例的副本。

返回类型

ParameterDict

fromkeys(keys, default=None)[source][source]

返回一个包含提供的键的新 ParameterDict。

参数
  • keys (iterable, string) – 用于创建新 ParameterDict 的键

  • default (Parameter, optional) – 为所有键设置的值

返回类型

ParameterDict

get(key, default=None)[source][source]

如果存在,则返回与 key 关联的参数。否则,如果提供了 default,则返回 default;如果未提供,则返回 None。

参数
  • key (str) – 从 ParameterDict 中获取的键

  • default (Parameter, optional) – 如果 key 不存在,则返回的值

返回类型

Any

items()[source][source]

返回 ParameterDict 键值对的可迭代对象。

返回类型

Iterable[tuple[str, Any]]

keys()[source][source]

返回 ParameterDict 键的可迭代对象。

返回类型

Iterable[str]

pop(key)[source][source]

从 ParameterDict 中移除 key 并返回其参数。

参数

key (str) – 从 ParameterDict 中弹出的键

返回类型

Any

popitem()[source][source]

移除并返回 ParameterDict 中最后插入的 (key, parameter) 对。

返回类型

tuple[str, Any]

setdefault(key, default=None)[source][source]

为 ParameterDict 中的 key 设置默认值。

如果 key 在 ParameterDict 中,则返回其值。否则,使用参数 default 插入 key 并返回 defaultdefault 默认为 None

参数
  • key (str) – 要设置默认值的键

  • default (Any) – 设置给键的参数

返回类型

Any

update(parameters)[source][source]

使用来自 parameters 的键值对更新 ParameterDict,覆盖现有键。

注意

如果 parameters 是一个 OrderedDict、一个 ParameterDict 或一个键值对可迭代对象,则其中新元素的顺序将被保留。

参数

parameters (iterable) – 从字符串到 Parameter 的映射(字典),或类型为 (string, Parameter) 的键值对可迭代对象

values()[source][source]

返回 ParameterDict 值的可迭代对象。

返回类型

Iterable[Any]]

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取针对初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得问题解答

查看资源