Python 如何修改Keras张量对象的元素

Python 如何修改Keras张量对象的元素,python,tensorflow,keras,conv-neural-network,tf.keras,Python,Tensorflow,Keras,Conv Neural Network,Tf.keras,我正在Keras中构建一个卷积神经网络,该网络接收一批尺寸为(无、256、256、1)的图像,并输出一批大小为(无、256、256、3)的图像。现在在最后一层输出之后,我想添加一个层,根据输入上的值条件为输出层中的一些像素赋值。以下是我尝试过的: 功能 def SetBoundaries(ins): xi = ins[0] xo = ins[1] bnds = np.where(xi[:, :, :, 0] == 0) bnds_s, bnds_i, bnds_

我正在Keras中构建一个卷积神经网络,该网络接收一批尺寸为(无、256、256、1)的图像,并输出一批大小为(无、256、256、3)的图像。现在在最后一层输出之后,我想添加一个层,根据输入上的值条件为输出层中的一些像素赋值。以下是我尝试过的:

功能

def SetBoundaries(ins):
    xi = ins[0]
    xo = ins[1]

    bnds = np.where(xi[:, :, :, 0] == 0)
    bnds_s, bnds_i, bnds_j = bnds[0], bnds[1], bnds[2]
    xo[bnds_s, bnds_i, bnds_j, 0] = 0
    xo[bnds_s, bnds_i, bnds_j, 1] = 0
    xo[bnds_s, bnds_i, bnds_j, 2] = 0

    return xo
Keras车型

def conv_res(inputs):
    x0 = inputs

    ...

    xc = conv_layer(xc, kernel_size=3, stride=1,
                    num_filters=3, name="Final_Conv")

    # apply assignment function
    xc = Lambda(SetBoundaries, name="assign_boundaries")([x0, xc])
    return xc
最后,利用该方法建立了模型

def build_model(inputs):
    xres = int(inputs.shape[1])
    yres = int(inputs.shape[2])
    cres = int(inputs.shape[3])

    inputs = Input((xres, yres, cres))
    outputs = UNet.conv_res(inputs)
    model = keras.Model(inputs=inputs, outputs=outputs)
    return model
但是,当我运行时,会出现以下错误:

NotImplementedError: Cannot convert a symbolic Tensor (assign_boundaries/Equal:0) to a numpy array.
没有Lambda函数,一切正常。我知道问题是给张量对象赋值,但我怎样才能达到我想要的


谢谢

np。其中
适用于NumPy数组,但您的模型的输出是Tensorflow张量。尝试使用,这是相同的事情,但是对于
tf.Tensor
s

np。其中
适用于NumPy数组,但模型的输出是Tensorflow张量。尝试使用,这是相同的事情,但是对于
tf.Tensor
s

我将函数更改为:

def SetBoundaries(ins):
    xi = ins[0]
    xo = ins[1]

    xin = tf.broadcast_to(xi, tf.shape(xo))
    mask = K.cast(tf.not_equal(xin, 0), dtype="float32")
    xf = layers.Multiply()([mask, xo])

    return xf

我将功能更改为:

def SetBoundaries(ins):
    xi = ins[0]
    xo = ins[1]

    xin = tf.broadcast_to(xi, tf.shape(xo))
    mask = K.cast(tf.not_equal(xin, 0), dtype="float32")
    xf = layers.Multiply()([mask, xo])

    return xf