我想要自定义Keras层,实现两个模型的输出分配不同的权重,并且权重可以如下训练
prediction1=model1.output
prediction2=model2.output
class WeightedSum(Layer):
def __init__(self,**kwargs):
super(WeightedSum, self).__init__(**kwargs)
def build(self, input_shape):
self.weights =K.variable(np.random.random(1))
self.trainable_weights=[self.weights]
def call(self, two_model_outputs):
return self.weights * two_model_outputs[0] + (1 - self.weights) * two_model_outputs[1]
def compute_output_shape(self, input_shape):
return input_shape[0]
final_pred=WeightedSum()([prediction1,prediction2])
Traceback (most recent call last):
File "test-paper3.py", line 182, in <module>
final_pred=WeightedSum()([prediction1,prediction2])
File "/root/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py", line 431, in __call__
self.build(unpack_singleton(input_shapes))
File "test-paper3.py", line 162, in build
self.weights =K.variable(np.random.random(1))
AttributeError: can't set attribute