首页 > 解决方案 > 如何在 Python 中抑制 Keras 日志

问题描述

我正在编写一个运行 Tensorflow 模型进行分类的 Python 应用程序。为了简单起见,使用库Keras。这是我的日志记录配置:

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
handler = RotatingFileHandler(LOG_DIR + '/' + LOG_FILE_NAME, maxBytes=LOG_FILE_MAX_BYTES,backupCount=LOG_FILE_BACKUP_COUNT)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger = logging.getLogger('')
logger.addHandler(handler)
logging.getLogger('boto').setLevel(logging.WARNING)
logging.getLogger('keras').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)

尽管我将 keras 的日志记录级别设置为critical,但它仍然会在开始时向 STDOUT 打印出某种警告:

UserWarning: Update your `InputLayer` call to the Keras 2 API: `InputLayer(batch_input_shape=[None, 64,..., sparse=False, name="input_1", dtype="float32")`
  return cls(**config)
UserWarning: Update your `Conv2D` call to the Keras 2 API: `Conv2D(trainable=True, name="convolution2d_1", activity_regularizer=None, activation="relu", kernel_size=(3, 3), filters=64, strides=[1, 1], padding="same", data_format="channels_last", kernel_initializer="glorot_uniform", kernel_regularizer=None, bias_regularizer=None, kernel_constraint=None, bias_constraint=None, use_bias=True)`
  return cls(**config)
UserWarning: Update your `MaxPooling2D` call to the Keras 2 API: `MaxPooling2D(strides=[2, 2], trainable=True, name="maxpooling2d_1", pool_size=[2, 2], padding="valid", data_format="channels_last")`
  return cls(**config)

为什么此输出未记录到日志文件中?我是否需要为keras模块创建一个处理程序并指定与应用程序的其余部分相同的日志文件?CRITICAL高于Warning。为什么它仍然输出某种类型的警告?

标签: pythonloggingkerasstdout

解决方案


您可以简单地关闭所有python警告,方法是使用

python -W ignore script.py

或使用

import warnings
warnings.filterwarnings("ignore")

根据this SO post。python 您可以在官方文档中找到有关第二种方法的更多信息。

第三种方法是使用上述模块并使用 `catch_warnings 上下文管理器

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    # the warning will be ignored
    fxn()

推荐阅读