标签: tensorflow-estimator

如何控制张量流量估算器保存的检查点数量?

我注意到新的Estimator API会在训练期间自动保存检查点,并在训练中断时自动从上一个检查点重新启动.不幸的是,它似乎只保留了最后5个检查点.

您知道如何控制培训期间保留的检查点数量吗?

tensorflow tensorflow-estimator

3
推荐指数
1
解决办法
964
查看次数

将估算器转换为TPUEstimator

是否可以在不花费大量精力重写其功能的情况下将TensorFlow 转换EstimatorTPUEstimatorins?我有一个Estimator格式良好的模型,可以在CPU上很好地工作,但是我不知道一种TPUEstimator无需重写model_fnand 的便捷方法input_fn

这需要手动进行大量工作的原因是,我正在使用Keras创建模型,然后使用以下帮助函数创建了Estimator

   my_keras_model.compile(
                optimizer=tf.keras.optimizers.SGD(lr=0.0001, momentum=0.9),
                loss='categorical_crossentropy',
                metric='accuracy')
   estimator = tf.keras.estimator.model_to_estimator(keras_model=my_keras_model)
Run Code Online (Sandbox Code Playgroud)

如果我可以做类似的事情estimator.to_TPU_estimator()或那样的事情,那就太好了–也许有人知道解决方案?

python machine-learning keras tensorflow tensorflow-estimator

3
推荐指数
1
解决办法
1334
查看次数

如何在Estimator API中初始化嵌入层

我试图在tensorflow模型中使用现有的嵌入,嵌入的大小大于2Gb,这使得我最初的尝试不成功:

embedding_var = tf.get_variable(
        "embeddings", 
        shape=GLOVE_MATRIX.shape, 
        initializer=tf.constant_initializer(np.array(GLOVE_MATRIX))
)
Run Code Online (Sandbox Code Playgroud)

这给了我这个错误:

 Cannot create a tensor proto whose content is larger than 2GB.
Run Code Online (Sandbox Code Playgroud)

我正在使用基于Estimator API的AWS SageMaker,并且会话中实际运行的图形发生在场景后面,因此我不确定如何初始化一些占位符以进行嵌入.如果有人能够在EstimatorAPI方面分享如何进行这种初始化的方式会很有帮助.

tensorflow tensorflow-estimator

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

estimator.predict引发“ ValueError:不支持任何值”

所以我基本上从适用于此模型的tensorflow教程中复制了代码:

https://gormanalysis.com/wp-content/uploads/2017/11/intro-to-nnets_sketch2-3.png

它试图对神经网络建模以识别“楼梯”形状,如下所示:


