【tensorflow】列印Tensorflow graph中的所有變數--tf.trainable_variables()

來源:互聯網
上載者:User

一般來說,列印tensorflow變數的函數有兩個:
tf.trainable_variables () 和 tf.all_variables()
不同的是:
tf.trainable_variables () 指的是需要訓練的變數
tf.all_variables() 指的是所有變數

一般而言,我們更關注需要訓練的訓練變數:
值得注意的是,在輸出變數名時,要對整個graph進行初始化

一、列印需要訓練的變數名稱

sess.run(tf.global_varibales_initializer())variable_name = [v.name for c in tf.trainable_variables()]print(variable_names)

二、列印需要訓練的變數名稱和變數值

variable_names = [v.name for v in tf.trainable_variables()]values = sess.run(variable_names)for k,v in zip(variable_names, values):    print("Variable: ", k)    print("Shape: ", v.shape)    print(v)

這裡提供一個函數,列印變數名稱,shape及其變數數目

def print_num_of_total_parameters(output_detail=False, output_to_logging=False):    total_parameters = 0    parameters_string = ""    for variable in tf.trainable_variables():        shape = variable.get_shape()        variable_parameters = 1        for dim in shape:            variable_parameters *= dim.value        total_parameters += variable_parameters        if len(shape) == 1:            parameters_string += ("%s %d, " % (variable.name, variable_parameters))        else:            parameters_string += ("%s %s=%d, " % (variable.name, str(shape), variable_parameters))    if output_to_logging:        if output_detail:            logging.info(parameters_string)        logging.info("Total %d variables, %s params" % (len(tf.trainable_variables()), "{:,}".format(total_parameters)))    else:        if output_detail:            print(parameters_string)        print("Total %d variables, %s params" % (len(tf.trainable_variables()), "{:,}".format(total_parameters)))

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.