【问题标题】:How to get weights from tensorflow fully_connected如何从 tensorflowfully_connected 中获取权重
【发布时间】:2017-04-01 15:23:15
【问题描述】:

我正在尝试在训练后从模型中提取权重。这是一个玩具示例

import tensorflow as tf
import numpy as np

X_ = tf.placeholder(tf.float64, [None, 5], name="Input")
Y_ = tf.placeholder(tf.float64, [None, 1], name="Output")

X = ...
Y = ...
with tf.name_scope("LogReg"):
    pred = fully_connected(X_, 1, activation_fn=tf.nn.sigmoid)
    loss = tf.losses.mean_squared_error(labels=Y_, predictions=pred)
    training_ops = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(200):
        sess.run(training_ops, feed_dict={
            X_: X,
            Y_: Y
        })
        if (i + 1) % 100 == 0:
            print("Accuracy: ", sess.run(accuracy, feed_dict={
                X_: X,
                Y_: Y
            }))

# Get weights of *pred* here

我查看了Get weights from tensorflow model docs,但找不到检索权重值的方法。

所以在玩具例子的情况下,假设X_的形状是(1000, 5),我怎样才能得到之后1层权重中的5个值

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您的代码中有一些问题需要修复:

    1- 您需要在以下行使用variable_scope 而不是name_scope(请参阅TensorFlow 文档了解它们之间的区别):

    with tf.name_scope("LogReg"):
    

    2- 为了能够稍后在代码中检索变量,您需要知道它的名称。因此,您需要为感兴趣的变量指定一个名称(如果您不支持,则会分配一个默认的名称,但是您需要弄清楚它是什么!):

    pred = tf.contrib.layers.fully_connected(X_, 1, activation_fn=tf.nn.sigmoid, scope = 'fc1')
    

    现在让我们看看上述修复如何帮助我们获取变量的值。每一层都有两种类型的变量:权重和偏差。在以下代码 sn-p(您的修改版本)中,我将仅展示如何检索全连接层的权重:

    X_ = tf.placeholder(tf.float64, [None, 5], name="Input")
    Y_ = tf.placeholder(tf.float64, [None, 1], name="Output")
    
    X = np.random.randint(1,10,[10,5])
    Y = np.random.randint(0,2,[10,1])
    
    with tf.variable_scope("LogReg"):
        pred = tf.fully_connected(X_, 1, activation_fn=tf.nn.sigmoid, scope = 'fc1')
        loss = tf.losses.mean_squared_error(labels=Y_, predictions=pred)
        training_ops = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
    
    with tf.Session() as sess:
    
        all_vars= tf.global_variables()
        def get_var(name):
            for i in range(len(all_vars)):
                if all_vars[i].name.startswith(name):
                    return all_vars[i]
            return None
        fc1_var = get_var('LogReg/fc1/weights')
    
        sess.run(tf.global_variables_initializer())    
        for i in range(200):
            _,fc1_var_np = sess.run([training_ops,fc1_var], feed_dict={
            X_: X,
            Y_: Y 
            })
            print fc1_var_np
    

    【讨论】:

    • 谢谢@Ali。您能否提供有关如何查看冻结的.pb 模型文件中的权重的 MWE。说 inception_v3。 out_val = sess.run([out for op in tf.get_default_graph().get_operations() if op.type != 'Placeholder' for out in op.values() if out.dtype == tf.float32], feed_dict=my_feed_dict)这种方法对我不起作用。
    【解决方案2】:

    试试这个:

    with tf.Session() as sess:
        last_check = tf.train.latest_checkpoint(tf_data)
        saver = tf.train.import_meta_graph(last_check+'.meta')
        saver.restore(sess,last_check)
        ######
        Model_variables = tf.GraphKeys.MODEL_VARIABLES
        Global_Variables = tf.GraphKeys.GLOBAL_VARIABLES
        ######
        all_vars = tf.get_collection(Model_variables)
        # print (all_vars)
        for i in all_vars:
            print (str(i) + '  -->  '+ str(i.eval()))
    

    我知道了:

    <tf.Variable 'linear/linear_model/DOLocationID/weights/part_0:0' shape=(1, 1) dtype=float32_ref>  -->  [[-0.00912262]]
    <tf.Variable 'linear/linear_model/PULocationID/weights/part_0:0' shape=(1, 1) dtype=float32_ref>  -->  [[ 0.00573495]]
    <tf.Variable 'linear/linear_model/passenger_count/weights/part_0:0' shape=(1, 1) dtype=float32_ref>  -->  [[-0.07072949]]
    <tf.Variable 'linear/linear_model/trip_distance/weights/part_0:0' shape=(1, 1) dtype=float32_ref>  -->  [[ 2.59973669]]
    <tf.Variable 'linear/linear_model/bias_weights/part_0:0' shape=(1,) dtype=float32_ref>  -->  [ 4.27982235]
    

    【讨论】:

      猜你喜欢
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多