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

4
我在Tensorflow中进行了简单的线性回归。如何知道回归系数是什么? 我已经阅读了文档,但无法找到任何信息!(https://www.tensorflow.org/api_docs/python/tf/estimator/LinearRegressor编辑 代码示例
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)

你能否发布你的代码,以便我们看到你具体做了什么?一般来说很难回答... - Umberto
对不起,我正在按照 https://www.tensorflow.org/get_started/get_started 中的教程示例进行操作。 - japmelian
你没有使用 tf.estimator.LinearRegressor,而是实现了自己的估算器,对吗?(这相当于一个线性回归器)。 - jdehesa
@jdehesa 我也尝试了那个选项。在这种情况下,我该如何获取系数值? - japmelian
2个回答

3

编辑:正如Jason Ching指出的那样,这个答案发布后发生了一些变化。现在有估算器方法get_variable_namesget_variable_value,估算器权重似乎不再自动添加到tf.GraphKeys.MODEL_VARIABLES中。


估算器基本上是作为黑盒子设计的,因此没有直接的API来检索权重。即使在你定义模型时(与使用预先存在的模型相反),你也无法从估算器对象直接访问参数。

话虽如此,你仍然可以通过其他方式检索变量。如果你知道变量的名称,一个选择是使用get_operation_by_nameget_tensor_by_name从图形对象中获取它们。更实用和通用的选择是使用集合。当你调用tf.get_variable或之后,调用tf.add_to_collection,你可以将模型变量放在一个通用的集合名称下以供以后检索。如果你查看一个tf.estimator.LinearRegressor实际上是如何构建的(在这个模块中搜索函数linear_model),所有的模型变量都被添加到tf.GraphKeys.GLOBAL_VARIABLEStf.GraphKeys.MODEL_VARIABLES中。这是(我没有真正检查过)所有可用的罐头估算器共同的特点,因此通常在使用其中之一时,你应该能够简单地执行以下操作:

model_vars = tf.get_collection(tf.GraphKeys.MODEL_VARIABLES)

在这种情况下,最好使用tf.GraphKeys.MODEL_VARIABLES而不是tf.GraphKeys.GLOBAL_VARIABLES,因为后者具有更广泛的用途,很可能还包含其他无关的变量。

2
我的tf.GraphKeys.MODEL_VARIABLES是空的。我正在使用以下代码:print([(v, linear_regressor.get_variable_value(v)) for v in linear_regressor.get_variable_names()]) - Jason Ching
@JasonChing 谢谢,我已经更新了答案(或者你可以自己发布另一个答案,我会点赞并引用它)。显然他们在答案发布后做了一些更改。 - jdehesa

0

试试这个:

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()))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接