(来源:gormanalysis.com

import numpy as np
import tensorflow as tf
import _pickle as cPickle

with open("var_x.txt", "rb") as fp:   # Unpickling
    var_x = cPickle.load(fp)

with open("var_y.txt", "rb") as fp:   # Unpickling
    var_y = cPickle.load(fp)

# 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", [4], dtype=tf.float64)
  b = tf.get_variable("b", [1], dtype=tf.float64)
  y = tf.sigmoid( W*features['x'] + b)
  # Loss sub-graph
  loss …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-estimator

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

Tensorflow错误:不支持可调用

我按照教程https://www.tensorflow.org/tutorials/layers进行操作,我想用它来使用自己的数据集。

def train_input_fn_custom(filenames_array, labels_array, batch_size):
    # Reads an image from a file, decodes it into a dense tensor, and resizes it to a fixed shape.
    def _parse_function(filename, label):
        image_string = tf.read_file(filename)
        image_decoded = tf.image.decode_png(image_string, channels=1)
        image_resized = tf.image.resize_images(image_decoded, [40, 40])
        return image_resized, label

    filenames = tf.constant(filenames_array)
    labels = tf.constant(labels_array)

    dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
    dataset = dataset.map(_parse_function)
    dataset = dataset.shuffle(1000).repeat().batch(batch_size)

    return dataset.make_one_shot_iterator().get_next()


def main(self):
    tf.logging.set_verbosity(tf.logging.INFO)

    # Get data
    filenames_train = ['blackcorner-data/1.png', 'blackcorner-data/2.png']
    labels_train = [0, 1]

    # Create the …
Run Code Online (Sandbox Code Playgroud)

python python-3.x tensorflow tensorflow-datasets tensorflow-estimator

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

张量转换函数 numpy() 在 tf.estimator 模型函数中不起作用

我已经在 tensorflow v2.0 和 v1.12.0(带有tf.enable_eager_execution())上尝试过这个。显然,如果我numpy()在我的main()函数中使用下面显示的代码片段进行调用,它就可以完美运行。但是,如果我在我的 estimator 模型函数 ie 中使用它,model_fn(features, labels, mode, params)那么它会抱怨'Tensor' object has no attribute 'numpy'.

ndarray = np.ones([3, 3])
tensor = tf.multiply(ndarray, 42)
print(tensor)
print(tensor.numpy())
Run Code Online (Sandbox Code Playgroud)

有没有其他人遇到过类似的问题?对于 tf.estimator 来说似乎是个大问题,不是吗?

tensorflow tensorflow-estimator tensorflow2.0

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

使用Estimators API结合tf.data.Dataset时如何加快批量准备

我想加快我的训练程序,使用带有input_fn编写的Estimator API tf.data.Dataset.

我的实现需要2秒钟来准备一批数据,然后在GPU上运行训练1秒,然后重新开始准备批处理.这实在是效率低下.

我正在寻找一种方法来异步准备批次并将它们上传到GPU以加速培训.或者替代地用于在调用之间缓存数据集的方法input_fn(由于dataset.cache()必须在每个input_fn调用上重新创建数据集,因此似乎不是一个好的选择).

这是我的代码的简化版本:

def input_fn(filenames, labels, epochs):
  dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
  dataset = dataset.map(_read_wav, num_parallel_calls=num_map_threads)
  if shuffle:
     dataset = dataset.shuffle(buffer_size=len(labels))
  dataset = dataset.map(_post_process,  num_parallel_calls=num_map_threads)
  dataset = dataset.map(lambda wav, label: ({'wav': wav}, label))
  dataset = dataset.batch(128)
  dataset = dataset.repeat(epochs) # to iterate over the training set forever
  iterator = dataset.dataset.make_one_shot_iterator()
  features, labels = iterator.get_next()
  return features, labels

train_input_fn = lambda : input_fn(train_files, train_labels, None)
eval_input_fn = lambda : input_fn(eval_files, eval_labels, 1)

train_spec = …
Run Code Online (Sandbox Code Playgroud)

tensorflow tensorflow-datasets tensorflow-estimator

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

tf.data.Dataset是否支持生成字典结构?

以下是[ https://www.tensorflow.org/programmers_guide/datasets]中的一段代码。在此示例中,该map函数是用户定义的函数,用于读取数据。并且在map函数中,我们需要将输出类型设置为[tf.uint8, label.dtype]

import cv2

# Use a custom OpenCV function to read the image, instead of the standard
# TensorFlow `tf.read_file()` operation.
def _read_py_function(filename, label):
  image_decoded = cv2.imread(image_string, cv2.IMREAD_GRAYSCALE)
  return image_decoded, label

# Use standard TensorFlow operations to resize the image to a fixed shape.
def _resize_function(image_decoded, label):
  image_decoded.set_shape([None, None, None])
  image_resized = tf.image.resize_images(image_decoded, [28, 28])
  return image_resized, label

  filenames = ["/var/data/image1.jpg", "/var/data/image2.jpg", ...]
  labels = [0, 37, 29, 1, ...]

dataset …
Run Code Online (Sandbox Code Playgroud)

tensorflow tensorflow-datasets tensorflow-estimator

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

如何在'input_fn'中使用tensorflow的迭代器'make_initializable_iterator'?

我想用tf.estimator.Estimator训练我的模式并通过Dataset API加载我的数据.因为我的数据,例如'mnist',是一个数组(张量),所以我尝试用'tf.data加载它. Dataset.from_tensor_slices'.But我不如何将"input_fn"内初始化"make_initializable_iterator".

如果我可以使用'make_one_shot_iterator'成功训练,但在训练前它会加载缓慢.而" TensorFlow中的高级API "是'input_fn'中'make_initializable_iterator'的一个很好的例子,但它需要从'input_fn'向其他函数返回'iterator_initializer_hook'.我想知道还有其他更好或更优雅的方式吗?

    def input_fn():

    mnist_data = input_data.read_data_sets('mnist_data', one_hot=False)
    images = mnist_data.train.images.reshape([-1, 28, 28, 1])
    labels = np.asarray(mnist_data.train.labels, dtype=np.int64)

    # Build dataset iterator
    dataset = tf.data.Dataset.from_tensor_slices((images, labels))
    dataset = dataset.repeat(None)  # Infinite iterations
    dataset = dataset.shuffle(buffer_size=10000)
    dataset = dataset.batch(100)
    iterator = dataset.make_one_shot_iterator()
    next_example = iterator.get_next()
    # Set runhook to initialize iterator

    return next_example
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-datasets tensorflow-estimator

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

将tf.set_random_seed与tf.estimator.Estimator一起使用

我正在使用tf.estimator.Estimator来管理培训和测试我的部分代码。我正在调整一些超参数,因此我需要确保使用相同的随机种子初始化权重。无论如何,对于tf.estimator创建的会话,set_random_seed是否存在?

tensorflow tensorflow-datasets tensorflow-estimator

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

tf.estimator.Estimator.evaluate()是否始终在一个GPU上运行吗?

我的印象中,调用evaluate()一个tf.estimator.Estimator实例时运行在多GPU模式,即使分配策略MirroredStrategy,配置为使用至少2个GPU。

这是表明此行为的示例脚本:https : //gist.github.com/patzm/b69fcdf33fc9062683d749d0ea936b5e

这是nvidia-smi显示此行为的屏幕截图: nvidia-smi的示例屏幕截图

如果evaluate()应该在多个GPU上运行(如上所述),请在回答中突出显示我的错误。

python tensorflow tensorflow-estimator

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

Tensorflow Estimator.predict() 失败

我正在重新创建 DnCNN,即高斯降噪器,它使用一系列卷积层进行图像到图像的预测。它训练得非常好,但是当我尝试执行列表(model.predict(..))时,出现错误:

标签不能为 none

我实际上将我的 EstimatorSpec 的所有规范参数明确地放在那里,因为它们是根据调用 Estimator 的方法(train/eval/predict)懒惰地评估的。

def DnCNN_model_fn (features, labels, mode):
   # some convolutinons here
   return tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=conv_last + input_layer,
        loss=tf.losses.mean_squared_error(
            labels=labels, 
            predictions=conv_last + input_layer),
        train_op=tf.train.AdamOptimizer(learning_rate=0.001, epsilon=1e-08).minimize(
            loss=tf.losses.mean_squared_error(
                labels=labels,
                predictions=conv_last + input_layer),
            global_step=tf.train.get_global_step()),
        eval_metric_ops={
            "accuracy": tf.metrics.mean_absolute_error(
                labels=labels,
                predictions=conv_last + input_layer)}
      )
Run Code Online (Sandbox Code Playgroud)

将其放入估计器中:

d = datetime.datetime.now()

DnCNN = tf.estimator.Estimator(
    model_fn=DnCNN_model_fn,
    model_dir=root + 'model/' +
              "DnCNN_{}_{}_{}_{}".format(d.month, d.day, d.hour, d.minute),
    config=tf.estimator.RunConfig(save_summary_steps=2,
                                  log_step_count_steps=10)
)
Run Code Online (Sandbox Code Playgroud)

训练模型后,我进行如下预测:

test_input_fn = tf.estimator.inputs.numpy_input_fn(
    x= test_data[0:2,:,:,:],
    y= None,
    batch_size=1,
    num_epochs=1,
    shuffle=False)

predicted = DnCNN.predict(input_fn=test_input_fn) 
list(predicted) # …
Run Code Online (Sandbox Code Playgroud)

predict tensorflow-estimator

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