2017-08-30 117 views
2

我已经在Tensorflow中做了一个简单的线性回归。我怎么知道回归的系数是什么? 我已阅读文档,但无法在任何地方找到它! (https://www.tensorflow.org/api_docs/python/tf/estimator/LinearRegressor在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) 
+0

你可以发布你的代码,以便我们看到你究竟做了什么?一般难以回答... – Umberto

+0

对不起。我正在使用https://www.tensorflow.org/get_started/get_started – japmelian

+0

中的示例,您并未使用['tf.estimator.LinearRegressor'](https://www.tensorflow.org/api_docs/python/tf/estimator/LinearRegressor),而是实现你自己的估计器,对吧? (这相当于一个线性回归器)。 – jdehesa

回答

1

估计被设计为一个黑盒子的基本工作原理,所以没有直接的API来获取权重。即使像你一样,你是定义模型的人(与使用预先存在的模型相反),你不能直接访问估计器对象中的参数。

也就是说,您仍然可以通过其他方式检索变量。如果您知道变量的名称,则可以使用get_operation_by_nameget_tensor_by_name从图形对象中简单地获取它们。一个更实用和一般的选择是使用一个集合。当您拨打tf.get_variable或之后,拨打tf.add_to_collection,您可以将模型变量置于通用集合名称下供以后检索。如果您看看tf.estimator.LinearRegressor实际上是如何构建的(在this module中搜索函数linear_model),则所有模型变量都会添加到tf.GraphKeys.GLOBAL_VARIABLEStf.GraphKeys.MODEL_VARIABLES。这是(大概是,我还没有真正选中)共同所有可用的罐头估计,所以通常使用其中的一个时,你应该能够简单地做:您在使用tf.GraphKeys.MODEL_VARIABLES

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

最好这种情况下,而不是tf.GraphKeys.GLOBAL_VARIABLES,它具有更通用的目的,并可能包含其他无关变量。