Predictive Hacks

How to Store the Scikit Learn Warnings

In case that you want to store the warnings that you get from Scikit Learn when you train a model, you can work with the built-in python library called warnings.

Let’s say that we run the following logistic regression model:

import warnings
from sklearn.linear_model import LogisticRegression
import pandas as pd

clf = LogisticRegression(random_state=5)

clf.fit(X_train, y)
 

And we get the following warning:

C:\Users\gpipis\Anaconda3\lib\site-packages\sklearn\linear_model\_logistic.py:763: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(

If we want to store this warning, we can work as follows:

with warnings.catch_warnings(record=True) as caught_warnings:
    clf.fit(X_train, y)
 

Now, we can get the warning by iterating the caught warnings.

for warn in caught_warnings:
    print(warn)
 
{message : ConvergenceWarning('lbfgs failed to converge (status=1):\nSTOP: TOTAL NO. of ITERATIONS REACHED LIMIT.\n\nIncrease the number of iterations (max_iter) or scale the data as shown in:\n    https://scikit-learn.org/stable/modules/preprocessing.html\nPlease also refer to the documentation for alternative solver options:\n    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression'), category : 'ConvergenceWarning', filename : 'C:\\Users\\gpipis\\Anaconda3\\lib\\site-packages\\sklearn\\linear_model\\_logistic.py', lineno : 763, line : None}

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s