一般在構建模型的時候,如果能在訓練之前就知道模型的參數量和結構圖,就能避免一些低級錯誤。常用的函數有summary和plot_model,下面就一個簡單的個例進行展示
另外,需要說明,在tensorflow 2.0版本中,tf.keras的用法和keras的用法基本一致,兩者的API說明文檔完全可以相互參考。這裏使用tf.keras
- summary的使用和保存
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import LSTM,Dense
from tensorflow.keras import Input,Model
num_encoder_tokens=10
latent_dim=20
num_decoder_tokens=15
def lstm_model():
# 定義編碼器的輸入
# encoder_inputs (None, num_encoder_tokens), None表示時間步
encoder_inputs = Input(shape=(None, num_encoder_tokens),name='encoder_inputs')
# 編碼器,return_sequences表示返回每個時間步的輸出,return_state表示返回最後一個時間步的h,c
encoder = LSTM(latent_dim, return_sequences=True,
return_state=True,name='encoder_lstm_1')
# 調用編碼器,得到編碼器的輸出(解碼器的輸入其實不需要),以及狀態信息 state_h 和 state_c
encoder_outpus, state_h, state_c = encoder(encoder_inputs)
# 丟棄encoder_outputs, 我們只需要編碼器的狀態
encoder_state = [state_h, state_c]
# 定義解碼器的輸入
# 同樣的,None表示可以處理任意長度的序列
decoder_inputs = Input(shape=(None, num_decoder_tokens),name='decoder_inputs')
# 接下來建立解碼器,解碼器將返回整個輸出序列
# 並且返回其中間狀態,中間狀態在訓練階段不會用到,但是在推理階段將是有用的
decoder_lstm = LSTM(latent_dim, return_sequences=True,
return_state=True,name='decoder_lstm1')
# 將編碼器輸出的狀態作爲初始解碼器的初始狀態
decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_state)
# 添加全連接層
decoder_dense = Dense(num_decoder_tokens, activation='softmax',name='decoder_Dense')
decoder_outputs = decoder_dense(decoder_outputs)
model=Model([encoder_inputs,decoder_inputs],decoder_outputs)
return model
lstm_test_model=lstm_model()
#line_length表示summary的輸出大小(長度),
lstm_test_model.summary(line_length=150,positions=[0.30,0.60,0.7,1.])
model的summary信息如下表:
包括四個信息,[layer_name,output_shape,params,connected_to],即[層名字,輸出維度大小,參數數量,該層的輸入和哪個層相連接],
sumarry中的參數line_length表示表長度,positions表示四個信息的位置(尾部位置)
上述代碼默認summary在屏幕上輸出,如果想將summary信息輸出成文件,使用下列代碼就行:
#這段代碼用來將model.summary() 輸出保存爲文件
from contextlib import redirect_stdout
with open('model_summary.txt', 'w') as f:
with redirect_stdout(f):
model.summary(line_length=200,positions=[0.30,0.60,0.7,1.0])
打開該文件,
2. plot_model
在使用plot_model畫結構圖之前,需要安裝一些必要的庫
下面是一些教程,可以試試
https://blog.csdn.net/qq_27825451/article/details/89338222 重點
https://blog.csdn.net/sinat_36811967/article/details/79220235
https://blog.csdn.net/weixin_42442855/article/details/89554612 重點
總結下來就是 不要安裝pydot,而是使用pydotplus庫
安裝pydotplus庫需要graphviz庫,這個庫的安裝,也可以使用下面教程
https://blog.csdn.net/weixin_43718675/article/details/88843534
#導入下面的庫
from tensorflow.keras.utils import plot_model
import pydotplus
#參數 :模型名稱,結構圖保存位置,是否展示shape
plot_model(lstm_test_model,to_file='lstm_test_model.png',show_shapes=True)
結構信息如下:
3. 獲取每層的layer維度信息
#輸出所以層的名字,輸入信息維度,輸出信息維度
for layer in lstm_test_model.layers:
print(layer.name)
print(layer.input_shape)
print(layer.output_shape)
print()