Display pyGAM model summary

Display pyGAM model summary into streamlit application.
Source: https://codeburst.io/pygam-getting-started-with-generalized-additive-models-in-python-457df5b4705f

    import pandas as pd
    from sklearn.datasets import load_boston
    from pygam import LinearGAM

    boston = load_boston()
    df = pd.DataFrame(boston.data, columns=boston.feature_names)
    target_df = pd.Series(boston.target)
    df.head()

    X = df
    y = target_df
    gam = LinearGAM(n_splines=10).gridsearch(X.values, y.values)
    gam.summary()

As shown in image the output of gam.summary is not displaying with any of the st.* (display functions)

Hi @Ahmad_Zia , welcome to the Streamlit community!

It’s unfortunate that the pyGAM summary method dumps the result using print() statements, but you can redirect the output using the following code:

import pandas as pd
from sklearn.datasets import load_boston
from pygam import LinearGAM
from io import StringIO
import sys
import streamlit as st

# redirect where stdout goes, write to 'mystdout'
# https://stackoverflow.com/a/1218951/2394542
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
target_df = pd.Series(boston.target)
df.head()

X = df
y = target_df
gam = LinearGAM(n_splines=10).gridsearch(X.values, y.values)
gam.summary()

sys.stdout = old_stdout

# this is what writes to the streamlit app...read the value from the redirected out
st.text(mystdout.getvalue())

Best,
Randy

1 Like

@randyzwitch Thanks a lot Randy, now atleast it started printing.

@randyzwitch Thank you so much for the help.