我正在尝试在训练后从模型中提取权重。这是一个玩具示例
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 个值最佳答案
您的代码中存在一些问题需要修复:
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')
现在让我们看看上述修复如何帮助我们获取变量的值。每层都有两种类型的变量:权重和偏差。在下面的代码片段(你的修改版本)中,我将只展示如何检索全连接层的权重:
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
关于python - 如何从tensorflow fully_connected获取权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158606/