1
5

More than 3 years have passed since last update.

【100 numpy exercises】でnumpy力を鍛える!(1〜10問目)

Last updated at Posted at 2021-08-11

最近、機械学習を学んでいるのですが、numpyを本格的に活用する機会がありそうなので学び直そうと思いました。

練習問題として「100 numpy exercises」というものがありました。

これはGitHub上に公開されており、ローカルにダウンロードすれば問題を解くことができます。

上記ページから「Code」というボタンを押し、「Download ZIP」を選択してから好きな場所にダウンロードしてください。

その中の「100_Numpy_exercises.ipynb」というものが問題集なので、Jupyter Notebookで開きます。

開いたら一番初めのセルを見てください。

100_Numpy_exercises.ipynb
%run initialise.py

initialize.pyモジュールを実行すると、各質問に対してhint(n)またはanswer(n)でn個の質問番号の答えやヒントを問い合わせることができます。

準備が整ったら、早速1~10問やっていきたいと思います!

1. Import the numpy package under the name np (★☆☆)

1. npという名前でnumpyパッケージをインポートします。
100_Numpy_exercises.ipynb(1)
import numpy as np

これは as をつけることによって名前を新たに命名することができます。
正解は answer(1) で確認できます。

2. Print the numpy version and the configuration (★☆☆)

2. numpyのバージョンと設定を表示する
100_Numpy_exercises.ipynb(2)
print(np.__version__)
np.show_config()

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(2)-output
1.21.0
blas_mkl_info:
  NOT AVAILABLE
blis_info:
  NOT AVAILABLE
openblas_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
    runtime_library_dirs = ['/usr/local/lib']
blas_opt_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
    runtime_library_dirs = ['/usr/local/lib']
lapack_mkl_info:
  NOT AVAILABLE
openblas_lapack_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
    runtime_library_dirs = ['/usr/local/lib']
lapack_opt_info:
    libraries = ['openblas', 'openblas']
    library_dirs = ['/usr/local/lib']
    language = c
    define_macros = [('HAVE_CBLAS', None)]
    runtime_library_dirs = ['/usr/local/lib']

ここではバージョンが1.21.0で、その下に各設定が出力されています。

3. Create a null vector of size 10 (★☆☆)

3. サイズ10のNULLベクトルを作成
100_Numpy_exercises.ipynb(3)
z = np.zeros(10)
print(z)

np.zerosは、0で初期化されたndarrayを生成する関数です。つまりnp.zerosを使えば、0を要素とする配列を生成することができます。

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(3)-output
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

10個の0が格納された配列を確認できました。

4. How to find the memory size of any array (★☆☆)

4. 任意の配列のメモリサイズの求め方
100_Numpy_exercises.ipynb(4)
Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))

ここでは10×10の配列を作成し、配列の要素数(Z.size)と要素1つあたりのメモリサイズ(Z.itemsize)をかけることによって配列のメモリサイズを求めるようにしています。

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(4)-output
800 bytes

5. How to get the documentation of the numpy add function from the command line? (★☆☆)

5. numpy add関数のドキュメントをコマンドラインから取得するには?
100_Numpy_exercises.ipynb(5)
%run `python -c "import numpy; numpy.info(numpy.add)"`

np.infoで括弧内に指定した関数のドキュメントを見ることができます。コマンドラインから取得する際には、上のコードのようになります。

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(5)-output
add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added.
    If ``x1.shape != x2.shape``, they must be broadcastable to a common
    shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If provided, it must have
    a shape that the inputs broadcast to. If not provided or None,
    a freshly-allocated array is returned. A tuple (possible only as a
    keyword argument) must have length equal to the number of outputs.
where : array_like, optional
    This condition is broadcast over the input. At locations where the
    condition is True, the `out` array will be set to the ufunc result.
    Elsewhere, the `out` array will retain its original value.
    Note that if an uninitialized `out` array is created via the default
    ``out=None``, locations within it where the condition is False will
    remain uninitialized.
**kwargs
    For other keyword-only arguments, see the
    :ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
add : ndarray or scalar
    The sum of `x1` and `x2`, element-wise.
    This is a scalar if both `x1` and `x2` are scalars.

Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.

Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])

The ``+`` operator can be used as a shorthand for ``np.add`` on ndarrays.

>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> x1 + x2
array([[ 0.,  2.,  4.],
       [ 3.,  5.,  7.],
       [ 6.,  8., 10.]])

6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)

6. サイズ10のNULLベクトルを作成するが、5番目の値は1である
100_Numpy_exercises.ipynb(6)
Z = np.zeros(10)
Z[4] = 1
print(Z)

3番目の問題と同じようにまず10個の0が格納された配列を生成する。
次に配列の5番目の0を1に置き換えるだけです。

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(6)-output
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]

7. Create a vector with values ranging from 10 to 49 (★☆☆)

7. 10から49までの値を持つベクトルの作成
100_Numpy_exercises.ipynb(7)
Z = np.arange(10,50)
print(Z)

np.arangeを使って括弧内に範囲を指定すれば、10から49までの値を持つ配列を作成することができます。

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(7)-output
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]

10から49までが格納されている配列の生成が確認できました。

8. Reverse a vector (first element becomes last) (★☆☆)

8. ベクトルを逆にする(最初の要素が最後の要素になる)
100_Numpy_exercises.ipynb(8)
Z = np.arange(50)
Z = Z[::-1]
print(Z)

np.arangeで0〜49の配列を生成し、ここで::-1を指定することで要素を逆順に変えられます。

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(8)-output
[49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26
 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2
  1  0]

49から始まり、0で終わっています。

9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)

9. 0から8までの値を持つ3×3のマトリックスを作る
100_Numpy_exercises.ipynb(9)
Z = np.arange(9).reshape(3, 3)
print(Z)

np.arangeで0〜8の配列を生成し、reshapeで配列の形を変えられます。

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(9)-output
[[0 1 2]
 [3 4 5]
 [6 7 8]]

10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)

10. [1,2,0,0,4,0]から0でない要素のインデックス番号を求める
100_Numpy_exercises.ipynb(10)
nz = np.nonzero([1,2,0,0,4,0])
print(nz)

np.nonzeroは配列の要素の中で、0ではない要素のインデックス番号を配列で返してくれる関数です。

実行結果は以下の通りです。

100_Numpy_exercises.ipynb(10)-output
(array([0, 1, 4]),)

今回は以上になります。
次は11〜20をやっていこうと思います。

次回の記事

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5