python 関数定義を見る

  • 昨日の記事は、scikit-learnをべたにやろうかと思ったその書きかけ
  • しばらくやったら、たくさんありすぎることと、まあ、コピペすれば動くじゃない!ということでやる気がなくなる
  • が、そうは言っても手を動かすことは慣れるために必要
  • ただし、Exampleは読みにくいものも多く、なんだかなーと思わないでもない
  • ということで、関数に出会ったら、その書かれ方を読むのが手っ取り早いだろう、ということで
from sklearn.datasets.samples_generator import make_blobs
import inspect
inspect.getsource(make_blobs)
  • 改行文字が"\n"で出て、見にくいので
print(inspect.getsource(make_blobs))
  • 逆に、関数定義を書くときは、このinspect.getsource()で書きださせたときに、諸情報が現れるように、冒頭に、コメント欄を指定 (""","""でサンドイッチ)すればよさそうだ
  • そのコメント欄には、
    • 簡易説明
    • Parameters
    • Returns
    • Exanmples
    • See also
  • があればよいだろうか?他にも書式として定形的なものがあるだろうか?
import inspect

inspect.getsource(make_blobs)
Out[154]: 'def make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0,\n               center_box=(-10.0, 10.0), shuffle=True, random_state=None):\n    """Generate isotropic Gaussian blobs for clustering.\n\n    Read more in the :ref:`User Guide <sample_generators>`.\n\n    Parameters\n    ----------\n    n_samples : int, optional (default=100)\n        The total number of points equally divided among clusters.\n\n    n_features : int, optional (default=2)\n        The number of features for each sample.\n\n    centers : int or array of shape [n_centers, n_features], optional\n        (default=3)\n        The number of centers to generate, or the fixed center locations.\n\n    cluster_std: float or sequence of floats, optional (default=1.0)\n        The standard deviation of the clusters.\n\n    center_box: pair of floats (min, max), optional (default=(-10.0, 10.0))\n        The bounding box for each cluster center when centers are\n        generated at random.\n\n    shuffle : boolean, optional (default=True)\n        Shuffle the samples.\n\n    random_state : int, RandomState instance or None, optional (default=None)\n        If int, random_state is the seed used by the random number generator;\n        If RandomState instance, random_state is the random number generator;\n        If None, the random number generator is the RandomState instance used\n        by `np.random`.\n\n    Returns\n    -------\n    X : array of shape [n_samples, n_features]\n        The generated samples.\n\n    y : array of shape [n_samples]\n        The integer labels for cluster membership of each sample.\n\n    Examples\n    --------\n    >>> from sklearn.datasets.samples_generator import make_blobs\n    >>> X, y = make_blobs(n_samples=10, centers=3, n_features=2,\n    ...                   random_state=0)\n    >>> print(X.shape)\n    (10, 2)\n    >>> y\n    array([0, 0, 1, 0, 2, 2, 2, 1, 1, 0])\n\n    See also\n    --------\n    make_classification: a more intricate variant\n    """\n    generator = check_random_state(random_state)\n\n    if isinstance(centers, numbers.Integral):\n        centers = generator.uniform(center_box[0], center_box[1],\n                                    size=(centers, n_features))\n    else:\n        centers = check_array(centers)\n        n_features = centers.shape[1]\n\n    if isinstance(cluster_std, numbers.Real):\n        cluster_std = np.ones(len(centers)) * cluster_std\n\n    X = []\n    y = []\n\n    n_centers = centers.shape[0]\n    n_samples_per_center = [int(n_samples // n_centers)] * n_centers\n\n    for i in range(n_samples % n_centers):\n        n_samples_per_center[i] += 1\n\n    for i, (n, std) in enumerate(zip(n_samples_per_center, cluster_std)):\n        X.append(centers[i] + generator.normal(scale=std,\n                                               size=(n, n_features)))\n        y += [i] * n\n\n    X = np.concatenate(X)\n    y = np.array(y)\n\n    if shuffle:\n        indices = np.arange(n_samples)\n        generator.shuffle(indices)\n        X = X[indices]\n        y = y[indices]\n\n    return X, y\n'
print(inspect.getsource(make_blobs))
def make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0,
               center_box=(-10.0, 10.0), shuffle=True, random_state=None):
    """Generate isotropic Gaussian blobs for clustering.

    Read more in the :ref:`User Guide <sample_generators>`.

    Parameters
    ----------
    n_samples : int, optional (default=100)
        The total number of points equally divided among clusters.

    n_features : int, optional (default=2)
        The number of features for each sample.

    centers : int or array of shape [n_centers, n_features], optional
        (default=3)
        The number of centers to generate, or the fixed center locations.

    cluster_std: float or sequence of floats, optional (default=1.0)
        The standard deviation of the clusters.

    center_box: pair of floats (min, max), optional (default=(-10.0, 10.0))
        The bounding box for each cluster center when centers are
        generated at random.

    shuffle : boolean, optional (default=True)
        Shuffle the samples.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    Returns
    -------
    X : array of shape [n_samples, n_features]
        The generated samples.

    y : array of shape [n_samples]
        The integer labels for cluster membership of each sample.

    Examples
    --------
    >>> from sklearn.datasets.samples_generator import make_blobs
    >>> X, y = make_blobs(n_samples=10, centers=3, n_features=2,
    ...                   random_state=0)
    >>> print(X.shape)
    (10, 2)
    >>> y
    array([0, 0, 1, 0, 2, 2, 2, 1, 1, 0])

    See also
    --------
    make_classification: a more intricate variant
    """
    generator = check_random_state(random_state)

    if isinstance(centers, numbers.Integral):
        centers = generator.uniform(center_box[0], center_box[1],
                                    size=(centers, n_features))
    else:
        centers = check_array(centers)
        n_features = centers.shape[1]

    if isinstance(cluster_std, numbers.Real):
        cluster_std = np.ones(len(centers)) * cluster_std

    X = []
    y = []

    n_centers = centers.shape[0]
    n_samples_per_center = [int(n_samples // n_centers)] * n_centers

    for i in range(n_samples % n_centers):
        n_samples_per_center[i] += 1

    for i, (n, std) in enumerate(zip(n_samples_per_center, cluster_std)):
        X.append(centers[i] + generator.normal(scale=std,
                                               size=(n, n_features)))
        y += [i] * n

    X = np.concatenate(X)
    y = np.array(y)

    if shuffle:
        indices = np.arange(n_samples)
        generator.shuffle(indices)
        X = X[indices]
        y = y[indices]

    return X, y