创建模型将引发“ AttributeError:'Tensor'对象没有属性'_keras_history'”

时间:2019-05-12 05:15:01

标签: python tensorflow keras

当我使用keras.models.Model()创建模型时,出现以下错误:

  

AttributeError:“张量”对象没有属性“ _keras_history”

我在模型中创建了3个MLP,并且意图是形状为(6040,100)的张量。

代码和完整的回溯如下:

def get_model(num_users,num_items,layers_1=[10],
              layers_2=[10],layers_3=[10],reg_layers_1=[0],
              reg_layers_2=[0],reg_layers_3=[0]):
    assert len(layers_1) == len(reg_layers_1)
    assert len(layers_2) == len(reg_layers_2)
    assert len(layers_3) == len(reg_layers_3)

    num_layer_1 = len(layers_1)
    num_layer_2 = len(layers_2)
    num_layer_3 = len(layers_3)

    intents = scaled_dotproduct_attention(user_bought_sorted[0],100)
    for i in range(1,len(user_bought_sorted)):
        temp = scaled_dotproduct_attention(user_bought_sorted[i],100)
        intents = concatenate([intents,temp],0)

    #intents = tf.reshape(intents,[-1,100])

    user_input = Input(shape=(1,),dtype='int32',name='user_input')
    item_input = Input(shape=(1,),dtype='int32',name='item_input')

    mlp_embedding_user = Embedding(input_dim=num_users,output_dim=100,name='mlp_embedding_user',
                                   embeddings_initializer=initializers.random_normal(),
                                   embeddings_regularizer=l2(reg_layers_1[0]),input_length=1)
    mlp_embedding_item = Embedding(input_dim=num_items,output_dim=100,name='mlp_embedding_items',
                                   embeddings_initializer=initializers.random_normal(),
                                   embeddings_regularizer=l2(reg_layers_1[0]),input_length=1)
    attention_embedding_item = Embedding(input_dim=num_items,output_dim=100,name='attention_embedding_items',
                                         embeddings_initializer=initializers.random_normal(),
                                         embeddings_regularizer=l2(reg_layers_2[0]),input_length=1)
    #attention_embedding_intent = Embedding(input_dim=num_users,output_dim=100,name='attention_embedding_intent',
    #                                       embeddings_initializer=initializers.random_normal(),
    #                                       embeddings_regularizer=l2(reg_layers_2[0]),input_length=1)

    #MLP_1
    mlp_user_latent = Flatten()(mlp_embedding_user(user_input))
    mlp_item_latent = Flatten()(mlp_embedding_item(item_input))
    mlp_vector = concatenate([mlp_user_latent,mlp_item_latent])
    for idx in range(1,num_layer_1):
        layer_1 = Dense(layers_1[idx],kernel_regularizer=l2(reg_layers_1[idx]),
                        activation='relu',name='layer_1%d' % idx)
        mlp_vector = layer_1(mlp_vector)

    #MLP_attention
    attention_item_latent = Flatten()(attention_embedding_item(item_input))
    #attention_intent_latent = Reshape((100,))(intents)
    attention_vector = K.dot(attention_item_latent,K.transpose(intents))

    for adx in range(1,num_layer_2):
        layer_2 = Dense(layers_2[adx],kernel_regularizer=l2(reg_layers_2[adx]),
                        activation='relu',name='layer_2%d' % adx)
        attention_vector = layer_2(attention_vector)

    #MLP_intents
    intents_vector = concatenate([mlp_vector,attention_vector])
    for ndx in range(num_layer_3):
        layer_3 = Dense(layers_3[ndx],kernel_regularizer=l2(reg_layers_3[ndx]),
                        activation='relu',name='layer_3%d' % ndx)
        intents_vector = layer_3(intents_vector)

    prediction = Dense(1,activation='sigmoid',kernel_initializer=initializers.lecun_normal(),
                       name='prediction')(intents_vector)

    model = Model(inputs=[user_input, item_input], outputs=prediction)

    return model






    model = get_model(num_users,num_items,layers_1=[64,32,16,8],
                  layers_2=[64,32],layers_3=[64,32,16],
                  reg_layers_1=[0,0,0,0],reg_layers_2=[0,0],
                  reg_layers_3=[0,0,0])

