Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 一般的な配列作成関数 | NumPy基礎
NumPy基礎
セクション 1.  6
single

single

book一般的な配列作成関数

メニューを表示するにはスワイプしてください

NumPy には、指定した形状(次元数)の配列を自動的に作成する配列生成関数も用意されています。代表的なものは以下の通りです:

  • zeros()
  • ones()
  • full()

zeros()

この関数名が示す通り、指定した形状のゼロ配列を作成します。配列の形状は shape パラメータで指定し、整数(1次元配列のサイズ)または高次元配列の場合は整数のタプルで指定します。

12345678910
import numpy as np # Сreating a 1D array of zeros with 5 elements zeros_1d = np.zeros(5) print(zeros_1d) # Сreating a 1D array of zeros with specifying dtype zeros_1d_int = np.zeros(5, dtype=np.int8) print(zeros_1d_int) # Сreating a 2D array of zeros of shape 5x3 zeros_2d = np.zeros((5, 3)) print(zeros_2d)
copy

ご覧のとおり、他の種類の配列と同様に、dtype パラメータも指定できます。

ones()

この関数は zeros() 関数と似ていますが、ゼロの配列ではなく、1 の配列を作成します。

12345678910
import numpy as np # Сreating a 1D array of ones with 5 elements ones_1d = np.ones(5) print(ones_1d) # Сreating a 1D array of ones with specifying dtype ones_1d_int = np.ones(5, dtype=np.int8) print(ones_1d_int) # Сreating a 2D array of ones of shape 5x3 ones_2d = np.ones((5, 3)) print(ones_2d)
copy

full()

numpy.full() 関数は前述の関数と似ていますが、配列を埋める値を指定するための第2引数 fill_value があります。第1引数 shape には、整数 または 整数のタプル を指定できます。

1234567
import numpy as np # Сreate an array of fours of size 5 array_fours_1d = np.full(5, 4) # Сreate an array of fives of shape 4x2 array_fives_2d = np.full((4, 2), 5) print(f'1D fours array: {array_fours_1d}') print(f'2D fives array:\n{array_fives_2d}')
copy

その他の用途

これらの関数は単なるプレースホルダーとしてだけでなく、さらに多くの用途があります。線形代数 における数学的演算で直接使用されることが多く、画像処理 などの機械学習や深層学習のさまざまな分野でも利用されます。

タスク

スワイプしてコーディングを開始

  1. サイズが5の一次元ゼロ配列を作成し、zeros_array_1dに代入。
  2. 形状が2x4の二次元ゼロ配列を作成し、zeros_array_2dに代入。
  3. サイズが3の一次元の1の配列を作成し、ones_array_1dに代入。
  4. 形状が2x3の二次元の1の配列を作成し、ones_array_2dに代入。
  5. 形状が2x2の二次元の7の配列を作成し、sevens_array_2dに代入。

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  6
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt