我需要使用Tensorflow分析器来分析一些由于某种原因而运行缓慢的代码.不幸的是,有问题的代码使用tf.Estimator,所以我无法弄清楚如何注入运行元数据对象到会话中的run()调用,以获取信息的探查需求.
我该怎么办?
我想在我的估算器评估期间使用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?如果有必要,我该如何实施呢?
这tensorflow.Estimator似乎与监督学习有关,但即使模型或培训只需要进行小的改动,似乎很难采用其他任务.例如,在强化学习中,我需要提供一个奖励值,而这个值不属于features.
我创建了我的估算器:
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
我已将 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
假设你正在训练的自定义tf.estimator.Estimator与tf.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)
我有一个估算器,可以通过指定train_distribute和eval_distribute在配置中使用多个 GPU 进行训练和评估。但predict_distribute在tf.estimator.RunConfig. 如何使用多个 GPU 进行预测?
我有一个来自 github 的基于 tensorflow 的代码,它非常慢。它甚至不打印(即使在为 tf.logging 启用调试模式之后)打印以下内容后发生的事情
信息:tensorflow:完成运行local_init_op。 --> 此行代码执行后需要 20 分钟 INFO:tensorflow:prediction_loop 标记为完成
有人可以告诉在哪里查看和优化吗?
已经检查了以下事项:
估算器代码:
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) 我正在使用 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()手动指定一些东西才能将不同的数据传递给工人?我正在挖掘Estimator和MirroredStrategy的代码,但我不清楚发生了什么。从分布式策略的描述中产生了额外的混淆:
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)