2017年11月に提案されたカプセルネットワークの実行速度を上げる. 論文へのリンクはこちら
- squash関数をベクトル版step関数に変更
- routingアルゴリズムの変数bを削除
def step(vectors, axis=-1):
"""
カプセルネットワークでは非線形の活性化関数が使用される. この関数はベクトルの長さを0~1に圧縮する.
:param vectors: 圧出される複数のベクトル, 4次元テンソル
:param axis: 圧縮する軸
:return: 複数の入力ベクトルと同じ形の一つのテンソル
"""
s_squared_norm = K.sum(K.square(vectors), axis, keepdims=True)
return vectors / s_squared_norm
# 前処理として係数を1に初期化
# c.shape = [None, self.num_capsule, self.input_num_capsule].
c = tf.ones(shape=[K.shape(inputs_hat)[0], self.num_capsule, self.input_num_capsule])
assert self.routings > 0, 'The routings should be > 0.'
for i in range(self.routings):
# inputs_hat.shape=[None, num_capsule, input_num_capsule, dim_capsule]
# The first two dimensions as `batch` dimension,
# then matmal: [input_num_capsule] x [input_num_capsule, dim_capsule] -> [dim_capsule].
# outputs.shape=[None, num_capsule, dim_capsule]
outputs = step(K.batch_dot(c, inputs_hat, [2, 2])) # [None, 10, 16]
if i < self.routings - 1:
# outputs.shape = [None, num_capsule, dim_capsule]
# inputs_hat.shape=[None, num_capsule, input_num_capsule, dim_capsule]
# The first two dimensions as `batch` dimension,
# then matmal: [dim_capsule] x [input_num_capsule, dim_capsule]^T -> [input_num_capsule].
# c.shape=[batch_size, num_capsule, input_num_capsule]
c += K.batch_dot(outputs, inputs_hat, [2, 3])
google colabのGPUを使用.
変更点 | 時間 | 精度 |
---|---|---|
変更なし | 3分36秒 | loss: 0.1284 - capsnet_loss: 0.1013 - decoder_loss: 0.0690 - capsnet_acc: 0.8994 - val_loss: 0.0445 - val_capsnet_loss: 0.0242 - val_decoder_loss: 0.0516 - val_capsnet_acc: 0.9878 |
step関数 | 3分35秒 | loss: 0.2779 - capsnet_loss: 0.2505 - decoder_loss: 0.0699 - capsnet_acc: 0.7014 - val_loss: 0.0679 - val_capsnet_loss: 0.0487 - val_decoder_loss: 0.0490 - val_capsnet_acc: 0.9776 |
light-routingアルゴリズム | 3分33秒 | loss: 0.2068 - capsnet_loss: 0.1794 - decoder_loss: 0.0699 - capsnet_acc: 0.8095 - val_loss: 0.0542 - val_capsnet_loss: 0.0364 - val_decoder_loss: 0.0456 - val_capsnet_acc: 0.9829 |
どちらも | 3分31秒 | loss: 0.2227 - capsnet_loss: 0.1949 - decoder_loss: 0.0710 - capsnet_acc: 0.7932 - val_loss: 0.1243 - val_capsnet_loss: 0.1060 - val_decoder_loss: 0.0466 - val_capsnet_acc: 0.8827 |
TensorFlow>=1.2 Keras>=2.0.7をインストール
pip install tensorflow-gpu
pip install keras
git clone https://github.com/XifengGuo/CapsNet-Keras.git capsnet-keras
cd capsnet-keras
デフォルト設定
python capsulenet.py
ヘルプ機能
python capsulenet.py -h
下記のコマンドでresult/trained_model.h5
にモデルを保存することができます.
$ python capsulenet.py -t -w result/trained_model.h5
テストaccuracyと再構成された画像を出力してくれます.
学習済みモデルのダウンロードはこちら
(注)Keras 2.0.9が必要ですので満たしていない方はアップデートをしてください.
python capsulenet-multi-gpu.py --gpus 2
このコマンドで自動的にGPUを用いて処理してくれます. なお,トレーニング中はaccuracyを出力しません.
-
PyTorch:
-
TensorFlow:
- naturomics/CapsNet-Tensorflow
I referred to some functions in this repository. - InnerPeace-Wu/CapsNet-tensorflow
- chrislybaer/capsules-tensorflow
- naturomics/CapsNet-Tensorflow
-
MXNet:
-
Chainer:
-
Matlab:
- python
- keras
- ディープラーニング
- カプセルネットワーク