Skip to main content
 首页 » 编程设计

python之计算两层的差异

2024年10月17日6jpfss

我想合并两个 keras 层,使合并后的层具有两个层的差异。例如,如果第 1 层输出为 [0,1,2],第 2 层输出为 [1,2,3],则合并层应为 [-1,-1,-1]。我尝试使用以下内容

from keras.layers import Input, merge 
from keras.models import Model 
import numpy as np 
 
input_a = np.reshape([1, 2, 3], (1, 1, 3)) 
input_b = np.reshape([4, 5, 6], (1, 1, 3)) 
 
a = Input(shape=(1, 3)) 
b = Input(shape=(1, 3)) 
 
 
diff = merge([a, b], mode=lambda x, y: x - y) 
 
diff_model = Model(input=[a, b], output=diff) 
 
print(diff_model.predict([input_a, input_b])) 

导致以下错误,

  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1464, in merge                │    self.add_inbound_node(layers, node_indices, tensor_indices) 
    name=name)                                                                                               │  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topolog 
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1123, in __init__             │y.py", line 543, in add_inbound_node 
    self.add_inbound_node(layers, node_indices, tensor_indices)                                              │    Node.create_node(self, inbound_layers, node_indices, tensor_ind 
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 543, in add_inbound_node      │ices) 
    Node.create_node(self, inbound_layers, node_indices, tensor_indices)                                     │  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topolog 
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 153, in create_node           │y.py", line 155, in create_node 
    output_tensors = to_list(outbound_layer.call(input_tensors, mask=input_masks))                           │    output_shapes = to_list(outbound_layer.get_output_shape_for(inp 
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1200, in call                 │ut_shapes)) 
    return self.mode(inputs, **arguments)                                                                    │  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topolog 
TypeError: <lambda>() takes exactly 2 arguments (1 given)   

如何执行合并操作?

请您参考如下方法:

我能够以上述方式合并图层,

diff = merge([a, b], mode=lambda (x, y): x - y, output_shape=(3,))