我知道我们可以使用get_layer()建立一个新模型,但是我的问题有点不同:
我简化了模型:
import keras
import numpy as np
a = np.array([[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]])
x = keras.layers.Input(shape=(6,))
y = keras.layers.Lambda(lambda x: x * 1)(x)
z = keras.layers.Lambda(lambda x: x * 1)(y[:,4])
model = keras.Model(x,[y,z])
model.compile(optimizer='sgd',loss='mean_squared_error')
model.predict(a)
如果我删除“ z”行,则该模型运行正常。否则会遇到以下错误:
AttributeError Traceback (most recent call last)
<ipython-input-74-7fc86ac55867> in <module>()
----> 1 model = keras.Model(x,[y,z])
2 model.compile(optimizer='sgd',loss='mean_squared_error')
~/.conda/envs/21/lib/python3.6/site-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
89 warnings.warn('Update your `' + object_name +
90 '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 91 return func(*args, **kwargs)
92 wrapper._original_function = func
93 return wrapper
~/.conda/envs/21/lib/python3.6/site-packages/keras/engine/network.py in __init__(self, *args, **kwargs)
89 'inputs' in kwargs and 'outputs' in kwargs):
90 # Graph network
---> 91 self._init_graph_network(*args, **kwargs)
92 else:
93 # Subclassed network
~/.conda/envs/21/lib/python3.6/site-packages/keras/engine/network.py in _init_graph_network(self, inputs, outputs, name)
233 # Keep track of the network's nodes and layers.
234 nodes, nodes_by_depth, layers, layers_by_depth = _map_graph_network(
--> 235 self.inputs, self.outputs)
236 self._network_nodes = nodes
237 self._nodes_by_depth = nodes_by_depth
~/.conda/envs/21/lib/python3.6/site-packages/keras/engine/network.py in _map_graph_network(inputs, outputs)
1410 layer=layer,
1411 node_index=node_index,
-> 1412 tensor_index=tensor_index)
1413
1414 for node in reversed(nodes_in_decreasing_depth):
~/.conda/envs/21/lib/python3.6/site-packages/keras/engine/network.py in build_map(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
1397 tensor_index = node.tensor_indices[i]
1398 build_map(x, finished_nodes, nodes_in_progress, layer,
-> 1399 node_index, tensor_index)
1400
1401 finished_nodes.add(node)
~/.conda/envs/21/lib/python3.6/site-packages/keras/engine/network.py in build_map(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
1369 ValueError: if a cycle is detected.
1370 """
-> 1371 node = layer._inbound_nodes[node_index]
1372
1373 # Prevent cycles.
AttributeError: 'NoneType' object has no attribute '_inbound_nodes'
有人可以告诉我为什么会发生这种情况以及如何解决吗? 谢谢!
答案 0 :(得分:0)
只需在Lambda
层中切张量:
a = np.array([[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6]])
x = keras.layers.Input(shape=(6,))
y = keras.layers.Lambda(lambda x: x * 1)(x)
z = keras.layers.Lambda(lambda x: x[:, 4] * 1)(y)
model = keras.Model(x, [y, z])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.predict(a)