python - 获取 Tensorflow 中线性回归的系数

标签 python machine-learning tensorflow

我在 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)

最佳答案

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


Estimators 被设计成基本上作为一个黑盒子工作,所以没有直接的 API 来检索权重。即使在您的情况下,您是定义模型的人(而不是使用预先存在的模型),您也无法直接访问估算器对象中的参数。

也就是说,您仍然可以通过其他方式取回变量。如果您知道变量的名称,一种选择是使用 get_operation_by_nameget_tensor_by_name 从图形对象中简单地获取它们。一个更实用和通用的选择是使用集合。无论是在您调用 tf.get_variable 时还是之后调用 tf.add_to_collection ,您都可以将模型变量放在一个公共(public)集合名称下以供以后检索。如果您查看 tf.estimator.LinearRegressor 的实际构建方式(在 this module 中搜索函数 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,后者具有更通用的用途并且可能包含其他不相关的变量。

关于python - 获取 Tensorflow 中线性回归的系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45959112/

相关文章:

python - 如何从 scikit-learn DecisionTreeClassifier 获取信息增益?

java - 将 Tensorflow 添加到 Java Project Netbeans

python - '无法计算 Pack,因为输入 #1(从零开始)预计是浮点张量,但实际上是 int32 张量 [Op :Pack] name: packed'. tf.squeeze 错误

python - 将所有并排单词成对拆分字符串单词

python - 堆栈/取消堆栈时如何不丢失 NaN 行?

python - scikit learn中的GridSearchCV如何选择k折的最佳参数

python - TensorFlow 2.0 : Cant run minimal TF Tutorial: TypeError: Can not convert a int64 into a Tensor or Operation

docker - Tensor Flow服务docker无效字段

python - 如何查找记录字段在多行中的最大出现次数?

python - 在 csv 文件中使用 python 格式化从 twitter api 返回的数据?