3 Jupyter notebook (Python) tricks

Introduction

Recently, I've been taking good care of Jupyter notebook (Python3), I will post it because some tricks have increased.

environment

Tips

Convert the result of the decision tree of sklearn into a figure and display it inline

Decision trees such as sklearn.tree.tree.DecisionTreeClassifier can output in .dot format, but trying to display them on a notebook is quite annoying. However, with certain preparations and procedures, you will be able to do that easily.

Things necessary

Method

Define a function like this.

decision_tree_util.py


import os
from tempfile import mkstemp
import subprocess

from sklearn.tree.export import export_graphviz


def convert_decision_tree_to_ipython_image(clf, feature_names=None, class_names=None,
                                           image_filename=None, tmp_dir=None):
    dot_filename = mkstemp(suffix='.dot', dir=tmp_dir)[1]
    with open(dot_filename, "w") as out_file:
        export_graphviz(clf, out_file=out_file,
                        feature_names=feature_names,
                        class_names=class_names,
                        filled=True, rounded=True,
                        special_characters=True)

    from IPython.display import Image

    image_filename = image_filename or ('%s.png' % dot_filename)

    subprocess.call(('dot -Tpng -o %s %s' % (image_filename, dot_filename)).split(' '))
    image = Image(filename=image_filename)
    os.remove(dot_filename)
    return image

You can use it like this.

notebook


from sklearn import datasets
from sklearn.tree.tree import DecisionTreeClassifier
%matplotlib inline

iris = datasets.load_iris()
X = iris.data
Y = iris.target

clf = DecisionTreeClassifier(max_depth=3)
clf.fit(X, Y)
convert_decision_tree_to_ipython_image(clf, image_filename='tree.png')

Reload the imported file at runtime

You may want to reload because you changed the file you are importing from another location. If you write the following, it will be reloaded every time you run notebook. Before I knew this, I restarted the kernel every time (^^;

%reload_ext autoreload
%autoreload 2

Output multiple graphs, pandas.DataFrame, etc. on the notebook from the program

I want to output DataFrame etc.

from IPython.core.display import display

Import and

display(data_frame)

Then it will be displayed as usual. If you pass a character string etc., the character string will be output normally.

I want to output a graph

If you write like this,

notebook


from IPython.core.display import display
from numpy.random.mtrand import normal
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

display('graph1')
sns.distplot(normal(0, 1, size=1000))
sns.distplot(normal(0.1, 2, size=1000))

display('graph2')
sns.distplot(normal(-2, 2, size=1000))
sns.distplot(normal(2, 4, size=1000))

The graphs are frozen together and the graph comes to the bottom.


In that case, you should call plt.show () at the right time.

notebook


from IPython.core.display import display
from numpy.random.mtrand import normal
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

display('graph1')
sns.distplot(normal(0, 1, size=1000))
sns.distplot(normal(0.1, 2, size=1000))
plt.show()

display('graph1')
sns.distplot(normal(-2, 2, size=1000))
sns.distplot(normal(2, 4, size=1000))
plt.show()

This can be used not only for script on notebook, but also when you want to output to notebook from ordinary source code.

at the end

It was a trick.

Recommended Posts

3 Jupyter notebook (Python) tricks
Jupyter tricks
Python tricks
python3.8 venv environment jupyter notebook
Snippet settings for python jupyter notebook
Python memo Anaconda x Jupyter Notebook
Generate Jupyter notebook ".ipynb" in Python
Jupyter Notebook: 4 banal tips and tricks
Easy to use Jupyter notebook (Python3.5)
Jupyter Notebook memo
Introducing Jupyter Notebook
Powerful Jupyter Notebook
[Python] Pre-processing tricks
Jupyter notebook password
Jupyter Notebook memo
Linking python and JavaScript with jupyter notebook
Get started Jupyter Notebook
Install Python Jupyter lab
[Cloud103] # 3 Jupyter Notebook again
Convert jupyter notebook .ipynb files to python executable .py files
Virtual environment construction with Docker + Flask (Python) + Jupyter notebook
python jupyter notebook Data preprocessing championship (target site: BicCamera)
Shortcut key for Jupyter notebook
Using Graphviz with Jupyter Notebook
Display HTML in Jupyter notebook
Use pip with Jupyter Notebook
Multiprocessing error in Jupyter Notebook
Try using Jupyter Notebook dynamically
[Super Basics] About jupyter Notebook
High charts on Jupyter notebook
View PDF on Jupyter Notebook
Use Cython with Jupyter Notebook
homebrew, pyenv, anaconda, Jupyter Notebook
Play with Jupyter Notebook (IPython Notebook)
Try running Python with Try Jupyter
[Complete version] Jupyter Notebook shortcut
Python | Jupyter> Post-mortem debugging | pdb.post_mortem ()
Run Jupyter Notebook on windows
How to use Jupyter Notebook
[Python tricks] 5 minor but useful Python tricks
<Python> Build a dedicated server for Jupyter Notebook data analysis
Allow external connections with jupyter notebook
How to batch start a python program created with Jupyter notebook
Formatting with autopep8 on Jupyter notebook
Jupyter Notebook essential for software development
Python
Post a Jupyter Notebook as a blog post
Visualize decision trees with jupyter notebook
Make a sound with Jupyter notebook
Jupyter Notebook Magic Command Personal Summary
Paste Jupyter Notebook document into Wordpress
Simply view the Jupyter notebook file
Run azure ML on jupyter notebook
[MEMO] [Development environment construction] Jupyter Notebook
Use markdown with jupyter notebook (with shortcut)
Add more kernels with Jupyter Notebook
View graphs inline in Jupyter Notebook
Convenient analysis with Pandas + Jupyter notebook
Launch jupyter notebook (+ take security measures)
Jupyter Notebook 6.0.2 cannot be installed in the Python 2.7 environment created in Anaconda
Try running Jupyter Notebook on Mac