python - 在 Tensorflow 中更改变量的初始值设定项

标签 python tensorflow

我有一个预定义的代码可以创建一个 Tensorflow 图。变量包含在变量作用域中,每个变量都有一个预定义的初始值设定项。 有什么办法可以改变变量的初始值设定项吗?

例子: 第一张图定义

with tf.variable_scope('conv1')
    w = tf.get_variable('weights')

稍后我想修改变量并将初始值设定项更改为 Xavier:

 with tf.variable_scope('conv1')
     tf.get_variable_scope().reuse_variable()
     w = tf.get_variable('weights',initializer=tf.contrib.layers.xavier_initializer(uniform=False))

然而,当我重用一个变量时,初始化器并没有改变。 稍后当我执行 initialize_all_variables() 时,我得到默认值而不是 Xavier 如何更改变量的初始值设定项? 谢谢

最佳答案

问题是在设置重用时无法更改初始化(初始化是在第一个 block 中设置的)。

因此,只需在第一次变量范围调用期间使用 xavier 初始化定义它。所以第一个调用是,然后用正确的方式初始化所有变量:

with tf.variable_scope(name) as scope:
    kernel = tf.get_variable("W",
                             shape=kernel_shape, initializer=tf.contrib.layers.xavier_initializer_conv2d())
    # you could also just define your network layer 'now' using this kernel
    # ....
    # Which would need give you a model (rather just weights)

如果您需要重新使用这组权重,第二次调用可以获得它的副本。

with tf.variable_scope(name, reuse=True) as scope:
    kernel = tf.get_variable("W")
    # you can now reuse the xavier initialized variable
    # ....

关于python - 在 Tensorflow 中更改变量的初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37992326/

相关文章:

python - TensorFlow 中的高效图像膨胀

python matplotlib : Plotting to GUI in non-main thread

Python-Pandas : meaning of asterisk sign in expression

tensorflow - 如何在reduce_XXX Tensorflow 操作中屏蔽向量?

tensorflow - 如何设置用于二元分类的神经网络架构

python - 如何使用 mmconvert 将 tensorflow 模型(InceptionResnetV2 pb 文件)转换为 pytorch 模型?

python - 带有 Mobilenets 的 Tensorflow 对象检测 API 过拟合自定义多类数据集

python - 如何检测手中的物体?从这个视频

Python:如何从网络导入Excel文件?

python - 自创建模块用于异步导入