和完整的追溯:

AttributeError                            Traceback (most recent call last)
<ipython-input-121-25ef0dd05d42> in <module>
      2                   layers_2=[64,32],layers_3=[64,32,16],
      3                   reg_layers_1=[0,0,0,0],reg_layers_2=[0,0],
----> 4                   reg_layers_3=[0,0,0])

<ipython-input-120-d2a66d53e76f> in get_model(num_users, num_items, layers_1, layers_2, layers_3, reg_layers_1, reg_layers_2, reg_layers_3)
     62                        name='prediction')(intents_vector)
     63 
---> 64     model = Model(inputs=[user_input, item_input], outputs=prediction)
     65 
     66     return model

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     85                 warnings.warn('Update your `' + object_name +
     86                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 87             return func(*args, **kwargs)
     88         wrapper._original_function = func
     89         return wrapper

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/engine/topology.py in __init__(self, inputs, outputs, name)
   1714         nodes_in_progress = set()
   1715         for x in self.outputs:
-> 1716             build_map_of_graph(x, finished_nodes, nodes_in_progress)
   1717 
   1718         for node in reversed(nodes_in_decreasing_depth):

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/engine/topology.py in build_map_of_graph(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1704                 tensor_index = node.tensor_indices[i]
   1705                 build_map_of_graph(x, finished_nodes, nodes_in_progress,
-> 1706                                    layer, node_index, tensor_index)
   1707 
   1708             finished_nodes.add(node)

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/engine/topology.py in build_map_of_graph(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1704                 tensor_index = node.tensor_indices[i]
   1705                 build_map_of_graph(x, finished_nodes, nodes_in_progress,
-> 1706                                    layer, node_index, tensor_index)
   1707 
   1708             finished_nodes.add(node)

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/engine/topology.py in build_map_of_graph(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1704                 tensor_index = node.tensor_indices[i]
   1705                 build_map_of_graph(x, finished_nodes, nodes_in_progress,
-> 1706                                    layer, node_index, tensor_index)
   1707 
   1708             finished_nodes.add(node)

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/engine/topology.py in build_map_of_graph(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1704                 tensor_index = node.tensor_indices[i]
   1705                 build_map_of_graph(x, finished_nodes, nodes_in_progress,
-> 1706                                    layer, node_index, tensor_index)
   1707 
   1708             finished_nodes.add(node)

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/engine/topology.py in build_map_of_graph(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1704                 tensor_index = node.tensor_indices[i]
   1705                 build_map_of_graph(x, finished_nodes, nodes_in_progress,
-> 1706                                    layer, node_index, tensor_index)
   1707 
   1708             finished_nodes.add(node)

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/engine/topology.py in build_map_of_graph(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1704                 tensor_index = node.tensor_indices[i]
   1705                 build_map_of_graph(x, finished_nodes, nodes_in_progress,
-> 1706                                    layer, node_index, tensor_index)
   1707 
   1708             finished_nodes.add(node)

~/Desktop/100_server_venv/lib/python3.6/site-packages/keras/engine/topology.py in build_map_of_graph(tensor, finished_nodes, nodes_in_progress, layer, node_index, tensor_index)
   1675             """
   1676             if not layer or node_index is None or tensor_index is None:
-> 1677                 layer, node_index, tensor_index = tensor._keras_history
   1678             node = layer.inbound_nodes[node_index]
   1679 

AttributeError: 'Tensor' object has no attribute '_keras_history'

1 个答案:

答案 0 :(得分:0)

您不能直接在Keras张量中使用后端函数,这些张量中的每个操作都必须是一层。您需要将每个自定义操作包装在Lambda层中,并为该层提供适当的输入。