tf.zeros() return tf.get_variable() 吗?
Does tf.zeros() return tf.get_variable()?
试图理解 keras 优化器 (source code) 中的 SGD
优化代码。在 get_updates
模块中,我们有:
# momentum
shapes = [K.int_shape(p) for p in params]
moments = [K.zeros(shape) for shape in shapes]
self.weights = [self.iterations] + moments
for p, g, m in zip(params, grads, moments):
v = self.momentum * m - lr * g # velocity
self.updates.append(K.update(m, v))
其中 K = keras.backend
。现在,由于 moments
被设置为零张量列表,而 m
是该列表的迭代,为什么 m
不总是在 v = self.momentum * m - lr * g
?
现在我查找了用于 tensorflow 的 keras.backend.zeros
的代码(source code), and keras.backend.zeros
returns tf.zeros
,这显然 return 是零的常量张量。(编辑:或者 return 是 tf.Variable
如果指定了形状,则用 tf.zeros
初始化。)
我的直觉是它会 return 类似 tf.get_variable()
的初始化器为零,因此张量不会每次都被覆盖。相反,名称为 m
的张量只会按 K.update()
.
不断更新
那么 tf.zeros()
是否真的像 tf.get_variable()
一样使用零初始化?还有什么我想念的吗?
编辑: 所以即使指定了形状,上面链接的源代码似乎仍然是 return 一个新的张量变量,而不是重用现有的(即使用 get_variable()
),这看起来很困难,因为没有指定名称。仍然对为什么现有变量 returned 而不是零的新张量变量感到困惑。
我认为您错过了正确的 K.zeros
功能。这是 keras 2.1 (keras/backend/tensorflow_backend.py
) 中的源代码:
def zeros(shape, dtype=None, name=None):
"""Instantiates an all-zeros variable and returns it.
# Arguments
shape: Tuple of integers, shape of returned Keras variable
dtype: String, data type of returned Keras variable
name: String, name of returned Keras variable
# Returns
A variable (including Keras metadata), filled with `0.0`.
# Example
```python
>>> from keras import backend as K
>>> kvar = K.zeros((3,4))
>>> K.eval(kvar)
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]], dtype=float32)
```
"""
if dtype is None:
dtype = floatx()
tf_dtype = tf.as_dtype(dtype)
return variable(tf.constant_initializer(0., dtype=tf_dtype)(shape),
dtype, name)
如您所见,它实际上 returns 用零 初始化的变量,而不是常量零张量。 documentation 表示相同:
Instantiates an all-zeros variable and returns it.
编辑:后续问题的答案。
这实际上是一个很好的观察:你是对的,对Optimizer.get_updates(loss, params)
的后续调用将创建new个变量,赋值new ops 到 self.updates
和 new 权重到 self.weights
。在某种意义上,get_updates
方法是优化器构造函数的一部分。
但是它是这样工作的:这个方法在每个模型实例中被调用一次。它 returns 在不同批次的循环中多次应用的更新操作列表,但操作本身保持不变。下面是Model
class(keras/engine/training.py
)的相关代码:
def _make_train_function(self):
...
if self.train_function is None:
...
with K.name_scope('training'):
with K.name_scope(self.optimizer.__class__.__name__):
training_updates = self.optimizer.get_updates(
params=self._collected_trainable_weights,
loss=self.total_loss)
updates = self.updates + training_updates + self.metrics_updates
# Gets loss and metrics. Updates weights at each call.
self.train_function = K.function(inputs,
[self.total_loss] + self.metrics_tensors,
updates=updates,
name='train_function',
**self._function_kwargs)
self.optimizer.get_updates(...)
仅被调用一次以构造 train_function
.
随意检查其他优化器并检查它们是否都在 get_updates()
方法中准备权重和更新操作。
试图理解 keras 优化器 (source code) 中的 SGD
优化代码。在 get_updates
模块中,我们有:
# momentum
shapes = [K.int_shape(p) for p in params]
moments = [K.zeros(shape) for shape in shapes]
self.weights = [self.iterations] + moments
for p, g, m in zip(params, grads, moments):
v = self.momentum * m - lr * g # velocity
self.updates.append(K.update(m, v))
其中 K = keras.backend
。现在,由于 moments
被设置为零张量列表,而 m
是该列表的迭代,为什么 m
不总是在 v = self.momentum * m - lr * g
?
现在我查找了用于 tensorflow 的 keras.backend.zeros
的代码(source code), and keras.backend.zeros
returns tf.zeros
,这显然 return 是零的常量张量。(编辑:或者 return 是 tf.Variable
如果指定了形状,则用 tf.zeros
初始化。)
我的直觉是它会 return 类似 tf.get_variable()
的初始化器为零,因此张量不会每次都被覆盖。相反,名称为 m
的张量只会按 K.update()
.
那么 tf.zeros()
是否真的像 tf.get_variable()
一样使用零初始化?还有什么我想念的吗?
编辑: 所以即使指定了形状,上面链接的源代码似乎仍然是 return 一个新的张量变量,而不是重用现有的(即使用 get_variable()
),这看起来很困难,因为没有指定名称。仍然对为什么现有变量 returned 而不是零的新张量变量感到困惑。
我认为您错过了正确的 K.zeros
功能。这是 keras 2.1 (keras/backend/tensorflow_backend.py
) 中的源代码:
def zeros(shape, dtype=None, name=None):
"""Instantiates an all-zeros variable and returns it.
# Arguments
shape: Tuple of integers, shape of returned Keras variable
dtype: String, data type of returned Keras variable
name: String, name of returned Keras variable
# Returns
A variable (including Keras metadata), filled with `0.0`.
# Example
```python
>>> from keras import backend as K
>>> kvar = K.zeros((3,4))
>>> K.eval(kvar)
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]], dtype=float32)
```
"""
if dtype is None:
dtype = floatx()
tf_dtype = tf.as_dtype(dtype)
return variable(tf.constant_initializer(0., dtype=tf_dtype)(shape),
dtype, name)
如您所见,它实际上 returns 用零 初始化的变量,而不是常量零张量。 documentation 表示相同:
Instantiates an all-zeros variable and returns it.
编辑:后续问题的答案。
这实际上是一个很好的观察:你是对的,对Optimizer.get_updates(loss, params)
的后续调用将创建new个变量,赋值new ops 到 self.updates
和 new 权重到 self.weights
。在某种意义上,get_updates
方法是优化器构造函数的一部分。
但是它是这样工作的:这个方法在每个模型实例中被调用一次。它 returns 在不同批次的循环中多次应用的更新操作列表,但操作本身保持不变。下面是Model
class(keras/engine/training.py
)的相关代码:
def _make_train_function(self):
...
if self.train_function is None:
...
with K.name_scope('training'):
with K.name_scope(self.optimizer.__class__.__name__):
training_updates = self.optimizer.get_updates(
params=self._collected_trainable_weights,
loss=self.total_loss)
updates = self.updates + training_updates + self.metrics_updates
# Gets loss and metrics. Updates weights at each call.
self.train_function = K.function(inputs,
[self.total_loss] + self.metrics_tensors,
updates=updates,
name='train_function',
**self._function_kwargs)
self.optimizer.get_updates(...)
仅被调用一次以构造 train_function
.
随意检查其他优化器并检查它们是否都在 get_updates()
方法中准备权重和更新操作。