Python 获取Tensorflow中线性回归的系数

Python 获取Tensorflow中线性回归的系数,python,machine-learning,tensorflow,Python,Machine Learning,Tensorflow,我在Tensorflow中做了一个简单的线性回归。我怎么知道回归系数是多少? 我已经看过文件了,但是我在任何地方都找不到!() 编辑代码示例 import numpy as np import tensorflow as tf # Declare list of features, we only have one real-valued feature def model_fn(features, labels, mode): # Build a linear model and pre

我在Tensorflow中做了一个简单的线性回归。我怎么知道回归系数是多少? 我已经看过文件了,但是我在任何地方都找不到!()

编辑代码示例

import numpy as np
import tensorflow as tf

# Declare list of features, we only have one real-valued feature
def model_fn(features, labels, mode):
  # Build a linear model and predict values
  W = tf.get_variable("W", [1], dtype=tf.float64)
  b = tf.get_variable("b", [1], dtype=tf.float64)
  y = W * features['x'] + b
  # Loss sub-graph
  loss = tf.reduce_sum(tf.square(y - labels))
  # Training sub-graph
  global_step = tf.train.get_global_step()
  optimizer = tf.train.GradientDescentOptimizer(0.01)
  train = tf.group(optimizer.minimize(loss),
                   tf.assign_add(global_step, 1))
  # EstimatorSpec connects subgraphs we built to the
  # appropriate functionality.
  return tf.estimator.EstimatorSpec(
      mode=mode,
      predictions=y,
      loss=loss,
      train_op=train)

estimator = tf.estimator.Estimator(model_fn=model_fn)
# define our data sets
x_train = np.array([1., 2., 3., 4.])
y_train = np.array([0., -1., -2., -3.])
x_eval = np.array([2., 5., 8., 1.])
y_eval = np.array([-1.01, -4.1, -7, 0.])
input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x": x_train}, y_train, batch_size=4, num_epochs=None, shuffle=True)
train_input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x": x_train}, y_train, batch_size=4, num_epochs=1000, shuffle=False)
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
    {"x": x_eval}, y_eval, batch_size=4, num_epochs=1000, shuffle=False)

# train
estimator.train(input_fn=input_fn, steps=1000)
# Here we evaluate how well our model did.
train_metrics = estimator.evaluate(input_fn=train_input_fn)
eval_metrics = estimator.evaluate(input_fn=eval_input_fn)
print("train metrics: %r"% train_metrics)
print("eval metrics: %r"% eval_metrics)
编辑:正如所指出的,在这个答案发布后,已经有了一些变化。现在有了估计器方法和,估计器权重似乎不再自动添加到
tf.GraphKeys.MODEL_变量中


估计器基本上被设计成一个黑箱,因此没有直接的API来检索权重。即使像您的情况一样,您是定义模型的人(与使用先前存在的模型相反),您也无法直接访问估计器对象中的参数

也就是说,您仍然可以通过其他方式检索变量。如果您知道变量的名称,一种选择是使用或从graph对象获取变量。一个更实用和通用的选择是使用集合。无论是在调用时还是之后调用,都可以将模型变量放在公共集合名称下,以便以后检索。如果您查看
tf.estimator.LinearRegressor
是如何实际构建的(在中搜索函数
linear_模型
),所有模型变量都会添加到
tf.GraphKeys.GLOBAL_变量
tf.GraphKeys.model_变量
。这对于所有可用的罐装估计器来说都是通用的(想必,我还没有真正检查过),因此通常在使用其中一种估计器时,您应该能够简单地执行以下操作:

model_vars = tf.get_collection(tf.GraphKeys.MODEL_VARIABLES)
在这种情况下,最好使用
tf.GraphKeys.MODEL_VARIABLES
,而不是
tf.GraphKeys.GLOBAL_VARIABLES
,后者具有更广泛的用途,可能还包含其他不相关的变量。

尝试以下方法:

LR.train(input_fn=train_input_data,steps = 1)

with tf.Session() as sess:
    last_check = tf.train.latest_checkpoint(tf_data)
    saver = tf.train.import_meta_graph(last_check + '.meta')
    print (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()))

你能发布你的代码让我们看看你到底做了什么吗?一般来说很难回答…对不起。我遵循教程示例中的示例,您不使用,而是实现自己的估计器,对吗?(这相当于线性回归)。@jdehesa我也尝试过这个选项。在这种情况下,如何获取系数值?我的tf.GraphKeys.MODEL_变量为空。我正在使用:
print([(v,线性回归器。get_variable_value(v))代表线性回归器中的v。get_variable_names())
@JasonChing谢谢,我已经更新了答案(或者可以自己发布另一个答案,我会投票并参考)。显然,自从答案公布后,他们做了一些改变。