簡體   English   中英

導致 INVALID_ARGUMENT 的 RandomCrop:需要可廣播的形狀

[英]RandomCrop causing INVALID_ARGUMENT: required broadcastable shapes

我正在使用 Keras 訓練神經網絡,並嘗試使用RandomCrop層。 我使用的是動態大小的數據集(分辨率不同),但我發現它目前不是導致此問題的原因。

當我運行model.fit()時,不久后,我收到上述錯誤INVALID_ARGUMENT: required broadcastable shapes 我能夠得到我的 model 的摘要,所以這不是什么不匹配。

當我刪除該層時,我的 model 工作正常,但我需要它來減小輸入的大小(因此使用RandomCrop )。

完整回溯 + tensorflow 狀態

2022-03-23 13:27:28.772937: W tensorflow/core/framework/op_kernel.cc:1733] INVALID_ARGUMENT: required broadcastable shapes

Traceback (most recent call last):
  File "c:\Users\samue\Desktop\rcrop\main.py", line 37, in <module>
    conv_model.fit(
  File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\tensorflow\python\eager\execute.py", line 54, in quick_execute
    tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error:

Detected at node 'mean_squared_error/SquaredDifference' defined at (most recent call last):
    File "C:\Program Files\Python310\lib\threading.py", line 966, in _bootstrap
      self._bootstrap_inner()
    File "C:\Program Files\Python310\lib\threading.py", line 1009, in _bootstrap_inner
      self.run()
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\engine\training.py", line 1000, in run_step
      outputs = model.train_step(data)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\engine\training.py", line 860, in train_step
      loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\engine\training.py", line 918, in compute_loss
      return self.compiled_loss(
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\engine\compile_utils.py", line 201, in __call__
      loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\losses.py", line 141, in __call__
      losses = call_fn(y_true, y_pred)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\losses.py", line 245, in call
      return ag_fn(y_true, y_pred, **self._fn_kwargs)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\losses.py", line 1329, in mean_squared_error
      return backend.mean(tf.math.squared_difference(y_pred, y_true), axis=-1)
Node: 'mean_squared_error/SquaredDifference'
Detected at node 'mean_squared_error/SquaredDifference' defined at (most recent call last):
    File "C:\Program Files\Python310\lib\threading.py", line 966, in _bootstrap
      self._bootstrap_inner()
    File "C:\Program Files\Python310\lib\threading.py", line 1009, in _bootstrap_inner
      self.run()
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\engine\training.py", line 1000, in run_step
      outputs = model.train_step(data)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\engine\training.py", line 860, in train_step
      loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\engine\training.py", line 918, in compute_loss
      return self.compiled_loss(
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\engine\compile_utils.py", line 201, in __call__
      loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\losses.py", line 141, in __call__
      losses = call_fn(y_true, y_pred)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\losses.py", line 245, in call
      return ag_fn(y_true, y_pred, **self._fn_kwargs)
    File "C:\Users\samue\AppData\Roaming\Python\Python310\site-packages\keras\losses.py", line 1329, in mean_squared_error
      return backend.mean(tf.math.squared_difference(y_pred, y_true), axis=-1)
Node: 'mean_squared_error/SquaredDifference'
2 root error(s) found.
  (0) INVALID_ARGUMENT:  required broadcastable shapes
         [[{{node mean_squared_error/SquaredDifference}}]]
         [[div_no_nan/ReadVariableOp/_84]]
  (1) INVALID_ARGUMENT:  required broadcastable shapes
         [[{{node mean_squared_error/SquaredDifference}}]]
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_1308]

如何重現

我創建了一個最小的可重現示例,只有兩張分辨率為[10, 10]的圖像都保存為.png和 rgb 色彩空間。

運行 main.py 加載這些圖像並嘗試開始訓練(失敗並出現錯誤)。

當我排除RandomCrop層時,它工作得很好。

文件夾結構

/main_folder
--main.py
--/data
   --001.png
   --002.png

主程序

import cv2, os
import keras
import tensorflow as tf
from keras import layers


strategy = tf.distribute.MirroredStrategy()

with strategy.scope():
    input_layer = keras.Input(shape=(None, None, 3))
    cropped = layers.RandomCrop(32, 32)(input_layer)
    out = layers.Conv2D(3, (3, 3), activation='sigmoid', padding='same')(cropped)

    conv_model = keras.Model(input_layer, out)
    conv_model.compile(
        optimizer='adam', 
        loss=tf.keras.losses.MeanSquaredError()
    )

conv_model.summary()

path = "data"
data = [cv2.imread(os.path.join(path, f)) / 255 for f in os.listdir(os.path.join(path))]


def data_generator():
    for i in range(len(data)):
        yield data[i], data[i]


dataset = tf.data.Dataset.from_generator(
    data_generator, 
    output_types=(tf.float32, tf.float32), 
    output_shapes=((None, None, 3), (None, None, 3))
).batch(1)

conv_model.fit(
    dataset,
    epochs=1,
    validation_data=dataset
)

所以,我想將其用於自動編碼器(在示例中)。 這意味着,我必須對輸入圖像和比較圖像進行相同的裁剪。 這聽起來不像是RandomCrop可以做的事情,但由於我已經在使用自定義生成器,所以我可以在那里實現它:

def data_generator():
    for i in range(len(data)):
        # Custom function to determine the patch size
        x, x1, y, y1 = randomly_choose(data[i].shape)
        yield data[i][x: x1, y: y1], data[i][x: x1, y: y1]

這讓我可以完全控制生成過程,允許我進行圖像翻轉、旋轉和其他更改。

暫無
暫無

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

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