LoginSignup
15
8

More than 3 years have passed since last update.

JavaScriptでもnumpyみたいなことがしたい!

Last updated at Posted at 2019-06-22

JavaScriptでも行列の計算がしたい

Pythonにはnumpyなどのライブラリがあり, 行列計算を簡単に行うことができます。
では, JavaScriptではどうでしょうか?
実は, numjsというライブラリが用意されています。
このnumjsですが, numpyライクなインタフェースを持っておりとても使いやすいです。

インストール方法

npm installで一発です。

npm install numjs

ただ、Pythonをインストールしておく必要であり, しかもPython3系ではなくPython2系でなければいけません。
pyenvを使われている方は、2系と3系の両方をglobalにすることでエラーを回避することができます。
例えば私の環境であれば以下のようにしました。

pyenv global 3.7.2 2.7.5

使い方

詳しい使い方は本家をご覧ください。
ここでは私がよく使うものをメモ書きしておきます。

行列の和

行列の和にはaddを使います。

addMatrix.js
const nj = require('numjs')

let a = nj.array([[0, 1, 1],
                  [1, 0, 1],
                  [1, 1, 0]])
let b = nj.array([[1, 0, 0],
                  [0, 1, 0],
                  [0, 0, 1]])

let c = nj.add(a, b)
// let c = a.add(b)でも可能

console.log(c)
/* 出力結果
array([[ 1, 1, 1],
       [ 1, 1, 1],
       [ 1, 1, 1]])
*/

行列の積

行列の積にはdotを使います。

dotMatrix.js
const nj = require('numjs')

let a = nj.array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
let b = nj.array([[1, 0, 0],
                  [0, 0, 1],
                  [0, 1, 0]])

let c = nj.dot(a, b)
// let c = a.dot(b)でも可能

console.log(c)
/* 出力結果
array([[ 1, 3, 2],
       [ 4, 6, 5],
       [ 7, 9, 8]])
*/

行列の転置

行列の転置には.Tを使います。

transposeMatrix.js
const nj = require('numjs')

let a = nj.array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])

console.log(a.T)
/* 出力結果
array([[ 1, 4, 7],
       [ 2, 5, 8],
       [ 3, 6, 9]])
*/

ベクトルの結合

ベクトルを結合して行列を生成する場合にはstackが便利です。

jointVector1.js
const nj = require('numjs')

let a = nj.array([1, 2, 3])
let b = nj.array([4, 5, 6])
let c = nj.array([7, 8, 9])

let d = nj.stack([a, b, c], axis = 0)

console.log(d)
/* 出力結果
array([[ 1, 2, 3],
       [ 4, 5, 6],
       [ 7, 8, 9]])
*/

なお, axisは結合方向を表す省略可能な引数であり, デフォルトでは0が指定されています。
axisに1を指定すると転置された行列を得ることができます。

jointVector2.js
const nj = require('numjs')

let a = nj.array([1, 2, 3])
let b = nj.array([4, 5, 6])
let c = nj.array([7, 8, 9])

let d = nj.stack([a, b, c], axis = 1)

console.log(d)
/* 出力結果
array([[ 1, 4, 7],
       [ 2, 5, 8],
       [ 3, 6, 9]])
*/

まとめ

JavaScriptでnumpyライクに行列計算ができるライブラリnumjsを紹介しました。
この他にも行列のreshapeやFFT (高速フーリエ変換) など便利な機能がたくさんありますので, 是非試してみてくださいね。

15
8
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
15
8