【问题标题】:How to suppress Keras logs in Python如何在 Python 中抑制 Keras 日志
【发布时间】:2018-08-20 23:45:08
【问题描述】:

我正在编写一个运行 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。为什么它仍然输出某种类型的警告?

【问题讨论】:

    标签: python logging keras stdout


    【解决方案1】:

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

    python -W ignore script.py
    

    或使用

    import warnings
    warnings.filterwarnings("ignore")
    

    根据this SO 帖子。第二种方法的更多信息可以在官方pythondocumentation找到。

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

    def fxn():
        warnings.warn("deprecated", DeprecationWarning)
    
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        # the warning will be ignored
        fxn()
    

    【讨论】:

    • 这不会关闭我想要记录的所有其他内容的警告吗?
    • @ddd 是的,不知何故。因此,如果您使用第三种方法,则 with 块内的所有警告都将被忽略。这意味着,您可以将此块包裹在生成警告的keras 代码周围。那么只有这些会被忽略。
    • 我明白你的意思。然而,keras 在导入时开始打印这些东西,而不是在调用某些函数时。这就是为什么这些用户警告会在应用程序刚启动时打印出来。
    • 这是不正确的,因为您在上面发布的警告仅在您调用其中一个函数时才会生成。但即使是这种情况,为什么不将导入包装在这样的块中呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2023-03-27
    相关资源
    最近更新 更多