簡體   English   中英

如何可視化具有訓練權重的 keras 神經網絡?

[英]How to visualize a keras neural network with trained weights?

我使用類似於此的 keras 創建了一個順序 model,

    model = Sequential()
    
    # Adding the input layer and the first hidden layer
    model.add(Dense(6, activation='relu',input_dim = 11))
    
    # Adding the second hidden layer (The real model contains many hidden layers)
    model.add(Dense(6,activation='relu')) 
    # Adding the output layer
    model.add(Dense( 1, activation = 'sigmoid'))

然后我編譯它並訓練它

    # Compiling the ANN
    classifier.compile(optimizer = 'Adamax', loss = 'binary_crossentropy',metrics=['accuracy'])
    model_history=classifier.fit(X_train, y_train.to_numpy(), batch_size = 10, epochs = 100)

然后我使用 keras 可視化器來獲得沒有權重的神經網絡的可視化。

    from keras_visualizer import visualizer
    visualizer(model, filename='net', format='png', view=True)

我想將 model 的訓練權重打印到這種可視化中。 有沒有我可以使用的庫或模塊? 任何建議都會有所幫助。 這是沒有打印權重的設計神經網絡的圖片。

在此處輸入圖像描述

我想將 model 的訓練權重打印到這種可視化中。 有沒有我可以使用的庫或模塊?

選項1:

有一個包\模塊形式的解決方法,即所謂的Deep Replay ,您可以將其作為庫導入以解決您的問題。

多虧了這個 package,您可以使用以下示例可視化\動畫並最有可能打印經過訓練的權重:

# install FFMPEG (to generate animations)
#!apt-get install ffmpeg

# install actual deepreplay package
#!pip install deepreplay

from keras.initializers import glorot_normal, glorot_uniform, he_normal, he_uniform
from keras.layers import Dense
from keras.models import Sequential
from deepreplay.callbacks import ReplayData
from deepreplay.datasets.ball import load_data
from deepreplay.plot import compose_plots, compose_animations
from deepreplay.replay import Replay

from matplotlib import pyplot as plt

plt.rcParams['animation.ffmpeg_path'] = '/usr/bin/ffmpeg'

X, y = load_data(n_dims=10)

activation = 'relu'
initializer_name = 'he_uniform'
initializer = eval(initializer_name)(seed=13)
title = 'Activation: ReLU - Initializer: {}'.format(initializer_name)
group_name = 'relu_{}'.format(initializer_name)
filename = f'{group_name}_{initializer_name}_{activation}_weight_initializers.h5'

# Model builder function
def build_model(n_layers, input_dim, units, activation, initializer):
    if isinstance(units, list):
        assert len(units) == n_layers
    else:
        units = [units] * n_layers

    model = Sequential()
    # Adds first hidden layer with input_dim parameter
    model.add(Dense(units=units[0],
                    input_dim=input_dim,
                    activation=activation,
                    kernel_initializer=initializer,
                    name='h1'))

    # Adds remaining hidden layers
    for i in range(2, n_layers + 1):
        model.add(Dense(units=units[i-1],
                        activation=activation,
                        kernel_initializer=initializer,
                        name='h{}'.format(i)))

    # Adds output layer
    model.add(Dense(units=1, activation='sigmoid', kernel_initializer=initializer, name='o'))
    # Compiles the model
    model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['acc'])
    return model


replaydata = ReplayData(X, y, filename=filename, group_name=group_name)

# Create the MLP model with 5 layers within 10 input neurons and 100 unists in hidden and output layers
model = build_model(n_layers=5, input_dim=10, units=100, activation=activation, initializer=initializer)

# fit the model over 10 epochs with batch size of 16
model.fit(X, y, epochs=10, batch_size=16, callbacks=[replaydata])

# Plot the results
replay = Replay(replay_filename=filename, group_name=group_name)

fig = plt.figure(figsize=(12, 6))
ax_zvalues = plt.subplot2grid((2, 2), (0, 0))
ax_weights = plt.subplot2grid((2, 2), (0, 1))
ax_activations = plt.subplot2grid((2, 2), (1, 0))
ax_gradients = plt.subplot2grid((2, 2), (1, 1))

wv = replay.build_weights(ax_weights)
gv = replay.build_gradients(ax_gradients)

# Z-values
zv = replay.build_outputs(ax_zvalues, before_activation=True,
                          exclude_outputs=True, include_inputs=False)
# Activations
av = replay.build_outputs(ax_activations, exclude_outputs=True, include_inputs=False)

# Save plots
fig = compose_plots([zv, wv, av, gv], epoch=0, title=title)
fig.savefig('part2.png', format='png', dpi=120)

# Animate & save mp4
sample_anim = compose_animations([zv, wv, av, gv])
sample_anim.save('part2.mp4', dpi=120, fps=5)

為了簡單,使用超過 10 個時期的小提琴圖來可視化 output 結果:圖像 因此,右上角的子圖顯示了十個時期內各層的權重變化。 其他子圖說明了 Z 值、激活函數和梯度變化的性能。

注1:如果您有興趣解讀小提琴情節,請查看以下帖子: post1post2post3

注意2:請注意,訓練過程從一些初始化器開始,它們在開始時可能有不同的權重。 常見的初始化方案如下:

  • 隨機的
  • 澤維爾/格洛羅

默認情況下,當您使用模塊(參考)時,kernel 初始化程序是glorot_uniform ,但您可以查看這篇文章和這篇文章了解訓練深度前饋神經網絡的難度以獲取更多信息。 也可以手動初始化 NN 中的權重。 你可以查看這篇文章

注意3:最近這個package有一個bug,無法在Google Colab Notebook中實現,這仍然是一個懸而未決的問題; 它的GH Repo以及在SoF中的帖子。 所以最好在你自己的本地機器上嘗試一下,希望如此。

選項2:

還有另一個基於 ML 的工具,即所謂的W&B(權重和偏差) ,您可以將其作為庫導入以解決您的問題。

根據說明注冊並登錄帳戶后,您可以使用此 API 跟蹤和可視化您的 ML 管道的所有部分,包括權重和偏差以及管道中的其他參數:

import wandb
from wandb.keras import WandbCallback

# Step1: Initialize W&B run
wandb.init(project='project_name')

# 2. Save model inputs and hyperparameters
config = wandb.config
config.learning_rate = 0.01

# Model training code here ...
import tensorflow as tf
from tensorflow import keras
loss=tf.keras.losses.MeanSquaredError()
Optimiser=tf.keras.optimizers.Adam(learning_rate =0.001)
model.compile(loss=loss, optimizer=Optimiser, metrics=['accuracy'])
wandb.log({"loss": loss})

# Step 3: Add WandbCallback 
model.fit(X, y, epochs=10, batch_size=16, callbacks=[WandbCallback()])

運行model ,您可以檢查Model部分中的圖形信息,該部分已選擇\在左側以藍色顯示:

圖像

希望這個答案對您有所幫助,如果是這樣,您可以接受它作為答案✅。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM