张量流中的负尺寸尺寸错误

Negative dimension size error in tensorflow

所以我有 2 张图片,img1img2 都带有 shape=(20,20),我 expand_dims(1,20,20) 1 是批量大小和 feed他们连接到网络,但出现以下错误:

ValueError: Negative dimension size caused by subtracting 3 from 1 for '{{node conv2d/Conv2D}} = Conv2D[T=DT_FLOAT, data_format="NHWC", dilations=[1, 1, 1, 1], explicit_paddings=[], padding="VALID", strides=[1, 1, 1, 1], use_cudnn_on_gpu=true](Placeholder, conv2d/Conv2D/ReadVariableOp)' with input shapes: [?,1,20,20], [3,3,20,32]. ```

    def mean_squared_error(y_true, y_pred):
        return tf.keras.metrics.mean_squared_error(y_true, y_pred)
    
    model = Sequential()
    model.add(Conv2D(32, kernel_size=(3, 3),
                     activation='relu',
                     input_shape=(1,20,20)))
    model.add(Conv2D(1, kernel_size=(3, 3),
                     activation='relu'))
    
    model.compile(optimizer='adam', loss=mean_squared_error, metrics=[mean_squared_error, 'accuracy'])
    
    # Train
    
    model.fit(img1, img2)


卷积层减少了输入的维度,但是 IIUC,您正在尝试将 mse 应用于模型的输出和 img2。所以尝试这样的事情:

import tensorflow as tf

model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(32, kernel_size=(2, 2),
                  activation='relu',
                  input_shape=(20, 20, 1)))
model.add(tf.keras.layers.Conv2DTranspose(1, kernel_size=(2, 2),
                  activation='relu'))
model.compile(optimizer='adam', loss='mse', metrics=['mae'])

# Train
img1 = tf.random.normal((1, 20, 20))
img2 = tf.random.normal((1, 20, 20))
model.fit(img1, img2)