简体   繁体   中英

How to migrate from TensorFlow 1.x to TensorFlow 2.x

class Model:
    def __init__(
        self,
        learning_rate,
        num_layers,
        size,
        size_layer,
        output_size,
        forget_bias = 0.1,
    ):
        def lstm_cell(size_layer):
            return tf.compat.v1.nn.rnn_cell.LSTMCell(size_layer, state_is_tuple = False)

        rnn_cells = tf.compat.v1.nn.rnn_cell.MultiRNNCell(
            [lstm_cell(size_layer) for _ in range(num_layers)],
            state_is_tuple = False,
        )
        self.X = tf.compat.v1.placeholder(tf.float32, (None, None, size))
        self.Y = tf.compat.v1.placeholder(tf.float32, (None, output_size))
        drop = tf.compat.v1.nn.rnn_cell.DropoutWrapper(
            rnn_cells, output_keep_prob = forget_bias
        )
        self.hidden_layer = tf.compat.v1.placeholder(
            tf.float32, (None, num_layers * 2 * size_layer)
        )
        self.outputs, self.last_state = tf.compat.v1.nn.dynamic_rnn(
            drop, self.X, initial_state = self.hidden_layer, dtype = tf.float32
        )
        self.logits = tf.compat.v1.layers.dense(self.outputs[-1], output_size)
        self.cost = tf.reduce_mean(tf.square(self.Y - self.logits))
        self.optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate).minimize(
            self.cost
        ) 

i want to convert this code above to relevant TensorFlow 2.x without eager execution, anyone can help? I been trying to to change few things like: changing tf.compat.v1.nn.rnn_cell.LSTMCell to tf.keras.layers.LSTMCell and tf.compat.v1.nn.rnn_cell.MultiRNNCell to tf.keras.layers.StackedRNNCells also tf.compat.v1.nn.dynamic_rnn to tf.keras.layers.RNN how do i do this?

TensorFlow 1.x scripts will not work directly with TensorFlow 2.x but they need converting.

tf_upgrade_v2 --infile tensorflow_v1.py --outfile tensorflow_v2.py

If you have multiple files within a folder, you can use the below command.

tf_upgrade_v2  v1-code-folder  code-upgraded-folder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM