标签: tensorflow-estimator

在Tensorflow中使用`tf.estimator.Estimator`保存的模型进行预测

tf.estimator.Estimator用来训练模型:

def model_fn(features, labels, mode, params, config):

    input_image = features["input_image"]

    eval_metric_ops = {}
    predictions = {}

    # Create model
    with tf.name_scope('Model'):

        W = tf.Variable(tf.zeros([784, 10]), name="W")
        b = tf.Variable(tf.zeros([10]), name="b")
        logits = tf.nn.softmax(tf.matmul(input_image, W, name="MATMUL") + b, name="logits")

    loss = None
    train_op = None

    if mode != tf.estimator.ModeKeys.PREDICT:
        loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits))
        train_op = tf.contrib.layers.optimize_loss(loss=loss,
                                                       global_step=tf.contrib.framework.get_global_step(),
                                                       learning_rate=params["learning_rate"],
                                                       optimizer=params["optimizer"])
    # Add prediction
    classes = tf.as_string(tf.argmax(input=logits, axis=1, name="class"))
    with tf.name_scope('Predictions'):
        predictions["logits"] = logits
        predictions["classes"] = classes

    export_outputs = {"classes": tf.estimator.export.ClassificationOutput(classes=classes)} …
Run Code Online (Sandbox Code Playgroud)

tensorflow tensorflow-estimator

10
推荐指数
1
解决办法
7807
查看次数

如何在tf.estimator的input_fn中使用tf.data的可初始化迭代器?

我想管理我的培训tf.estimator.Estimator但是在tf.dataAPI 旁边使用它有些麻烦.

我有这样的事情:

def model_fn(features, labels, params, mode):
  # Defines model's ops.
  # Initializes with tf.train.Scaffold.
  # Returns an tf.estimator.EstimatorSpec.

def input_fn():
  dataset = tf.data.TextLineDataset("test.txt")
  # map, shuffle, padded_batch, etc.

  iterator = dataset.make_initializable_iterator()

  return iterator.get_next()

estimator = tf.estimator.Estimator(model_fn)
estimator.train(input_fn)
Run Code Online (Sandbox Code Playgroud)

因为我不能使用一个make_one_shot_iterator用于我的用例,我的问题是input_fn包含一个应该在其中初始化的迭代器model_fn(这里,我tf.train.Scaffold用来初始化本地操作).

此外,我明白我们不能只使用input_fn = iterator.get_next其他ops将不会添加到同一图表.

初始化迭代器的推荐方法是什么?

python tensorflow tensorflow-datasets tensorflow-estimator

10
推荐指数
1
解决办法
4136
查看次数

训练tf.estimator时记录准确度指标

在培训预先预测的估算器时,打印精度指标以及丢失的最简单方法是什么?

大多数教程和文档似乎都解决了当您创建自定义估算器时的问题 - 如果打算使用其中一个可用的估算器,这似乎有点过头了.

tf.contrib.learn有一些(现已弃用)Monitor钩子.TF现在建议使用钩子API,但看起来它实际上没有任何可以利用标签和预测来生成准确度数字的东西.

python tensorflow tensorboard tensorflow-estimator

10
推荐指数
1
解决办法
4227
查看次数

Tensorflow==2.0.0a0 - AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'

I'm using Tensorflow==2.0.0a0 and want to run the following script:

import tensorflow as tf
import tensorboard
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import tensorflow_probability as tfp
from tensorflow_model_optimization.sparsity import keras as sparsity
from tensorflow import keras

tfd = tfp.distributions

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    model = tf.keras.Sequential([
      tf.keras.layers.Dense(1,kernel_initializer='glorot_uniform'),
      tfp.layers.DistributionLambda(lambda t: tfd.Normal(loc=t, scale=1))
    ])
Run Code Online (Sandbox Code Playgroud)

All my older notebooks work with TF 1.13. However, I want to develop a notebook where I use …

python tensorflow tensorflow-estimator tf.keras

10
推荐指数
1
解决办法
2万
查看次数

从 tensorflow 2.0 中保存的模型运行预测

我有一个保存的模型(一个目录 model.pd和 变量)并希望在 Pandas 数据框上运行预测。

我尝试了几种方法都没有成功:

尝试 1:从保存的模型中恢复估算器

estimator = tf.estimator.LinearClassifier(
    feature_columns=create_feature_cols(),
    model_dir=path,
    warm_start_from=path)
Run Code Online (Sandbox Code Playgroud)

其中 path 是具有model.pd和 variables 文件夹的目录。我有一个错误

