使用 IPython 和 Spyder 代替复制 jupyter HTML 输出

Replicate jupyter HTML output using IPython and Spyder instead

以下代码片段将在 Jupyter 中生成以下输出:

display(HTML('<h2>Hello, world!</h2>'))

运行 仅在 Spyder 中 IPython 控制台中的相同片段 returns <IPython.core.display.HTML object> 如下所示:

是否可以使用 Spyder 在 IPython 控制台中显示相同的输出? 我以为我会像 here 提到的那样用 from IPython.core.display import display, HTML 到达某个地方,但我可能完全忽略了这一点。

感谢您的任何建议!

Spyder有一个集成笔记本的插件:Spyder-Notebook(我没用过)。 Pycharm也有集成。

(Spyder maintainer here) Spyder IPython 控制台不支持 html 输出,所以上面的代码对它不起作用。

另一种想法是将排列特征重要性的输出存储到 html 文件中,并使用默认浏览器打开它。我从 J Hudok in another thread 那里得到了灵感。以下是我的工作示例

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)