繁体   English   中英

抑制 python 警告

[英]Suppress a python warning

当我在 for 循环中迭代时,我不断收到相同的警告,我想抑制它。 警告内容如下:

C:\Users\Nick Alexander\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\preprocessing\data.py:193: UserWarning: Numerical issues were encountered when scaling the data and might not be solved. The standard deviation of the data is probably very close to 0. warnings.warn("Numerical issues were encountered "

产生警告的代码如下:

def monthly_standardize(cols, df_train, df_train_grouped, df_val, df_val_grouped, df_test, df_test_grouped):
    # Disable the SettingWithCopyWarning warning
    pd.options.mode.chained_assignment = None
    for c in cols:
        df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
        df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
        df_test[c] = df_test_grouped[c].transform(lambda x: scale(x.astype(float)))
    return df_train, df_val, df_test

我已经禁用了一个警告。 我不想禁用所有警告,我只想禁用此警告。 我正在使用 python 3.7 和 sklearn 版本 0.0

在脚本开头尝试此操作以忽略特定警告:

import warnings
warnings.filterwarnings("ignore", message="Numerical issues were encountered ")
import warnings
with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    # code that produces a warning

warnings.catch_warnings()表示“无论warnings.方法在此块内运行,退出块时撤消它们”。

要忽略特定代码块:

import warnings

class IgnoreWarnings(object):
    def __init__(self, message):
        self.message = message
    
    def __enter__(self):
        warnings.filterwarnings("ignore", message=f".*{self.message}.*")
    
    def __exit__(self, *_):
        warnings.filterwarnings("default", message=f".*{self.message}.*")

with IgnoreWarnings("fish"):
    warnings.warn("here be fish")
    warnings.warn("here be dog")
warnings.warn("here were fish")
UserWarning: here be dog
UserWarning: here were fish

python contextlib 有一个上下文管理器: suppress

from contextlib import suppress

with suppress(UserWarning):
    for c in cols:
        df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
        df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM