Tensorflow 디버깅 정보 비활성화


191

정보를 디버깅한다는 것은 TensorFlow가 터미널에로드 된 라이브러리 및 Python 오류가 아닌 장치 등을 발견 한 것을 의미합니다.

I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcublas.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcudnn.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcufft.so locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcuda.so.1 locally
I tensorflow/stream_executor/dso_loader.cc:105] successfully opened CUDA library libcurand.so locally
I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties: 
name: Graphics Device
major: 5 minor: 2 memoryClockRate (GHz) 1.0885
pciBusID 0000:04:00.0
Total memory: 12.00GiB
Free memory: 11.83GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0 
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Graphics Device, pci bus id: 0000:04:00.0)
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.0KiB
...


Tensorflow는 여전히 초기 알파 코드이며 numpy 및 pandas와의 기본 호환성을 위해 버그를 해결하고 있습니다. 그래서 하나의 타격에서 이러한 경고를 노크 수행 import warnings한 후 warnings.filterwarnings('ignore')다음 tensorflow 수입을 실행하고 깨진 알파 tensorflow 코드에 의존하는 코드, 다음 경고를 통해 다시 켭니다 warnings.resetwarnings(). 현재 Tensorflow는 0.05 이상의 버전 이름을 광고해서는 안됩니다.
— Eric Leschinski

답변:


214

다음을 사용하여 모든 디버깅 로그를 비활성화 할 수 있습니다 os.environ.

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' 
import tensorflow as tf

tf 0.12 및 1.0에서 테스트

자세한 내용은

0 = all messages are logged (default behavior)
1 = INFO messages are not printed
2 = INFO and WARNING messages are not printed
3 = INFO, WARNING, and ERROR messages are not printed

작동하지만 로그 앞의 타임 스탬프를 제거합니다. 어떻게 다시 설정할 수 있습니까?
— DreamFlasher

이 수준 (0, 1, 2, 3)은 무엇을 의미합니까?
— diralik

2
수입 tensorflow 전에도 1.13 및 python3에서 작동하지 않음
— Li haonan

146

