簡體   English   中英

如何凍結張量流模型?

[英]how to freeze the tensorflow model?

我有一個保存rnn類的model.py文件。 例如:

class TextRNN:
    def __init__(self, hidden_size, num_classes, learning_rate...):

        self.input_data = tf.placeholder(tf.int32,[batch_size,None],name="input_data")
        self.output_label = tf.placeholder(tf.float32,[batch_size,num_classes],name="output_label")
        self.dropout_rate = tf.placeholder(tf.float32,name="dropout_rate")

        with tf.name_scope("embedding"):
            ...

        with tf.name_scope("hidden"):
            ...

        with tf.name_scope("output"):
            ...

在main.py中,我使用了以下代碼來使用此模型。

with tf.Graph().as_default():
        sess = tf.Session()
        with sess.as_default():
            rnn = TextRNN(...)
            ...

            #training step
            def train_step(x_batch, y_batch...):
                feed_dict = {rnn.input_data:x_batch,rnn.output_label:y_batch,rnn.dropout_rate:0.5}
                sess.run(feed_dict)
                ...
            #testing step
            def test_step(x_batch, y_batch...):
                feed_dict = {rnn.input_data:x_batch,rnn.output_label:y_batch,rnn.dropout_rate:0.5}
                sess.run(feed_dict)

我的問題是在測試步驟中如何凍結模型? 我知道如果運行訓練步驟,該模型的權重將被更新。 但是當我運行測試步驟時,我不再想要更新權重了,我只想獲得預測的結果? 我應該如何修改我的代碼以實現此目的?

要訓​​練模型,您需要定義一個訓練來運行模型, 例如 train_op = tf.train.AdamOptimizer(1e-4).minimize(loss_op)意味着每次您運行train_op它都會進行AdamOptimizer的一步在loss_op ,它將更新變量。

但是,如果要評估模型,只需運行output_op即可得到結果。 TensorFlow將僅運行圖表中所需的部分,而不會更多。 所以,當你問output_oploss_op它不會改變的變量。

您可能會發現此頁面有助於了解更多內容在TensorFlow中的工作方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM