简体   繁体   English

使用字典和 for 循环调用 tf2 模型时出现意外警告

[英]unexpected warning when calling tf2 models using dictionary and for loop

In Tensorflow V2, when I call tf models inside a dictionary, it yields a warning.在 Tensorflow V2 中,当我在字典中调用 tf 模型时,会产生警告。 This is the dictionary of models:这是模型字典:

 import tensorflow as tf
 import numpy as np

width = 128
height = 128
nchannels = 10
nclasses = 5

models = {   
    'MobileNetV2': tf.keras.applications.MobileNetV2,                                                      
    'DenseNet121': tf.keras.applications.DenseNet121,
    'DenseNet169': tf.keras.applications.DenseNet169,
    'DenseNet201': tf.keras.applications.DenseNet201,
    'InceptionResNetV2': tf.keras.applications.InceptionResNetV2,
    'InceptionV3': tf.keras.applications.InceptionV3,
    'MobileNet': tf.keras.applications.MobileNet,
    'Xception': tf.keras.applications.Xception,
    'NASNetLarge': tf.keras.applications.NASNetLarge
    }


for name, arch in models.items():

   inp = np.random.rand(1, width, height, nchannels)
   print(inp.shape) 

   model_arch = arch(input_shape=[width, height, nchannels],
                                                   include_top=False,
                                                   weights=None)
  
   model_classification = tf.keras.layers.Dense(nclasses)

   model = tf.keras.Sequential([
    model_arch,
    tf.keras.layers.Flatten(),
    model_classification])

   res = model.predict(inp)
   print(name, res.shape)

And this is the warning:这是警告:

WARNING:tensorflow:7 out of the last 7 calls to <function 
Model.make_predict_function.<locals>.predict_function at 0x0000019FA812C790> 
triggered tf.function retracing. Tracing is expensive and the excessive number 
of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) 
passing tensors with different shapes, (3) passing Python objects instead of 
tensors. For (1), please define your @tf.function outside of the loop. For (2), 
@tf.function has experimental_relax_shapes=True option that relaxes argument 
shapes that can avoid unnecessary retracing. For (3), please refer to 
https://www.tensorflow.org/tutorials/customization
/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs
/python/tf/function for  more details.

How can I avoid the warning?我怎样才能避免警告? What is the proper way to train multiple tf models on the same dataset?在同一数据集上训练多个 tf 模型的正确方法是什么?

The issue comes from multiple model initializations at once inside the models dictionary definition.该问题来自models字典定义中的多个 model 初始化。 Since you are going to train one model at a time, it is better to defer the model initialization to the inner loop over the models.由于您要一次训练一个 model,因此最好将 model 初始化推迟到模型的内循环。 Adding one dense layer for classification, your model definition could look like this:添加一个密集层进行分类,您的 model 定义可能如下所示:

N_CLASSES = 48  # Define your own, based on your dataset!

models = {
    'VGG16': tf.keras.applications.VGG16,
             ....
    'VGG19': tf.keras.applications.VGG19  
    }

for name, arch in models.items():
   # You may have to define a custom input size, according yo tour dataset.
   #  Use  arch(input_size=(WIDTH, HEIGHT, N_CHANNELS)) for that.
   model_arch = arch()
   model_classification = tf.keras.layers.Dense(N_CLASSES)
   
   model = tf.keras.Sequential([
        model_arch,
        tf.keras.layers.Flatten(),
        model_classification
   ])
        
   # Training loop, including the data pipeline
   # Stop training, measure accuracy and store model.
   #   -> Next iteration will erase whatever is not stored.

IMPORTANT!重要的! You have to go through the training loop (eg: model.fit(train_data) ) in order to avoid the warning.您必须通过训练循环 go (例如: model.fit(train_data) )以避免警告。 Otherwise Tensorflow will still warn you that you're being very inefficient when generating an entire model just to run a single prediction (what your code does).否则 Tensorflow 仍然会警告您在生成整个 model 以运行单个预测(您的代码所做的)时效率非常低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 TF2(对象检测 API)时,多个 GPU 是否允许更大的模型和批量大小? - Will multiple GPUs allow for larger models and batch sizes when using TF2 (oibject detection API)? 使用 TFRecordDataset 时如何从 TF2 图中释放 memory - How to release memory from TF2 graphs when using TFRecordDataset 在训练时确认 TF2 正在使用我的 GPU - Confirm that TF2 is using my GPU when training TF2 / Keras切片张量使用[:,:,0] - TF2 / Keras slice tensor using [:, :, 0] 使用 cx_Freeze 时出现问题:“无法导入名称 &#39;tf2&#39;” - Problem when using cx_Freeze: "cannot import name 'tf2'" 使用 TF1 读取使用 TF2 创建的 protobuf - reading a protobuf created with TF2 using TF1 使用 tf.eager 训练复杂的 nn 模型(使用 TF2 符号支持更好) - Train complicated nn models with tf.eager (better with TF2 symbolic support) 在 TF2 中使用自定义训练循环时,如何保存所有变量(不仅是净变量)以便能够恢复训练? - How to save all variables (not only net variables) to be able to resume training when using custom training loops in TF2? (tf2/tf.keras) # params 如何在一个模型包含另一个模型时减少 - (tf2/tf.keras) How could # params decreases when a model contains another model 抓取时字典循环调用同一网站 - Dictionary loop calling same website when scraping
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM