标签: tensorflow-estimator

Tensorflow Keras模型和Estimator之间有什么区别?

Tensorflow Keras模型和Tensorflow Estimators都能够训练神经网络模型并使用它们来预测新数据.它们都是位于低级核心TensorFlow API之上的高级API.那我什么时候应该使用另一个呢?

keras tensorflow tensorflow-estimator

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

用tf.estimator提早停止,怎么样?

tf.estimator在TensorFlow 1.4中使用tf.estimator.train_and_evaluate它很棒,但我需要提前停止.添加它的首选方法是什么?

我认为这有一些tf.train.SessionRunHook地方.我看到有一个旧的contrib包ValidationMonitor似乎提前停止了,但它似乎不再是1.4了.或者未来的首选方式是依靠tf.keras(早期停止真的很容易)而不是tf.estimator/tf.layers/tf.data,或许?

python neural-network keras tensorflow tensorflow-estimator

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

Tensorflow:logits 和标签必须具有相同的第一维

我是 tensoflow 的新手,我想用我自己的数据(40x40 的图像)调整 MNIST 教程https://www.tensorflow.org/tutorials/layers。这是我的模型函数:

def cnn_model_fn(features, labels, mode):
        # Input Layer
        input_layer = tf.reshape(features, [-1, 40, 40, 1])

        # Convolutional Layer #1
        conv1 = tf.layers.conv2d(
                inputs=input_layer,
                filters=32,
                kernel_size=[5, 5],
                #  To specify that the output tensor should have the same width and height values as the input tensor
                # value can be "same" ou "valid"
                padding="same",
                activation=tf.nn.relu)

        # Pooling Layer #1
        pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)

        # Convolutional Layer #2 and Pooling Layer #2
        conv2 …
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow tensorflow-datasets tensorflow-estimator

18
推荐指数
4
解决办法
5万
查看次数

使用`tensorflow.python.keras.estimator.model_to_estimator`将Keras模型转换为Estimator API时如何通知类权重?

我在将一个纯Keras模型转换为不平衡数据集上的TensorFlow Estimator API时遇到了一些麻烦.

使用纯Keras API时,该class_weight参数在model.fit方法中可用,但在将Keras模型转换为TensorFlow Estimator时tensorflow.python.keras.estimator.model_to_estimator,无法通知class_weights.

怎么能克服这个?

我在Ubuntu 18,Cuda 9,Cudnn 7上使用TF 1.12

纯Keras型号:

def keras_model(n_classes=None, model_dir='./tmp-model/', config=None):
    with tf.device('/gpu:0'):

        # Inputs
        inp_raw = Input(shape=(max_len,), name='word_raw')

        # raw text LSTM network
        word_raw_emb = Embedding(
            input_dim=nunique_chars_raw,
            output_dim=EMBED_SIZE,
            input_length=MAX_WORD_LENGTH,
            trainable=True,
            name='word_raw_emb')(inp_raw)

        word_raw_emb = Dropout(rate=dropout_rate)(word_raw_emb)

        word_raw_emb_lstm = Bidirectional(
            LSTM(48, return_sequences=True))(word_raw_emb)
        word_raw_emb_gru = Bidirectional(
            GRU(48, return_sequences=False))(word_raw_emb_lstm)

        word_raw_net = Dense(16, activation='relu')(word_raw_emb_gru)
        output_raw_net = Dense(n_classes, activation='softmax')(word_raw_net)

        model = Model(inputs=inp_raw, outputs=output_raw_net)
        optz = keras.optimizers.RMSprop(
            lr=0.002, rho=0.9, epsilon=None, decay=0.0)
        model.compile(loss='categorical_crossentropy',
                      optimizer=optz, …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-estimator

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

使用tf.estimator.Estimator框架转移学习

我正在尝试使用我自己的数据集和类进行在imagenet上预训练的Inception-resnet v2模型的传输学习.我的原始代码库是对tf.slim样本的修改,我找不到了,现在我正在尝试使用tf.estimator.*框架重写相同的代码.

但是,我正在运行从预训练检查点加载一些权重的问题,用其默认初始值设定项初始化剩余的层.

研究这个问题,我发现了这个GitHub问题这个问题,都提到了需要tf.train.init_from_checkpoint在我的问题中使用model_fn.我试过了,但由于两者都没有例子,我想我错了.

这是我的最小例子:

import sys
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import tensorflow as tf
import numpy as np

import inception_resnet_v2

NUM_CLASSES = 900
IMAGE_SIZE = 299

def input_fn(mode, num_classes, batch_size=1):
  # some code that loads images, reshapes them to 299x299x3 and batches them
  return tf.constant(np.zeros([batch_size, 299, 299, 3], np.float32)), tf.one_hot(tf.constant(np.zeros([batch_size], np.int32)), NUM_CLASSES)


def model_fn(images, labels, num_classes, mode):
  with tf.contrib.slim.arg_scope(inception_resnet_v2.inception_resnet_v2_arg_scope()):
    logits, end_points = …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-estimator

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

TensorFlow估算器ServingInputReceiver的功能与Receiver_tensors的比较:何时以及为什么?

在上一个问题中,serving_input_receiver_fn探讨了的目的和结构,并在回答中

def serving_input_receiver_fn():
  """For the sake of the example, let's assume your input to the network will be a 28x28 grayscale image that you'll then preprocess as needed"""
  input_images = tf.placeholder(dtype=tf.uint8,
                                         shape=[None, 28, 28, 1],
                                         name='input_images')
  # here you do all the operations you need on the images before they can be fed to the net (e.g., normalizing, reshaping, etc). Let's assume "images" is the resulting tensor.

  features = {'input_data' : images} # this …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-estimator

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

使用tf.Estimator创建的tensorflow上的图优化

背景:

我有一个基于tf.estimator.DNNClassifier的简单分类,它通过intent标签获取文本和输出概率.我能够训练将模型输出到可服务的以及使用tensorflow服务服务于服务.问题是这个可服务性太大(大约1GB),因此我想尝试一些张量流图变换来尝试减少所服务文件的大小.

问题:

我理解如何saved_model.pb使用和使用freeze_model.py来创建一个.pb可用于调用转换的新文件.这些转换的结果(.pb文件也是如此)不可用,不能与tensorflow服务一起使用.

开发者如何来自:

saved model -> graph transforms -> back to a servable
Run Code Online (Sandbox Code Playgroud)

文档表明这肯定是可能的,但从文档到关于如何做到这一点并不直观.

我试过的:

import tensorflow as tf

from tensorflow.saved_model import simple_save
from tensorflow.saved_model import signature_constants
from tensorflow.saved_model import tag_constants
from tensorflow.tools.graph_transforms import TransformGraph


with tf.Session(graph=tf.Graph()) as sess_meta:
    meta_graph_def = tf.saved_model.loader.load(
        sess_meta,
        [tag_constants.SERVING],
        "/model/path")

    graph_def = meta_graph_def.graph_def

    other_graph_def = TransformGraph(
        graph_def,
        ["Placeholder"],
        ["dnn/head/predictions/probabilities"],
        ["quantize_weights"])


    with tf.Graph().as_default(): …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-serving tensorflow-estimator

13
推荐指数
2
解决办法
727
查看次数

Tensorflow 2.0 Keras的训练速度比2.0 Estimator慢4倍

我们最近将TF 2.0切换到了Keras,但是将其与2.0上的DNNClassifier Estimator进行比较时,我们发现Keras的速度慢了大约4倍。但是我无法为自己的生活弄清楚为什么会这样。两者的其余代码都相同,使用一个input_fn()返回相同的tf.data.Dataset,并使用相同的feature_columns。几天来一直在努力解决这个问题。任何帮助将不胜感激。谢谢

估算器代码:

estimator = tf.estimator.DNNClassifier(
        feature_columns = feature_columns,
        hidden_units = [64,64],
        activation_fn = tf.nn.relu,
        optimizer = 'Adagrad',
        dropout = 0.4,
        n_classes = len(vocab),
        model_dir = model_dir,
        batch_norm = false)

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

Keras代码:

feature_layer = tf.keras.layers.DenseFeatures(feature_columns);

model = tf.keras.Sequential([
        feature_layer,
        layers.Dense(64, input_shape = (len(vocab),), activation = tf.nn.relu),
        layers.Dropout(0.4),
        layers.Dense(64, activation = tf.nn.relu),
        layers.Dropout(0.4),
        layers.Dense(len(vocab), activation = 'softmax')]);

model.compile(
        loss = 'sparse_categorical_crossentropy',
        optimizer = 'Adagrad'
        distribute = None)

model.fit(x = train_input_fn(),
          epochs = 1,
          steps_per_epoch = 400,
          shuffle = True) …
Run Code Online (Sandbox Code Playgroud)

python keras tensorflow tensorflow-estimator tensorflow2.0

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

ModuleNotFoundError:tensorflow 2.1.0 没有名为“tensorflow_core.estimator”的模块

使用 tensorflow 时,出现以下错误消息

ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.'

File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.estimator'
Run Code Online (Sandbox Code Playgroud)

已安装的 tensorflow 相关包如下所示。我需要更新估算器的版本吗?如果是这种情况,如何安装正确版本的估算器?

在此处输入图片说明

tensorflow tensorflow-estimator tensorflow2.0

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

模块“tensorflow.tools.docs.doc_controls”没有属性“inheritable_header”

今天从张量流运行估计器并出现了这个错误,知道如何解决它吗?

File "C:\Users\ASUS Laptop\anaconda3\envs\tf_gpu\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 70, in <module>
    @doc_controls.inheritable_header("""\
AttributeError: module 'tensorflow.tools.docs.doc_controls' has no attribute 'inheritable_header'
Run Code Online (Sandbox Code Playgroud)

这是在我的 estimator.py 文件中: @doc_controls.inheritable_header("""
警告:不建议在新代码中使用估算器。估算器运行 v1.Session更难以正确编写的风格代码,并且可能会出现意外行为,尤其是与 TF 结合使用时2 代码。估算器确实属于我们的 兼容性保证范围,但除了安全漏洞之外不会收到任何修复。 有关详细信息,请参阅迁移指南。""")

python machine-learning tensorflow tensorflow-estimator tensorflow2.0

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