Как отобразить объект ‹IPython.core.display.HTML› в консоли spyder IPython?

Я пытаюсь запустить код:

perm = PermutationImportance(clf).fit(X_test, y_test)
eli5.show_weights(perm)

чтобы получить представление о том, какие функции являются наиболее важными в модели, но результат

<IPython.core.display.HTML object> 

Любые решения или обходные пути для этой проблемы?

Спасибо вам за ваши предложения!


person Evan    schedule 27.02.2019    source источник


Ответы (4)


(сопровождающий Spyder здесь) На данный момент (февраль 2019 г.) нет доступных обходных путей или решений для отображения веб-контента на наших консолях, извините.

Примечание. Мы думаем, как сделать это возможным, но, скорее всего, это не будет доступно до 2022 года.

person Carlos Cordoba    schedule 27.02.2019
comment
Здравствуйте, сейчас есть в наличии? (июль 2020 г.) Спасибо! - person python_enthusiast; 30.07.2020
comment
К сожалению, это не так, извините. - person Carlos Cordoba; 30.07.2020
comment
он доступен сейчас (июнь 2021 г.)? - person Caridorc; 03.06.2021
comment
Нет, это не так, извините. - person Carlos Cordoba; 03.06.2021

Kiudge должен просто отображать HTML:

with open('C:\Temp\disppage.htm','wb') as f:   # Use some reasonable temp name
    f.write(htmlobj.html.encode("UTF-8"))

# open an HTML file on my own (Windows) computer
url = r'C:\Temp\disppage.htm'
webbrowser.open(url,new=2)
person J Hudock    schedule 17.07.2019
comment
Я получаю, что объект «HTML» не имеет атрибута «html» от f.write - person Cos; 13.07.2020

Спасибо за идею J Hudok. Ниже приведен мой рабочий пример

from sklearn.datasets import load_iris
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
import eli5
from eli5.sklearn import PermutationImportance
from sklearn.model_selection import train_test_split
import webbrowser

# Load iris data & convert to dataframe
iris_data = load_iris()
data = pd.DataFrame({
    'sepal length': iris_data.data[:,0],
    'sepal width': iris_data.data[:,1],
    'petal length': iris_data.data[:,2],
    'petal width': iris_data.data[:,3],
    'species': iris_data.target
})
X = data[['sepal length', 'sepal width', 'petal length', 'petal width']]
y = data['species']

# Split train & test dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# Initialize classifier
clf = RandomForestClassifier(n_estimators=56, max_depth=8, random_state=1, verbose=1)
clf.fit(X_train, y_train)

# Compute permutation feature importance
perm_importance = PermutationImportance(clf, random_state=0).fit(X_test, y_test)

# Store feature weights in an object
html_obj = eli5.show_weights(perm_importance, feature_names = X_test.columns.tolist())

# Write html object to a file (adjust file path; Windows path is used here)
with open('C:\\Tmp\\Desktop\iris-importance.htm','wb') as f:
    f.write(html_obj.data.encode("UTF-8"))

# Open the stored HTML file on the default browser
url = r'C:\\Tmp\\Desktop\iris-importance.htm'
webbrowser.open(url, new=2)
person Ziaul Chowdhury    schedule 03.08.2020

Я нашел решение для Spyder:

clf.fit(X_train, y_train)
onehot_columns = list(clf.named_steps['preprocessor'].named_transformers_['cat'].named_steps['onehot'].get_feature_names(input_features=categorical_features))
numeric_features_list = list(numeric_features)
numeric_features_list.extend(onehot_columns)
numeric_features_list = np.array(numeric_features_list)
selected_features_bool =list(clf.named_steps['feature_selection'].get_support(indices=False))
numeric_features_list = list(numeric_features_list[selected_features_bool])
eli5.format_as_dataframe(eli5.explain_weights(clf.named_steps['classification'], top=50, feature_names=numeric_features_list))

В результате он выдал мне вывод в формате dataframe:

0                       region_BAKI  0.064145
1           call_out_offnet_dist_w1  0.025365
2                         trf_Bolge  0.022637
3            call_in_offnet_dist_w1  0.018974
4        device_os_name_Proprietary  0.018608

...

person Zaur Huseynov    schedule 30.12.2020