【TensorFlow2.0】 expected input_conv to have 4 dimensions, but got array... 錯誤解釋和解決方法

在使用TensorFlow2.0中自帶Keras進行訓練的時候,輸入的訓練集爲RGB三通道圖像,然而配置好網絡後使用 model.fit(x, ...)進行訓練時卻始終報如下錯誤

expected input_conv to have 4 dimensions, but got array... 

具體意思是輸入的參數x需要輸入4個參數,而訓練輸入卻只有3個維度,我的圖片維度爲(192, 192, 3)。

解決過程

首先先去了解了一下fit函數的x究竟是什麼,TensorFlow官網給出的解釋如下

x: Input data. It could be:

  • A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs).
  • A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs).
  • A dict mapping input names to the corresponding array/tensors, if the model has named inputs.
  • tf.data dataset. Should return a tuple of either (inputs, targets) or (inputs, targets, sample_weights).
  • A generator or keras.utils.Sequence returning (inputs, targets) or (inputs, targets, sample weights).

X:輸入數據。它應該爲
Numpy數組(或類似數組) 或 如果模型有多個輸入即數組列表。
如果模型有多個輸入,即爲TensorFlow張量或張量列表。
如果模型具有命名輸入,則將輸入名稱映射到相應的數組/張量的字典。
tf.data數據集。應返回(INPUTS,TARGETS)或(INPUTS,TARGET,SAMPLE_WEIGHT)的元組。
生成器或keras.utils.Sequence返回(輸入,目標)或(輸入,目標,樣本權重)。

結合其他講解,瞭解到輸入的數據應該是四個維度(數據集個數,Batch_Size 長度, 寬度, 通道數)

一開始我認爲這就是僅僅一個四維的元組而已,就想着通過 tf.expand_dims() 函數爲其添加一個維度

結果是的確添加了一個維度,圖片變爲(1, 192, 192, 3),然而還是有錯誤,便想把x的第一個參數改成Batch_Size的值卻死活改不了,後來冷靜下來想了一下,48*192*192*3怎麼也不可能等於1*192*192*3,怎麼改呀?

解決措施

使用 tf.stack 命令把輸入的所有圖片集合合併成一個tensor,就可以訓練了。

因此對model.fit第一個參數x的理解應該是Batch_Size個數據集合並而成的tensor。

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