【问题标题】:custom rnn migration to tensorflow 2.0自定义 rnn 迁移到 tensorflow 2.0
【发布时间】:2020-03-09 13:40:16
【问题描述】:

我需要将 tensorflow 1.x 中的自定义 RNN 实现中的以下部分迁移到 tensorflow 2.x。

我有点卡在需要将 tf.get_variable 转换为 tf.variable_scope 内的 xaver 初始化程序等初始化程序的地方。

我参考了迁移指南,但我仍然无法理解 tf.get_variable 与 xavier 初始化的转换,而且我必须迁移一些没有预定义形状的占位符。


        with tf.variable_scope(self._scope):

            with tf.variable_scope("PresentState"):
                self._U = tf.get_variable("U", shape=[self._num_in, self._n_hidden], dtype=tf.float32,
                                             initializer=xavier_initializer())
                self._W = tf.get_variable("W", shape=[self._n_hidden, self._n_hidden],
                                             dtype=tf.float32,
                                             initializer=xavier_initializer())
                self._b = tf.get_variable("B", shape=[self._n_hidden], dtype=tf.float32,
                                            initializer=xavier_initializer())
                self._p = None

占位符部分。

p = tf.placeholder(tf.float32, shape=[batch_size, None, num_in], name="p")

【问题讨论】:

    标签: python tensorflow tensorflow2.0 tensorflow2.x


    【解决方案1】:

    在惯用的 TF2.x 代码中,您不应使用 tf.Placeholders,而是将它们定义为可调用 @tf.function 的函数参数。由于 TF2.x 现在支持急切执行,因此您不需要任何 tf.Session 调用,因此可以将您的纯 Python 变量传递给任何 @tf.function

    对于你问题的第一部分:

    我对 RNN 没有那么深入,但从您的代码看来,您可以将内部 tf.variable_scope 重构为 tf.Module,这样您就可以按如下方式使用 xavier 初始化(未测试):

    class PresentState(tf.Module):
      def __init__(self, ins, hiddens, outs):
        initializer = tf.initializers.GlorotNormal() # Xavier initialization
        self._U = tf.Variable(initializer([ins, outs]), dtype=tf.float32)
        self._W = tf.Variable(initializer([ins, outs]), dtype=tf.float32)
        self._b = tf.Variable(initializer([outs]), dtype=tf.float32)
        self._p = None
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多