爱德华的源代码中,类Normal的位置在哪里?

时间:2017-02-10 03:32:34

标签: tensorflow edward

使用edward时,我们始终使用from edward.models import Normal,但我在github

中找不到Normal的声明

任何能告诉我它在哪里的人

1 个答案:

答案 0 :(得分:2)

它们在edward/models/random_variables.py中定义。

您可以像这样导入from edward.models import Normal 类:

from edward.models.random_variables import *

这建议查看edward/models/__init__.py,其中包含以下行:

edward/models/random_variables.py

查看from edward.models.random_variable import RandomVariable as _RandomVariable from tensorflow.contrib import distributions as _distributions # Automatically generate random variable classes from classes in # tf.contrib.distributions. _globals = globals() for _name in sorted(dir(_distributions)): _candidate = getattr(_distributions, _name) if (_inspect.isclass(_candidate) and _candidate != _distributions.Distribution and issubclass(_candidate, _distributions.Distribution)): # to use _candidate's docstring, must write a new __init__ method def __init__(self, *args, **kwargs): _RandomVariable.__init__(self, *args, **kwargs) __init__.__doc__ = _candidate.__init__.__doc__ _params = {'__doc__': _candidate.__doc__, '__init__': __init__} _globals[_name] = type(_name, (_RandomVariable, _candidate), _params) del _candidate ,我们找到了this code

tensorflow.contrib.distributions

这将通过tensorflow.contrib.distributions.Distribution模块查找从__file__派生的类(忽略其他属性,例如模块的Distribution成员或基本_globals[_name] = type(_name, (_RandomVariable, _candidate), _params) 类本身)。对于每一个,它会进行一些黑客攻击(仅影响生成的文档)然后执行此关键行:

RandomVariable

type()内置函数创建一个新类型,即声明一个新类。第二个参数是基类列表,这里是edward' _globals类和TensorFlow随机变量类。之前它将from edward.models.random_variable import RandomVariable as EdRandVar from tensorflow.contrib.distributions import Normal as TfNormal Normal = type("Normal", (EdRandVar, TfNormal), {...}) 定义为globals(),这是一个内置函数,返回模块变量的字典。因此,在您感兴趣的情况下,上述行等同于以下内容:

from edward.models.random_variable import RandomVariable as EdRandVar
from tensorflow.contrib.distributions import Normal as TfNormal
class Normal(EdRandVar, TfNormal):
    pass

反过来又等同于此(如果忽略文档字符串):

$items = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8'];
$result = '';
for($i = 0 ; $i < count($items) ; $i++) {
    $result .= '<div class="' 
        . 'group_' 
        . intval(floor($i/3) + 1)
        . '">' 
        . $items[$i] 
        . '</div>';
}
echo $result;