2.0 업데이트 (10/8/19) 설정 TF_CPP_MIN_LOG_LEVEL이 계속 작동하지만 (v0.12 + 업데이트에서 아래 참조) 현재 문제가 있습니다 ( 문제 # 31870 참조 ). 설정 TF_CPP_MIN_LOG_LEVEL이 작동하지 않는 경우 (다시 참조) 다음을 수행하여 로그 수준을 설정하십시오.

import tensorflow as tf
tf.get_logger().setLevel('INFO')

또한 tf.autograph.set_verbosity오토 그래프 로그 메시지의 세부 정보를 설정 하는 설명서를 참조하십시오 ( 예 :

# Can also be set using the AUTOGRAPH_VERBOSITY environment variable
tf.autograph.set_verbosity(1)

TF 2.0 이상을 통한 v0.12 + 업데이트 (5/20/17) :

TensorFlow 0.12+에서는이 문제 에 따라 환경 변수를 통해 로깅을 제어 할 수 있습니다 TF_CPP_MIN_LOG_LEVEL. 기본값은 0 (모든 로그 표시)이지만 Level열 아래에서 다음 값 중 하나로 설정할 수 있습니다 .

  Level | Level for Humans | Level Description                  
 -------|------------------|------------------------------------ 
  0     | DEBUG            | [Default] Print all messages       
  1     | INFO             | Filter out INFO messages           
  2     | WARNING          | Filter out INFO & WARNING messages 
  3     | ERROR            | Filter out all messages      

Python을 사용하는 다음 일반 OS 예제를 참조하십시오.

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
import tensorflow as tf

철저하게 tf_logging말하면, 요약 ops, tensorboard, 다양한 추정기 등에서 사용되는 Python 모듈 의 레벨을 설정하십시오 .

# append to lines above
tf.logging.set_verbosity(tf.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}

1.14의 경우 다음과 같이 v1 API 사용을 변경하지 않으면 경고가 표시됩니다.

# append to lines above
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)  # or any {DEBUG, INFO, WARN, ERROR, FATAL}


TensorFlow 또는 TF-Learn 로깅의 이전 버전 (v0.11.x 이하)의 경우 :

TensorFlow 로깅에 대한 정보는 아래 페이지를보십시오. 새 업데이트와 함께, 당신은 하나에 로깅 상세를 설정할 수있어 DEBUG, INFO, WARN, ERROR, 또는 FATAL. 예를 들면 다음과 같습니다.

tf.logging.set_verbosity(tf.logging.ERROR)

이 페이지는 TF-Learn 모델과 함께 사용할 수있는 모니터를 추가로 검토합니다. 여기에 페이지가 있습니다.

이것은 하지 않습니다 (단 TF는-알아보기)하지만, 모든 로깅을 차단합니다. 두 가지 해결책이 있습니다. 하나는 '기술적으로 올바른'솔루션 (Linux)이고 다른 하나는 TensorFlow 재 구축과 관련이 있습니다.

script -c 'python [FILENAME].py' | grep -v 'I tensorflow/'

다른 방법 은 소스 수정 및 TensorFlow 재 구축과 관련된 이 답변 을 참조하십시오 .


"I tensorflow"메시지는 성가시다. tf는 재 빌딩 대신 api를 사용하여 메시지를 침묵시키는 방법을 제공해야한다
— 물리학 자

2
이것은 또한 커맨드 라인에서 수행 할 수 있습니다 :export TF_CPP_MIN_LOG_LEVEL="3" && python your_code.py
— Andrew Hundt

또한으로 실행할 수 있습니다TF_CPP_MIN_LOG_LEVEL="3" python your_code.py
— craymichael

tensorflow 경고 / 오류를 오류로 전환하는 방법이 있습니까?
— CMCDragonkai

1
tf.logging.set_verbosity (tf.logging.ERROR) # 또는 {DEBUG, INFO, WARN, ERROR, FATAL} 또는 나를 위해 일했습니다
— Amir Md Amiruzzaman

16

나는 (on tensorflow-0.10.0rc0) 이 문제를 겪었 지만 제안 된 답변을 통해 과도한 코 테스트 로깅 문제를 해결할 수는 없습니다.

나는 tensorflow 로거로 직접 조사 하여이 문제를 해결했습니다. 가장 정확한 수정은 아니지만 훌륭하게 작동하며 tensorflow를 직접 또는 간접적으로 가져 오는 테스트 파일 만 오염시킵니다.

# Place this before directly or indirectly importing tensorflow
import logging
logging.getLogger("tensorflow").setLevel(logging.WARNING)

1
TF_CPP_MIN_LOG_LEVEL 솔루션은 그렇지 않은 동안 나를 위해 일했습니다. 좋은 생각이야!
— 내결함성

tensorflow 1.12에서 나를 위해 일한 솔루션 만.
— BiBi

사용 tensorflow-gpu 1.14.0. 위 함수를 호출했을 때이 출력을 받음 The name tf.logging.set_verbosity is deprecated. Please use tf.compat.v1.logging.set_verbosity instead. WARNING:tensorflow:From C:/.../NN.py:297: The name tf.logging.ERROR is deprecated. Please use tf.compat.v1.logging.ERROR instead. 메시지 다음에 경고가 표시되지 않도록
— 하세요


10

으로는 TF_CPP_MIN_LOG_LEVEL당신이 시도 할 수 있습니다 나를 위해 작동하지 않았다 :

tf.logging.set_verbosity(tf.logging.WARN)

tensorflow v1.6.0에서 나를 위해 일했습니다.


6

일반적인 python3 로그 관리자는 tensorflow == 1.11.0으로 작동합니다.

import logging
logging.getLogger('tensorflow').setLevel(logging.INFO)


2

여기에 약간의 유연성을 추가하기 위해 원하는 메시지를 필터링하는 기능을 작성하여 로깅 수준을보다 세밀하게 제어 할 수 있습니다.

logging.getLogger('tensorflow').addFilter(my_filter_func)

where 객체를 입력 [ docs ] 으로 my_filter_func받아들이고 메시지를 버리려면 0을 반환합니다. 그렇지 않으면 0이 아닙니다.LogRecordLogRecord

다음은 모든 n 번째 정보 메시지 만 유지하는 필터 예입니다 ( nonlocal여기 의 사용으로 인해 Python 3 ).

def keep_every_nth_info(n):
    i = -1
    def filter_record(record):
        nonlocal i
        i += 1
        return int(record.levelname != 'INFO' or i % n == 0)
    return filter_record

# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))

위의 모든 내용은 TensorFlow가 이미 로깅 상태를 설정했다고 가정합니다. tf.logging.get_verbosity()필터를 추가하기 전에 호출 하여 부작용없이이를 보장 할 수 있습니다 .


2

예, tf 2.0-beta를 사용하고 있으며 기본 로깅을 활성화 / 비활성화하려고합니다. tf1.X의 환경 변수와 메소드가 더 이상 존재하지 않는 것 같습니다.

PDB를 밟아서 이것이 작동한다는 것을 알았습니다.

# close the TF2 logger
tf2logger = tf.get_logger()
tf2logger.error('Close TF2 logger handlers')
tf2logger.root.removeHandler(tf2logger.root.handlers[0])

그런 다음 자체 로거 API를 추가합니다 (이 경우 파일 기반).

logtf = logging.getLogger('DST')
logtf.setLevel(logging.DEBUG)

# file handler
logfile='/tmp/tf_s.log'
fh = logging.FileHandler(logfile)
fh.setFormatter( logging.Formatter('fh %(asctime)s %(name)s %(filename)s:%(lineno)d :%(message)s') )
logtf.addHandler(fh)
logtf.info('writing to %s', logfile)

2

tensorflow 2.1.0의 경우 다음 코드가 정상적으로 작동합니다.

import tensorflow as tf
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

2

화면 에서 경고 출력 만 제거 해야하는 경우이 간단한 명령을 사용하여 tensorflow를 가져온 직후 콘솔 화면 을 지우고 싶을 수 있습니다 (경험에서 모든 디버깅 로그를 비활성화하는 것보다 효과적 임).

창에서 :

import os
os.system('cls')

Linux 또는 Mac에서 :

import os
os.system('clear')

0

난에서 다음 코드 코드 울부 짖는 소리를 사용하도록 솔루션 중에 위, Jupyter 노트북에서 내 문제를 해결할 수 없었다 Cicoria 및 문제 해결.

import warnings  
with warnings.catch_warnings():  
    warnings.filterwarnings("ignore",category=FutureWarning)
    import tensorflow as tf
    from tensorflow import keras
    from tensorflow.keras.preprocessing.text import Tokenizer

print('Done') 
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.