When you write code in Python, you sometimes see some "warning" messages. This information will not make the code wrong, but will make the output look messy. If you find these warnings annoying, you can use the following code to "shut up". Today we will learn how this code is done!
Code explanation
1. Import the required tools
import warnings import logging from transformers import logging as hf_logging
warnings: This is a built-in tool in Python to manage "warnings".
logging: This is a Python logging tool, and logs are the prompt information output when the program is running.
hf_logging: This is the logging tool of the transformers library, which we can also use to adjust the display of logs.
2. Define a function: ignore_warnings
def ignore_warnings():
A function is like a "toolbox" and when you need its function, just call it.
3. Ignore specific warnings
("ignore", message="Some weights of the model checkpoint") ("ignore", message="Could not find image processor class") ("ignore", message="The `max_size` parameter is deprecated")
("ignore", ...): This is to say "I want to ignore certain warnings".
message: What is written here is the content of the warning. As long as the warning contains this text, it will be "silenced".
Just like we tell the program: "Don't bother me when you see these 'content' warnings!"
4. Adjust the log display level
(level=)
: Set the "sound size" of the log.
level=: Tell the program to "only display error messages, and do not display other useless prompts."
5. Set the log level of the Transformers library
hf_logging.set_verbosity_error()
hf_logging.set_verbosity_error(): This is a log specifically used to adjust the transformers library, telling it to "only display error messages, and don't talk about others".
When to use this code?
Use deep learning tools: such as transformers, which will output a lot of useless warnings and affect reading.
When debugging code: Sometimes you only want to see important information and ignore unnecessary prompts.
Summarize
This code is a "silent remote control" that helps us block out those annoying warnings and unimportant information, making the code output cleaner and tidy!
Complete code
import warnings import logging from transformers import logging as hf_logging def ignore_warnings(): # Ignore specific warnings ("ignore", message="Some weights of the model checkpoint") ("ignore", message="Could not find image processor class") ("ignore", message="The `max_size` parameter is deprecated") # Adjust log level to display only error messages (level=) hf_logging.set_verbosity_error()
Add this code to your project and try it! It will make your output world much quieter.
This is the article about this article about how to ignore annoying warnings in Python. For more related content of ignoring warnings in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!