涉及卷积的张量流中的自定义损失函数

Custom loss function in tensorflow involving convolution

我正在尝试使用图像与内核的卷积来实现自定义损失函数,这与 所做的非常相似。我已经准备好我的数据格式为 (batch_size, height, width, channels)。专门针对我的情况,这将是 (5, 500, 500, 3).

我正在使用的 2D 内核示例:
[0 0 0; -1 0 1; 0 0 0] 频道 0
[0 1 0; 0 0 0; 0 -1 0] 频道 1
[0 0 0; 0 1 0; 0 0 0] 频道 2

我想用不同的内核对每个通道进行卷积,然后总结结果。这将对批次中的 5 个图像中的每一个进行。结果应该是只有 1 个通道的 5 500x500 图像,因此输出的形状可以是 (batch_size, height, width, 1)(batch_size, height, width).

为了全面了解我正在尝试做的事情,我打算使用不同的过滤器集将上述过程再重复 2 次。所以现在我将有 3 个形状为 (batch_size, height, width, 1) 的输出,我可以将其叠加以获得形状为 (batch_size, height, width, 3) 的张量。这与原始张量的形状相同。之后,我将与另一个张量进行元素乘积并求和以计算损失值。

我找到了几个二维卷积函数:tf.nn.conv2d and tf.keras.backend.conv2d and tf.keras.layers.Conv2D。哪一个适合这个目的?使用单个 3x3x3 内核进行卷积是否更好?或者可能是 3x3x3 内核的 3D 卷积?

如果能提供一个简单的例子或者link,那就太好了!这是一个模板

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import backend as K

def my_loss(y_true, y_pred):
    kernelx0 = tf.convert_to_tensor(np.array([[0, 0, 0], [-1, 0, 1], [0, 0, 0]]))
    kernely0 = tf.convert_to_tensor(np.array([[0, 1, 0], [0, 0, 0], [0, -1, 0]]))
    kernelz0 = tf.convert_to_tensor(np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]))

    kernelx1 = ...
    kernely1 = ...
    kernelz1 = ...

    kernelx2 = ...
    kernely2 = ...
    kernelz2 = ...

    # how to do convolution?

    return loss

试试这个方法:

#this is your custom filter
kernel_in = tf.constant([[[0, 0, 0], [-1, 0, 1], [0, 0, 0]],
                  [[0, 1, 0], [0, 0, 0], [0, -1, 0]],
                  [[0, 0, 0], [0, 1, 0], [0, 0, 0]]], 
                  dtype=tf.float32)

kernel_in = tf.expand_dims(kernel_in,axis=-1) #expand this into a 4D tensor
#print(kernel_in.shape) #shape = (3,3,3,1)

out = tf.nn.conv2d(x_in, kernel_in, strides=[1, 1], padding='VALID') #x_in is your input