ipywidgets

ipywidgets

あまり使った事が無いので,

ipywidgets – GitHubのExampleをみながら触ってみる.

Jupyter Labでは動かない(widgetが表示されない)のが残念.

[1] Explore Random Graphs Using NetworkX

%matplotlib inline
import matplotlib.pyplot as plt
from ipywidgets import interact
import networkx as nx


# wrap a few graph generation functions so they have the same signature
def random_lobster(n, m, k, p):
    return nx.random_lobster(n, p, p / m)


def powerlaw_cluster(n, m, k, p):
    return nx.powerlaw_cluster_graph(n, m, p)


def erdos_renyi(n, m, k, p):
    return nx.erdos_renyi_graph(n, p)


def newman_watts_strogatz(n, m, k, p):
    return nx.newman_watts_strogatz_graph(n, k, p)


def plot_random_graph(n, m, k, p, generator):
    g = generator(n, m, k, p)
    nx.draw(g)
    plt.show()


interact(
    plot_random_graph, n=(2, 30), m=(1, 10), k=(1, 10), p=(0.0, 1.0, 0.001),
    generator={
             'lobster': random_lobster,
             'power law': powerlaw_cluster,
             'Newman-Watts-Strogatz': newman_watts_strogatz,
             u'Erdős-Rényi': erdos_renyi,
    }
)

ノード数,追加ノードから既存ノードに接続するエッジ数,接続される隣接ノード数,確率をグリグリとインタラクティブに変更できる.generatorのプルダウンリストを変更すれば,ランダムグラフのモデルを変更できる.楽しい.

[2] Image Browser

from sklearn import datasets


digits = datasets.load_digits()


def browse_images(digits):
    n = len(digits.images)
    def view_image(i):
        plt.imshow(digits.images[i], cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title(f'Training: {digits.target[i]}')
        plt.show()
    interact(view_image, i=(0, n-1))


browse_images(digits)

[3] Image Manipulation with skimage

from IPython.display import Image
from skimage import data, filters, io, img_as_float


img = img_as_float(data.coffee())
io.imshow(img)

matplotlib.image.AxesImage( = plt.imshow(img))

from PIL import Image

img2 = Image.fromarray(img)
img2.show()

# Stdlib imports
from io import BytesIO

# Third-party libraries
from IPython.display import Image
from ipywidgets import interact, interactive, fixed
import matplotlib as mpl
from skimage import data, filters, io, img_as_float
import numpy as np


def arr2img(arr):
    """Display a 2- or 3-d numpy array as an image."""
    if arr.ndim == 2:
        format, cmap = 'png', mpl.cm.gray
    elif arr.ndim == 3:
        format, cmap = 'jpg', None
    else:
        raise ValueError("Only 2- or 3-d arrays can be displayed as images.")
    # Don't let matplotlib autoscale the color range so we can control overall luminosity
    vmax = 255 if arr.dtype == 'uint8' else 1.0
    with BytesIO() as buffer:
        mpl.image.imsave(buffer, arr, format=format, cmap=cmap, vmin=0, vmax=vmax)
        out = buffer.getvalue()
    return Image(out)


arr2img(img)

その他:

・時計と角度

%matplotlib inline
import math
import matplotlib.pyplot as plt
from ipywidgets import interact


def circle(i, hh, mh):
    x, y = math.cos(math.radians(i)), math.sin(math.radians(i))
    mhx, mhy = math.cos(-math.radians(mh*6-90)), math.sin(-math.radians(mh*6-90))
    hhx = math.cos(-math.radians(hh*30+mh/2-90)) * 0.7
    hhy = math.sin(-math.radians(hh*30+mh/2-90)) * 0.7
    plt.plot(
        [math.cos(math.radians(j)) for j in range(360)],
        [math.sin(math.radians(j)) for j in range(360)],
        '--'
    )
    plt.scatter(x, y, c='r')
    plt.plot([0, mhx], [0, mhy], 'k-d', lw=3, ms=10, alpha=0.8)
    plt.plot([0, hhx], [0, hhy], 'k-d', lw=5, ms=10, alpha=0.9)
    for j in range(12):
        plt.text(
            math.cos(-math.radians(j*30-90)),
            math.sin(-math.radians(j*30-90)),
            f'{j}',
            fontsize=20, fontweight='bold'
        )
    plt.xticks([])
    plt.yticks([])
    plt.show()


interact(circle, i=(0, 360), hh=(0, 12), mh=(0, 60))

・ロジスティック写像

PAGE_BREAK: PageBreak

def plot_logistic(i):
    def logistic(a):
        x = [0.8]
        for i in range(400):
            x.append(a * x[-1] * (1 - x[-1]))
        return x[-100:]
    al = [2.0 + i * 0.002 for i in range(i)]
    _, ax = plt.subplots(figsize=(8, 6))
    for a in al:
        ax.plot([a]*len(logistic(a)), logistic(a), "c.", markersize=1.7)
    ax.set_title(f'i = {i}')
    plt.show()


interact(plot_logistic, i=(450, 1000))

カテゴリー: 未分類 パーマリンク

ipywidgets への3件のフィードバック

  1. ピンバック: Requests: 人間のためのHTTP | 粉末@それは風のように (日記)

  2. ピンバック: Facets | 粉末@それは風のように (日記)

  3. ピンバック: networkx | 粉末@それは風のように (日記)

コメントは受け付けていません。