ValueError: Tensor linear/linear_model/dummy_feature1/weights is not found in 
gs://bucket/Trainer/output/2013/20191008T170504.583379-63adee0eaee0/serving_model_dir/export/1570554483/variables/variables 
checkpoint {'linear/linear_model/dummy_feature1/weights': [1, 1], 'linear/linear_model/dummy_feature2/weights': [1, 1]
}
Run Code Online (Sandbox Code Playgroud)

尝试 2:通过运行直接从保存的模型运行预测

imported = tf.saved_model.load(path)  # path is the directory that has a `model.pd` and variables folder
imported.signatures["predict"](example)
Run Code Online (Sandbox Code Playgroud)

但尚未成功传递参数 - 看起来该函数正在寻找 atf.example并且我不确定如何将数据框转换为tf.example. 我的转换尝试如下,但出现 df[f] 不是张量的错误:

for f in features:
    example.features.feature[f].float_list.value.extend(df[f])
Run Code Online (Sandbox Code Playgroud)

我在 StackOverflow 上看到过解决方案,但它们都是 tensorflow 1.14。如果有人可以帮助使用 tensorflow 2.0,将不胜感激。

tensorflow tensorflow-estimator

10
推荐指数
1
解决办法
795
查看次数

不能使用估算器+数据集并训练不到一个纪元

TensorFlow 1.4将TF数据集移动到core(tf.data.Dataset),doc/tutorial建议tf.estimator用于训练模型.

但是,正如本页末尾所建议的那样,必须在input_fn函数内实例化数据集对象及其迭代器.这意味着每次调用都将重新开始数据集的迭代estimator.train(input_fn, steps).因此,调用步骤<在纪元中的样本数量,将导致在数据集的子集上训练模型.

因此我的问题.是否可以使用Estimator + Dataset实现类似的功能:

for i in range(num_epochs):
    # Train for some steps
    estimator.train(input_fn=train_input_fn, steps=valid_freq)

    validation_iterator.
    # Evaluate on the validation set (steps=None, we evaluate on the full validation set)
    estimator.evaluate(input_fn=valid_input_fn)
Run Code Online (Sandbox Code Playgroud)

没有在每次调用时从头开始训练样本迭代estimator.train(input_fn=train_input_fn, steps=valid_freq)

例如,与此处不同,实例化数据集及其迭代器input_fn?我尝试过,但它不工作,因为那么输入(从数据集迭代器)和模型(从估计model_fn)是不一样的图的一部分.

谢谢

相关的GitHub问题

tensorflow tensorflow-datasets tensorflow-estimator

9
推荐指数
1
解决办法
571
查看次数

当Json请求包含"_bytes"或"b64"时,google cloud ml-engine会做什么?

谷歌云文档(请参阅预测输入中的二进制数据)指出:

必须将编码的字符串格式化为JSON对象,并使用名为b64的单个键.以下Python示例使用base64库对原始JPEG数据的缓冲区进行编码以生成实例:

{"image_bytes":{"b64": base64.b64encode(jpeg_data)}}
Run Code Online (Sandbox Code Playgroud)

在TensorFlow模型代码中,您必须为输入和输出张量命名别名,以便它们以'_bytes'结尾.

我想了解更多有关此过程如何在Google云端运行的信息.

  • ml-engine是否会自动将"b64"字符串之后的任何内容解码为字节数据?

  • 当请求具有此嵌套结构时,它是否仅将"b64"部分传递给服务输入函数并删除"image_bytes"键?

  • 每个请求是单独传递给服务输入函数还是已经批处理?

  • 我们是否在服务输入函数返回的ServingInputReceiver中定义输入输出别名?

我发现无法创建服务输入函数,该函数使用此嵌套结构来定义要素占位符.我只在我的中使用"b64"而且我不确定gcloud ml-engine在接收请求时会做什么.

另外,当在本地使用预测时gcloud ml-engine local predict,发送具有嵌套结构的请求失败,(意外的密钥image_bytes,因为它没有在服务输入函数中定义).但是在预测使用时gcloud ml-engine predict,即使服务输入函数不包含对"image_bytes"的引用,使用嵌套结构发送请求也能正常工作.当忽略"image_bytes"并传入"b64"时,gcloud预测也有效.

服务输入功能的示例

def serving_input_fn():
    feature_placeholders = {'b64': tf.placeholder(dtype=tf.string,
                                                  shape=[None],
                                                  name='source')}
    single_image = tf.decode_raw(feature_placeholders['b64'], tf.float32)
    inputs = {'image': single_image}
    return tf.estimator.export.ServingInputReceiver(inputs, feature_placeholders)
