tensorflow2.1.0——Squential文檔解讀

在這裏插入圖片描述

在Squential列表裏邊可以有選擇性的寫input_shape參數,下面介紹介紹幾種寫法,任選其一即可,選擇自己習慣的常用。

  • (1) 當我們選擇在第一層聲明input_shape時,有以下幾種寫法
  • 這種寫法會讓模型從一開始就有網絡參數,並隨着網絡深度的增加,後面會自動地隨機初始化對應shape地權重
##  寫法1
model = Sequential()
model.add(Dense(32, input_shape=(500,)))

## 寫法2
model = Sequential()
model.add(Dense(32, input_dim=500))

## 寫法3
model = Sequential()
model.add(Dense(32, batch_input_shape=(None, 500)))

## 寫法4
model = Squential([
	Dense(32,input_shape//input_dim//batch_input_shape=(500,)//500//(None,500))
])
  • (2) 當我們選擇在第一層不聲明input_shape時,有以下幾種寫法
  • In that case the model gets built the first time you call fit (or other
    training and evaluation methods)
  • 模型會通過fit函數或者其他訓練或者評估地過程來構建網絡,言外之意就是就要給了數據,我就可以構建網絡了
model = Sequential()
model.add(Dense(32))
model.add(Dense(32))
model.weights # empty[]
model.compile(optimizer=optimizer, loss=loss)
# This builds the model for the first time:
model.fit(x, y, batch_size=32, epochs=10)

# Alternative way,we just give data to model
data = tf.ones(shape=(3,3))
out = model(data) # 調用Model類地call函數進行前向傳播
model.weights   # not empty[weights values]

# Another way :通過調用build函數進行手工構建build(batch_input_shape)
model = Sequential()
model.add(Dense(32))
model.add(Dense(32))
model.build((None, 500))  # None表示batch_size,可以表示爲任意地維度,等待接收。
model.weights  # returns list of length 4

寫在後面

瞭解神經網絡地輸入的shape非常重要,如果不瞭解清楚我們的data的shape和神經網絡的shape是否相配,會導致網絡的混亂。還有很重要一點要搞清楚參數是否包含batch_size的大小!
要注意兩個參數的不同:
①input_shape:不包含batch_size
②batch_input_shape:包含batch_size,在一般情況下,都寫成None。當然,在非常具體的情況下可以寫爲具體的數字。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章