标签: tensorflow-estimator

使用带有tf.Estimator的Tensorflow分析器

我需要使用Tensorflow分析器来分析一些由于某种原因而运行缓慢的代码.不幸的是,有问题的代码使用tf.Estimator,所以我无法弄清楚如何注入运行元数据对象到会话中的run()调用,以获取信息的探查需求.

我该怎么办?

python tensorflow tensorflow-estimator

5
推荐指数
1
解决办法
2356
查看次数

使用tf.estimator的自定义指标

我想在我的估算器评估期间使用tensorflow来计算确定系数(R平方).我试图以下面的方式基于官方指标的实现松散地实现它:

def r_squared(labels, predictions, weights=None,
              metrics_collections=None,
              updates_collections=None,
              name=None):

    total_error = tf.reduce_sum(tf.square(labels - tf.reduce_mean(labels)))
    unexplained_error = tf.reduce_sum(tf.square(labels - predictions))
    r_sq = 1 - tf.div(unexplained_error, total_error)

    # update_rsq_op = ?

    if metrics_collections:
        ops.add_to_collections(metrics_collections, r_sq)

    # if updates_collections:
    #     ops.add_to_collections(updates_collections, update_rsq_op)

    return r_sq #, update_rsq_op
Run Code Online (Sandbox Code Playgroud)

然后,我将此函数用作EstimatorSpec中的度量标准:

estim_specs = tf.estimator.EstimatorSpec(
    ...
    eval_metric_ops={
        'r_squared': r_squared(labels, predictions),
        ...
    })
Run Code Online (Sandbox Code Playgroud)

但是,由于我的R平方实现没有返回update_op,因此失败了.

TypeError: Values of eval_metric_ops must be (metric_value, update_op) tuples, given: Tensor("sub_4:0", dtype=float64) for key: r_squared
Run Code Online (Sandbox Code Playgroud)

现在我想知道,update_op究竟应该做什么?我是否真的需要实现update_op,还是可以以某种方式创建某种虚拟update_op?如果有必要,我该如何实施呢?

python tensorflow tensorflow-estimator

5
推荐指数
1
解决办法
2954
查看次数

如何使用tensorflow.Estimator进行强化学习

tensorflow.Estimator似乎与监督学习有关,但即使模型或培训只需要进行小的改动,似乎很难采用其他任务.例如,在强化学习中,我需要提供一个奖励值,而这个值不属于features.

tensorflow tensorflow-estimator

5
推荐指数
1
解决办法
492
查看次数

我尝试导出tf.estimator.DNNClassifier模型时出错.我怎么能保存这个?

我创建了我的估算器:

estimator = tf.estimator.DNNClassifier(
   hidden_units=[500, 100],
   feature_columns=[embedded_text_feature_column],
   n_classes=2,
   optimizer=tf.train.AdagradOptimizer(learning_rate=0.003))
Run Code Online (Sandbox Code Playgroud)

并进行以下培训:

estimator.train(input_fn=train_input_fn, steps = 2)
Run Code Online (Sandbox Code Playgroud)

完成这两个步骤后,我想保存我的模型/估算器.我尝试了以下方法:

# NOT SURE IF THE FOLLOWING FUNCTION IS CORRECT
def serving_input_receiver_fn():
  """Build the serving inputs."""
  # The outer dimension (None) allows us to batch up inputs for
  # efficiency. However, it also means that if we want a prediction
  # for a single instance, we'll need to wrap it in an outer list.

  inputs = {"x": tf.placeholder(shape=[None, 4], dtype=tf.float32)}
  return tf.estimator.export.ServingInputReceiver(inputs, inputs)

export_dir = classifier.export_savedmodel( …
Run Code Online (Sandbox Code Playgroud)

python machine-learning python-3.x tensorflow tensorflow-estimator

5
推荐指数
0
解决办法
106
查看次数

自动将类似 Tensorboard 的损失图保存到图像文件中

我目前正在尝试使用 tensorflow 预制估计器(tf.estimator.DNNRegressor)来预测粒子的运动。

我想将平均损失图的图像(如一个张量板显示)保存到每个模型的文件夹中。来自张量板的图像

Tensorboard 非常适合在训练期间监控这一点,但我想保存图像以供将来参考(例如,直观地比较不同的方法)

是否有捷径可寻?我可以在不同时间保存评估结果并使用 matplotlib,但是我没有找到任何关于如何从 regressor.train 方法中获取损失的信息。

tensorflow tensorflow-estimator

5
推荐指数
1
解决办法
3370
查看次数

TensorFlow Serving REST API 的正确有效负载

我已将 Keras 模型转换为 Tensorflow 估计器,将 Tensorflow Transform 添加到图中,然后导出模型以供服务。

当我检查模型签名时,我可以看到以下信息:

signature_def['serving_default']:
  The given SavedModel SignatureDef contains the following input(s):
    inputs['examples'] tensor_info:
        dtype: DT_STRING
        shape: (-1)
        name: input_example_tensor:0
  The given SavedModel SignatureDef contains the following output(s):
    outputs['specialities'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 154)
        name: specialities/Softmax:0
  Method name is: tensorflow/serving/predict
Run Code Online (Sandbox Code Playgroud)

我转换了特征规范,tf.estimator.export.build_parsing_serving_input_receiver_fn因此签名中输入节点的名称是example. 我的模型中输入节点的名称是procedures.

然后我使用saved_model_cli手动测试导出的模型,一切看起来都很好(我得到了一个概率列表)

!saved_model_cli run --dir=/model_dir/1533849825 
                     --tag_set serve 
                     --signature_def serving_default  
                     --input_examples 'examples=[{"procedures": ["99214,17000,17000,13121,99203"]}]'
Run Code Online (Sandbox Code Playgroud)

现在,我将此模型加载到 TF Serving 中,模型服务器启动正常。

当我使用下面的 json 有效负载 (application/json) 请求模型预测时,我收到以下错误:

{
  "signature_name":"serving_default",
  "instances":[ …
Run Code Online (Sandbox Code Playgroud)

rest keras tensorflow tensorflow-serving tensorflow-estimator

5
推荐指数
1
解决办法
4046
查看次数

TensorFlow 1.10+自定义估算器使用train_and_evaluate提前停止

假设你正在训练的自定义tf.estimator.Estimatortf.estimator.train_and_evaluate在类似的设置使用验证数据集@ simlmx的:

classifier = tf.estimator.Estimator(
    model_fn=model_fn,
    model_dir=model_dir,
    params=params)

train_spec = tf.estimator.TrainSpec(
    input_fn = training_data_input_fn,
)

eval_spec = tf.estimator.EvalSpec(
    input_fn = validation_data_input_fn,
)

tf.estimator.train_and_evaluate(
    classifier,
    train_spec,
    eval_spec
)
Run Code Online (Sandbox Code Playgroud)

通常,当训练数据集的损失继续改善而不是验证数据集时,使用验证数据集来切断训练以防止过度拟合.

目前,tf.estimator.EvalSpec允许用户指定steps评估模型的数量(默认为100).

一个(如果可能不使用tf.contrib函数)如何指定在评估丢失n数量(n * steps)之后终止训练,其中评估损失没有改善,然后将"最佳"模型/检查点(由验证数据集确定)保存到唯一文件名(例如best_validation.checkpoint)

python tensorflow tensorflow-estimator

5
推荐指数
1
解决办法
2180
查看次数

Tensorflow estimator 多 GPU 预测

我有一个估算器,可以通过指定train_distributeeval_distribute在配置中使用多个 GPU 进行训练和评估。但predict_distributetf.estimator.RunConfig. 如何使用多个 GPU 进行预测?

multi-gpu tensorflow tensorflow-estimator

5
推荐指数
0
解决办法
418
查看次数

“完成运行local_init_op”后Tensorflow变慢

我有一个来自 github 的基于 tensorflow 的代码,它非常慢。它甚至不打印(即使在为 tf.logging 启用调试模式之后)打印以下内容后发生的事情

信息:tensorflow:完成运行local_init_op。 --> 此行代码执行后需要 20 分钟 INFO:tensorflow:prediction_loop 标记为完成

有人可以告诉在哪里查看和优化吗?
已经检查了以下事项:

  • model_fn : 这在 local_init_op 之前执行
  • 本地文件:检查点文件从本地文件系统保存和加载。所以文件传输延迟不应该是原因
  • warm_start_from:尝试过。对预测时间没有影响

估算器代码:

estimator = tf.contrib.tpu.TPUEstimator(
      use_tpu=FLAGS.use_tpu,
      model_fn=model_fn,
      config=run_config,
      warm_start_from = tf.estimator.WarmStartSettings(
            ckpt_to_initialize_from='/content/ckpt',
        ),
      train_batch_size=FLAGS.train_batch_size,
      predict_batch_size=FLAGS.predict_batch_size)
Run Code Online (Sandbox Code Playgroud)

预测代码:

results = estimator.predict(
          predict_input_fn, yield_single_examples=True, checkpoint_path='/content/ckpt/model.ckpt-10949')
Run Code Online (Sandbox Code Playgroud)

执行这段代码所用的时间:

results = list(results)
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-estimator

5
推荐指数
0
解决办法
1703
查看次数

使用 MirroredStrategy 时,tensorflow Estimator 是否为工作人员采取不同的批次?

我正在使用 GANEstimator 和 MirroredStrategy 来处理单个实例的多个 GPU。input_fn在我的情况下tf.data.Dataset有以下设置:

dataset = dataset.repeat()
dataset = dataset.shuffle(buffer_size=100)
dataset = dataset.batch(self.batch_size, drop_remainder=True)
dataset = dataset.prefetch(100)
Run Code Online (Sandbox Code Playgroud)

我问这个的原因是我是否需要dataset.shard()手动指定一些东西才能将不同的数据传递给工人?我正在挖掘EstimatorMirroredStrategy的代码,但我不清楚发生了什么。从分布式策略描述中产生了额外的混淆:

MirroredStrategy: This does in-graph replication with synchronous 
training on many GPUs on one machine. Essentially, we create copies of all
variables in the model's layers on each device. We then use all-reduce 
to combine gradients across the devices before applying them 
to the variables to keep …
Run Code Online (Sandbox Code Playgroud)

tensorflow tensorflow-datasets tensorflow-estimator

5
推荐指数
1
解决办法
1223
查看次数