Run Code Online (Sandbox Code Playgroud)

我使用图像给出了示例,但我假设同样适用于作为字节和base64编码发送的所有类型的数据.

有很多stackoverflow问题,其中包含对包含"_bytes"信息片段的需求的引用,但我觉得如果有人可以详细解释一下这些内容会有什么用,那么我就不会如此受欢迎格式化请求时错过.

Stackoverflow关于此主题的问题

gcloud tensorflow-serving google-cloud-ml tensorflow-estimator

9
推荐指数
1
解决办法
943
查看次数

Tensorflow Estimator - warm_start_from和model_dir

当使用tf.estimatorwith warm_start_from model_dir,并且warm_start_from目录和model_dir目录都包含有效检查点时,哪个检查点将实际恢复?

为了给出一些上下文,我的估算器代码看起来像

est = tf.estimator.Estimator(
    model_fn=model_fn,
    model_dir=model_dir,
    warm_start_from=warm_start_dir)

for epoch in range(num_epochs):
    est.train(input_fn=train_input_fn)
    est.evaluate(input_fn=eval_input_fn)
Run Code Online (Sandbox Code Playgroud)

(输入函数使用一次迭代器.)

因此在第一次迭代期间,当model_dir空为空时,我希望加载热启动检查点,但在下一个时期,我希望从上一次迭代中model_dir加入中间微调检查点.但至少从日志中看,它看起来warm_start_dir仍在被加载.

我可能会覆盖我的下一次迭代的估算器,但我想知道它是否应该在估算器中构建一些如何.

tensorflow tensorflow-estimator

9
推荐指数
1
解决办法
2505
查看次数

MirroredStrategy 不使用 GPU

我想在我的多 GPU 系统上使用 tf.contrib.distribute.MirroredStrategy() 但它不使用 GPU 进行训练(请参阅下面的输出)。我也在运行 tensorflow-gpu 1.12。

我确实尝试在 MirroredStrategy 中直接指定 GPU,但出现了同样的问题。

model = models.Model(inputs=input, outputs=y_output)
optimizer = tf.train.AdamOptimizer(LEARNING_RATE)
model.compile(loss=lossFunc, optimizer=optimizer)

NUM_GPUS = 2
strategy = tf.contrib.distribute.MirroredStrategy(num_gpus=NUM_GPUS)
config = tf.estimator.RunConfig(train_distribute=strategy)
estimator = tf.keras.estimator.model_to_estimator(model,
                                              config=config)
Run Code Online (Sandbox Code Playgroud)

这些是我得到的结果:

INFO:tensorflow:Device is available but not used by distribute strategy: /device:CPU:0
INFO:tensorflow:Device is available but not used by distribute strategy: /device:GPU:0
INFO:tensorflow:Device is available but not used by distribute strategy: /device:GPU:1
WARNING:tensorflow:Not all devices in DistributionStrategy are visible to TensorFlow session.
Run Code Online (Sandbox Code Playgroud)

预期的结果显然是在多 GPU 系统上运行训练。这些是已知问题吗?

tensorflow tensorflow-estimator

9
推荐指数
1
解决办法
5632
查看次数

如何使用自定义tf.Estimator在Tensorboard事件文件中仅创建图的一个副本?

我正在使用自定义tf.Estimator对象来训练神经网络。问题在于培训后事件文件的大小-太大了。我已经通过使用解决了将一部分数据集保存为常量的问题tf.Dataset.from_generator()。但是,尺寸仍然很大,开始时tensorboard我收到消息

W0225 10:38:07.443567 140693578311424 tf_logging.py:120] Found more than one metagraph event per run. Overwriting the metagraph with the newest event.

因此,我想我正在此事件文件中创建并保存许多不同的图形。是否可以关闭此保存或仅保存第一份副本?

众所周知,我找到了删除所有默认日志的唯一方法,方法是删除带有

list(map(os.remove, glob.glob(os.path.join(runtime_params['model_dir'], 'events.out.tfevents*'))))
Run Code Online (Sandbox Code Playgroud)

但是,这对我来说是一个不好的解决方案,因为我希望保留摘要,最好保留图表的一个副本。

从文档中,我可以看到

估算器自动将以下内容写入磁盘:

  • 检查点,它们是训练期间创建的模型的版本。
  • 事件文件,其中包含TensorBoard用于创建可视化文件的信息。是否可以关闭事件文件的写操作

python tensorflow tensorboard tensorflow-datasets tensorflow-estimator

9
推荐指数
1
解决办法
392
查看次数