Keras モデルを視覚化するために使用できるツールは何ですか? 「1枚の画像は1000語の価値がある」という古い説は、複雑な機械学習モデルで作業する際にはさらに真実かもしれません。 幸いにも、機械学習モデルの視覚化にはいくつかの簡単な方法があります。このガイドはKerasモデルの視覚化に焦点を当て、以下のモデル(「テストモデル」)をデモに使用しています。 def build_model(pad_len, imu_dim, tof_dim, n_classes): def time_sum(x): return K.sum(x, axis=1) def squeeze_last_axis(x): return tf.squeeze(x, axis=-1) def expand_last_axis(x): return tf.expand_dims(x, axis=-1) filters_l1 = 64 kernel_l1 = 3 filters_l2 = 128 kernel_l2 = 5 reduction = 8 pool_size = 2 drop = 0.3 wd = 1e-4 inp = Input(shape=(pad_len, imu_dim + tof_dim)) imu = Lambda(lambda t: t[:, :, :imu_dim])(inp) tof = Lambda(lambda t: t[:, :, imu_dim:])(inp) # First CNN branch shortcut_1 = imu x1 = Conv1D(filters_l1, kernel_l1, padding="same", use_bias=False, kernel_regularizer=l2(wd))(imu) x1 = BatchNormalization()(x1) x1 = Activation("relu")(x1) x1 = Conv1D(filters_l1, kernel_l1, padding="same", use_bias=False, kernel_regularizer=l2(wd))(x1) x1 = BatchNormalization()(x1) x1 = Activation("relu")(x1) ch = x1.shape[-1] se = GlobalAveragePooling1D()(x1) se = Dense(ch//reduction, activation="relu")(se) se = Dense(ch, activation="sigmoid")(se) se = Reshape((1, ch))(se) x1 = Multiply()([x1, se]) if shortcut_1.shape[-1] != filters_l1: shortcut_1 = Conv1D(filters_l1, 1, padding="same", use_bias=False, kernel_regularizer=l2(wd))(shortcut_1) shortcut_1 = BatchNormalization()(shortcut_1) x1 = add([x1, shortcut_1]) x1 = Activation("relu")(x1) x1 = MaxPooling1D(pool_size)(x1) x1 = Dropout(drop)(x1) shortcut_2 = x1 x1 = Conv1D(filters_l2, kernel_l2, padding="same", use_bias=False, kernel_regularizer=l2(wd))(x1) x1 = BatchNormalization()(x1) x1 = Activation("relu")(x1) x1 = Conv1D(filters_l2, kernel_l2, padding="same", use_bias=False, kernel_regularizer=l2(wd))(x1) x1 = BatchNormalization()(x1) x1 = Activation("relu")(x1) ch = x1.shape[-1] se = GlobalAveragePooling1D()(x1) se = Dense(ch//reduction, activation="relu")(se) se = Dense(ch, activation="sigmoid")(se) se = Reshape((1, ch))(se) x1 = Multiply()([x1, se]) if shortcut_2.shape[-1] != filters_l2: shortcut_2 = Conv1D(filters_l2, 1, padding="same", use_bias=False, kernel_regularizer=l2(wd))(shortcut_2) shortcut_2 = BatchNormalization()(shortcut_2) x1 = add([x1, shortcut_2]) x1 = Activation("relu")(x1) x1 = MaxPooling1D(pool_size)(x1) x1 = Dropout(drop)(x1) # Second CNN branch x2 = Conv1D(filters_l1, kernel_l1, padding="same", use_bias=False, kernel_regularizer=l2(wd))(tof) x2 = BatchNormalization()(x2) x2 = Activation("relu")(x2) x2 = MaxPooling1D(2)(x2) x2 = Dropout(0.2)(x2) x2 = Conv1D(filters_l2, kernel_l1, padding="same", use_bias=False, kernel_regularizer=l2(wd))(x2) x2 = BatchNormalization()(x2) x2 = Activation("relu")(x2) x2 = MaxPooling1D(2)(x2) x2 = Dropout(0.2)(x2) merged = Concatenate()([x1, x2]) xa = Bidirectional(LSTM(128, return_sequences=True, kernel_regularizer=l2(wd)))(merged) xb = Bidirectional(GRU(128, return_sequences=True, kernel_regularizer=l2(wd)))(merged) xc = GaussianNoise(0.09)(merged) xc = Dense(16, activation="elu")(xc) x = Concatenate()([xa, xb, xc]) x = Dropout(0.4)(x) score = Dense(1, activation="tanh")(x) score = Lambda(squeeze_last_axis)(score) weights = Activation("softmax")(score) weights = Lambda(expand_last_axis)(weights) context = Multiply()([x, weights]) x = Lambda(time_sum)(context) x = Dense(256, use_bias=False, kernel_regularizer=l2(wd))(x) x = BatchNormalization()(x) x = Activation("relu")(x) x = Dropout(0.5)(x) x = Dense(128, use_bias=False, kernel_regularizer=l2(wd))(x) x = BatchNormalization()(x) x = Activation("relu")(x) x = Dropout(0.3)(x) out = Dense(n_classes, activation="softmax", kernel_regularizer=l2(wd))(x) return Model(inp, out) あなたが見ることができるように、上記のモデルはかなり複雑です。それはインターチアル測定ユニット(「IMU」)およびその他のセンサーデータからパターンを学ぶために使用されます。 . ご注意のように、オリジナルノートのモデル定義は、モデルデザインで繰り返される一定の論理をカプセル化するためにカスタムオブジェクトを使用します. I chose to remove those objects and explicity define the logic "inline" so as to better view the complete structure of the model in my slightly modified implementation. カグレノブ このガイドでは、以下の3つの視覚化ツールについて説明します。 Netron The Python package visualkeras TensorBoard 1. あなたのKerasモデルを視覚化するためにNetronを使用する 最もシンプルな視覚化ツールです. あなたは単にクリックする必要があります。 ホームページのボタンを押して、視覚化したいモデルを選択します。以下はテストモデルの最初のいくつかの層の視覚化です。 ネトロン Open Model... モデルがロードされると、モデルグラフのノードをクリックしてその属性を表示できます。 モデルグラフを輸出できます。 そして メインメニューアイコンをクリックし、適切なエクスポートオプションを選択します。 .png .svg 2.使用 あなたのKerasモデルを視覚化する ビジュアル ビジュアル THE Python パッケージも非常に使いやすく、トレーニング前にモデルを視覚化するための便利な方法を提供します。 : visualkeras pip pip install visualkeras 以下のPythonコードは、パッケージの基本的な使用を示しています。 # [Imports for your Keras model here...] import visualkeras # [Utility function to build your Keras model...] def build_model(model_params): # [Your model definition here...] # [Build the model...] model = build_model(model_params) # [Visualize the model...] visualkeras.graph_view(model).show() THE この方法は、テストモデルの最初のいくつかの層の次のグラフィックを生成します。 graph_view このパッケージはまた、A タイプとサイズによって区別されるモデル層のグラフィックを作成する方法: method that produces a graphic of the model layers distinguished by type and size: layered_view visualkeras.layered_view(model, legend=True).show() 見ると、通り過ぎる。 2 THE パラメータは、各層を記述する伝説を生成します。 True legend 1つの利点 The パッケージは、グラフィックがどのように表示されるかについて提供する制御です. You can review the parameters used to modify the graphic output on the ページです。 visualkeras パッケージ文書 3.使用 Kerasモデルを視覚化する テンサーボード テンサーボード Keras モデルを視覚化するための便利なオプションです。 ちょっとした「マッサージ」で、使用することも可能です。 トレーニング前にモデルの構造を視覚化する。 TensorBoard TensorFlow TensorBoard 3.1 インストール パッケージ jupyter-tensorboard このセクションは使用 Aの文脈の中で そのためには、設置の必要性は、 パッケージは、その代わりにいくつかの依存性を持っています。 次の手順を使用してインストールする : TensorBoard Jupyter notebook jupyter-tensorboard jupyter-tensorboard Install the package using . jupyter pip install jupyer Use the command to the package which was installed with the package installation process. The version of the package installed with which is as of this writing is not compatible with . This downgrade step installs a version of the package that is compatible with . See this for more information. pip install --upgrade notebook==6.4.12 downgrade notebook jupyter notebook jupyter 7.4.5 jupyter-tensorboard notebook jupyter-tensorboard StackOverflow article Install the package using . jupyter-tensorboard pip install jupyter-tensorboard 3.2 あなたのKerasモデルを視覚化するためにJupyterノートブックを設定する 上記のように、Kerasモデルを視覚化することができます。 次のJupyterノートコードは、入門セクションのテストモデルを使用してそれを実行する方法を示しています。 TensorBoard # Cell 1: Imports import tensorflow as tf from tensorflow.keras.models import Model, load_model from tensorflow.keras.layers import ( Input, Conv1D, BatchNormalization, Activation, add, MaxPooling1D, Dropout, Bidirectional, LSTM, GlobalAveragePooling1D, Dense, Multiply, Reshape, Lambda, Concatenate, GRU, GaussianNoise ) from tensorflow.keras.regularizers import l2 from tensorflow.keras import backend as K # Cell 2: Set logs directory LOG_DIR = "logs" # Cell 3: Utility function to build model # [`build-model` function for test model from introductory section here...] # Cell 4: Build the model model = build_model(398, 12, 335, 18) # Cell 5: Compile the model model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"]) # Cell 6: Create a TensorBoard callback tensorboard_callback = tf.keras.callbacks.TensorBoard( log_dir=LOG_DIR, histogram_freq=1, write_graph=True, profile_batch=0 # Disable profiling ) # Cell 7: Create dummy `x` and `y` training inputs that match model input and output shapes dummy_x_input = tf.random.normal((1, 398, 347)) # Batch size 1, input shape (398,347) dummy_y_input = tf.random.normal((1, 18)) # Batch size 1, input shape (18, ) # Cell 8: "Train" the model for zero epochs to create a conceptual graph of the model model.fit(dummy_x_input, dummy_y_input, epochs=0, batch_size=1, callbacks=[tensorboard_callback]) # Cell 9: Load the TensorBoard notebook extension %load_ext tensorboard # Cell 10: Launch TensorBoard %tensorboard --logdir $LOG_DIR --host localhost 上記のJupyterノートコードを実行する場合は、最後のセルが出力する必要があります。 セル実行が完了すると、Navigate to To view the ダッシュボード Launching TensorBoard http://localhost:6006 TensorBoard TensorBoard ポートを変更するには、 --port オプションを %tensorboard マジックコマンドに転送し、例えば %tensorboard --logdir $LOG_DIR --host localhost --port 8088 を変更できます。 TensorBoard ポートを変更できます。 オプション to the マジック・コマンド E.G. . --port %tensorboard %tensorboard --logdir $LOG_DIR --host localhost --port 8088 ヒント: Windows 10 で実行しているところで、TensorBoard に関して不思議な動作に気付きました。Jupyter ノートブックを実行するたびに TensorBoard を正しく起動させるには、まず C:\Users\[MY_WINDOWS_USERNAME]\AppData\Local\Temp\.tensorboard-info ディレクトリのすべての臨時ファイルを削除する必要があります。 私はWindows 10で実行していますが、TensorBoardに関して不思議な行動を観察しました。Jupyterノートブックを実行するたびにTensorBoardを適切に起動させるには、まず、Jupyterノートブックを実行するたびにすべての臨時ファイルを削除する必要があります。 ディレクター Tip: C:\Users\[MY_WINDOWS_USERNAME]\AppData\Local\Temp\.tensorboard-info 3.3 TensorBoard で Keras モデルを視覚化する TensorBoard は自動的に開きます。 ダッシュボード. If it does not, you can click on the メニューを選択するか、代替を選択できます。 ダウンロードメニューから Graphs Graphs Graphs から The ビュー 選択 モデルの構造を表示するには、最初にモデル全体を表す単一のノードを表示する必要があります。 Graphs Conceptual graph サブグラフ構造内の個々のノードをダブルクリックしてその属性を表示できます。TensorBoardはまた、モデルグラフを輸出することを可能にします。 フォーマット .png 結論 上記のあらゆる視覚化方法には、その利点と欠点があります。Netronは、訓練されたモデルと使用しやすいです。 TensorBoard は、未訓練のモデルでも使用できますが、適切に設定するにはもう少し作業が必要です。 visualkeras