LoginSignup
0
0

Numpyのメモ(随時更新)

Last updated at Posted at 2024-04-29

忘れがちなので個人的なNumpyのメモを残しておきます。
ちょっとずつ増やしていく

>> import numpy as np

連続した数列を作成したい

>> np.arange(10)

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

乱数を生成する

>> from numpy import random # パッケージのインポート

>> random.rand() # [0, 1)の乱数を生成

>> random.randn() # 平均0, 分散1の正規分布に従う乱数を生成

>> random.normal(100, 1) # 平均と分散を指定して正規分布に従う乱数を生成、第1引数が平均、第2引数が分散

>> random.rand(5) # 長さ5(=shapeが(5, ) )の乱数の1次元配列を生成

>> random.rand(5, 5) # shapeが(5, 5)の乱数の2次元配列を生成

>> random.normal(100, 10, (5, 5)) # shapeが(5, 5)で平均100, 分散10の正規分布に従う乱数の2次元配列を生成

>> random.seed(seed=32) # seed値として整数を指定して、乱数を生成する

ユニバーサル関数でよく使用するもの

参考

最大値を取得する

>> a = np.arange(10)
>> np.max(a)

9

行ごとor列ごとに関数を適用したい

# aという配列に対して、行ごとにnp.maxを適用する
>> np.max(a, axis=1, keepdims=True)

ノルムを計算する

>> a = np.arange(10).reshape(3, 3) # 例として3行3列の二次元配列を用意

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

>> np.linalg.norm(a) # aの行列ノルムを出す

14.283

>> np.linalg.norm(a, axis=0) # 列毎のベクトルノルムをとる

array([6.708, 8.124, 9.644])

>> np.linalg.norm(a, norm=1) # 行毎のベクトルノルムをとる

array([ 2.236,  7.071, 12.207])

>> np.linalg.norm(a, ord=2) # 各要素の2乗和の平方根でノルムを算出する、デフォルトは2

14.227

>> np.linalg.norm(a, ord=N) # 各要素のN乗和の平方根でノルムを算出する
0
0
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
0
0