我是新的TensorFlow 2和阅读文档:https://www.tensorflow.org/api_docs/python/tf/Module
在本页,与我的问题相关的部分是:MLP
(从那里复制粘贴):
class MLP(tf.Module):
def __init__(self, input_size, sizes, name=None):
super(MLP, self).__init__(name=name)
self.layers = []
with self.name_scope:
for size in sizes:
self.layers.append(Dense(input_dim=input_size, output_size=size))
input_size = size
@tf.Module.with_name_scope
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x
和我不明白为什么输出如下:
>>> module = MLP(input_size=5, sizes=[5, 5])
>>> module.variables
(<tf.Variable 'mlp/b:0' shape=(5,) ...>,
<tf.Variable 'mlp/w:0' shape=(5, 5) ...>,
<tf.Variable 'mlp/b:0' shape=(5,) ...>,
<tf.Variable 'mlp/w:0' shape=(5, 5) ...>,
)
我期望mlp/b:1
和mlp/w:1
出现的地方。我也在我的机器上尝试了相同的代码,并在name
上得到了相同的结果,即mlp/b:0
和mlp/w:0
都出现了两次。谁能帮我指出我漏掉了哪一点吗?结果是否意味着相同的W
,b
被重用?
从文档,
特遣部队。变量是一个张量,其值可以通过对其运行操作而改变。特定的操作允许你读取和修改这个张量的值。更高级别的库,如tf。Keras使用tf。变量存储模型参数。
:0
不是层数。它用于表示底层API中op的输出张量。
例如,tf.Variable
分配一个张量[:0]
,而通过tf.split
的三向分裂为计算图中各自的op分配三个张量[:0,:1,:2]
tf.Variable([1])
# has output
# <tf.Variable 'Variable:0' shape=(1,) dtype=int32, numpy=array([1], dtype=int32)>
和
tf.compat.v1.disable_eager_execution()
a,b,c = tf.split([1,1,1], 3)
print(a.name) # split:0
print(b.name) # split:1
print(c.name) # split:2
参考这篇文章