感谢查看我的问题。
例如,最终输出是两个矩阵A和B的总和,如下所示:
我尝试使用这些代码,但仍然遇到了一些问题:
1. 我如何使用自己的图层?
例如,最终输出是两个矩阵A和B的总和,如下所示:
output = keras.layers.add([A, B])
现在,我想建立一个新的参数x来改变输出结果。
我想让新的输出结果为Ax+B(1-x)
而且x是我的网络中一个可训练参数。
我该怎么做呢? 请帮帮我~ 非常感谢!
编辑(代码的一部分):
conv1 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(input)
drop1 = Dropout(0.5)(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(drop1)
conv2 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)
conv2 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)
drop2 = Dropout(0.5)(conv2)
up1 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop2))
#the line I want to change:
merge = add([drop2,up1])
#this layer is simply add drop2 and up1 layer.now I want to add a trainable parameter x to adjust the weight of thoese two layers.
我尝试使用这些代码,但仍然遇到了一些问题:
1. 我如何使用自己的图层?
merge = Mylayer()(drop2,up1)
还有其他方式吗?
2.out_dim的含义是什么? 这些参数都是三维矩阵。out_dim的含义是什么?
谢谢...T.T
编辑2(已解决)
from keras import backend as K
from keras.engine.topology import Layer
import numpy as np
from keras.layers import add
class MyLayer(Layer):
def __init__(self, **kwargs):
super(MyLayer, self).__init__(**kwargs)
def build(self, input_shape):
self._x = K.variable(0.5)
self.trainable_weights = [self._x]
super(MyLayer, self).build(input_shape) # Be sure to call this at the end
def call(self, x):
A, B = x
result = add([self._x*A ,(1-self._x)*B])
return result
def compute_output_shape(self, input_shape):
return input_shape[0]
model.summary()
是否报告该层中存在可训练参数。对于我来说,我必须在build()
中调用add_weight(shape=())
才能将权重正确添加到模型图中。shape=()
表示该权重是标量,您可以将其直接添加/乘/除到张量中。 - dant