“激活”类型的对象没有len()

2024-05-02 09:29:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Keras构建我的GraphSAGE模型,但出现以下错误:

/Users/name/anaconda3/envs/tf/bin/python /Users/name/PycharmProjects/keras_autoencoder/NodeEmbeddings.py
Using TensorFlow backend.
2020-03-26 22:35:08.640725: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2020-03-26 22:35:08.655308: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7f9aa4872710 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-03-26 22:35:08.655323: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
link_classification: using 'ip' method to combine node embeddings into edge embeddings
/Users/name/PycharmProjects/keras_autoencoder/NodeEmbeddings.py:65: UserWarning: Update your `Model` call to the Keras 2 API: `Model(inputs=[<tf.Tenso..., outputs=Tensor("re...)`
  model = Model(input=x_inp, output=prediction)
Traceback (most recent call last):
  File "/Users/name/PycharmProjects/keras_autoencoder/NodeEmbeddings.py", line 65, in <module>
    model = Model(input=x_inp, output=prediction)
  File "/Users/name/anaconda3/envs/tf/lib/python3.6/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "/Users/name/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/network.py", line 94, in __init__
    self._init_graph_network(*args, **kwargs)
  File "/Users/name/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/network.py", line 241, in _init_graph_network
    self.inputs, self.outputs)
  File "/Users/name/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/network.py", line 1434, in _map_graph_network
    tensor_index=tensor_index)
  File "/Users/name/anaconda3/envs/tf/lib/python3.6/site-packages/keras/engine/network.py", line 1415, in build_map
    for i in range(len(node.inbound_layers)):
TypeError: object of type 'Activation' has no len()

这是我的代码:

import networkx as nx
import stellargraph as sg
import pandas as pd
import numpy as np


from keras import layers, optimizers, losses, metrics, Model

from keras import optimizers

from stellargraph.mapper import GraphSAGENodeGenerator, GraphSAGELinkGenerator
from stellargraph.layer import GraphSAGE, link_classification
from stellargraph.data import UnsupervisedSampler


from sklearn import preprocessing
import matplotlib.pyplot as plt


from sklearn.decomposition import PCA
from sklearn.manifold import TSNE


# Loading Data --------------

# Define Edges and Nodes (from_pandas_edgelist creates Nodes automatically from the parsed edgelist)
edgelist= pd.read_csv("./data/cora/cora.cites", sep='\t', header=None, names=['target', 'source'])
edgelist['label'] = 'cites'
Gnx = nx.from_pandas_edgelist(edgelist, edge_attr='label')
nx.set_node_attributes(Gnx, 'paper', 'label')

# Define Node features
feature_names = ["w_{}".format(ii) for ii in range(1433)]
column_names = feature_names + ['subject']
node_data = pd.read_csv("./data/cora/cora.content", sep='\t', header=None, names=column_names)
node_with_features = node_data[feature_names]

# Create StellarGraph object
G = sg.StellarGraph(Gnx, node_features=node_with_features)


# Specify model and training parameter
nodes = list(G.nodes())
number_of_walks = 1
length = 5
batch_size = 50
epochs = 4
num_samples = [10, 5]

unsupervised_samples = UnsupervisedSampler(G, nodes=nodes, length=length, number_of_walks=number_of_walks)
train_gen = GraphSAGELinkGenerator(G,batch_size, num_samples)#.flow(unsupervised_samples)


# Creating GraphSAGE model
layer_sizes =[50,50]
graphsage = GraphSAGE(layer_sizes=layer_sizes, generator=train_gen, bias=True, dropout=0.0, normalize='l2')

x_inp, x_out = graphsage.build()
prediction = link_classification(output_dim=1, output_act='hard_sigmoid', edge_embedding_method='ip')(x_out)

model = Model(input=x_inp, output=prediction)

model.compile(
    optimizers=optimizers.Adam(lr=1e-3),
    loss=losses.binary_crossentropy,
    metrics=[metrics.binary_accuracy],
)


history = model.fit_generator(
    train_gen,
    epochs=epochs,
    verbose=1,
    use_multiprocessing=False,
    workers=4,
    shuffle=True,
)

# Node Embedding
x_inp_src = x_inp[0::2]
x_out_src = x_out[0]
embedding_model = Model(inputs=x_inp_src, outputs=x_out_src)
node_ids = node_data.index
node_gen = GraphSAGENodeGenerator(G, batch_size,num_samples).flow(node_ids)
node_embeddings = embedding_model.predict_generator(node_gen, workers=4, verbose=1)

因为我不确定这个错误告诉了我什么,因为KerasAPI中的激活方法没有实现len()。我已经阅读了关于这个错误的其他几个主题,但它也不起作用。请帮忙


Tags: nameinfrompyimportnodemodelnames
1条回答
网友
1楼 · 发布于 2024-05-02 09:29:36

确切的问题/解决方案取决于您使用的stellargraph的版本,但是如果您使用最新版本(0.11.0在撰写本文时没有问题,我已经做了一些调整以使其正常工作:

import networkx as nx
import stellargraph as sg
import pandas as pd
import numpy as np

# UPDATED: import from tensorflow.keras instead of keras
from tensorflow.keras import layers, optimizers, losses, metrics, Model

from stellargraph.mapper import GraphSAGENodeGenerator, GraphSAGELinkGenerator
from stellargraph.layer import GraphSAGE, link_classification
from stellargraph.data import UnsupervisedSampler


from sklearn import preprocessing
import matplotlib.pyplot as plt


from sklearn.decomposition import PCA
from sklearn.manifold import TSNE


# Loading Data        

# Define Edges and Nodes (from_pandas_edgelist creates Nodes automatically from the parsed edgelist)
edgelist= pd.read_csv("./data/cora/cora.cites", sep='\t', header=None, names=['target', 'source'])
edgelist['label'] = 'cites'
Gnx = nx.from_pandas_edgelist(edgelist, edge_attr='label')
nx.set_node_attributes(Gnx, 'paper', 'label')

# Define Node features
feature_names = ["w_{}".format(ii) for ii in range(1433)]
column_names = feature_names + ['subject']
node_data = pd.read_csv("./data/cora/cora.content", sep='\t', header=None, names=column_names)
node_with_features = node_data[feature_names]

# Create StellarGraph object
G = sg.StellarGraph(Gnx, node_features=node_with_features)


# Specify model and training parameter
nodes = list(G.nodes())
number_of_walks = 1
length = 5
batch_size = 50
epochs = 4
num_samples = [10, 5]

unsupervised_samples = UnsupervisedSampler(G, nodes=nodes, length=length, number_of_walks=number_of_walks)
train_gen = GraphSAGELinkGenerator(G,batch_size, num_samples)


# Creating GraphSAGE model
layer_sizes =[50,50]
graphsage = GraphSAGE(layer_sizes=layer_sizes, generator=train_gen, bias=True, dropout=0.0, normalize='l2')

x_inp, x_out = graphsage.build()
prediction = link_classification(output_dim=1, output_act='hard_sigmoid', edge_embedding_method='ip')(x_out)

# UPDATED: `inputs` and `outputs` instead of `input` and `output`
model = Model(inputs=x_inp, outputs=prediction)

model.compile(
    # UPDATED: parameter name `optimizer` instead of `optimizers`
    optimizer=optimizers.Adam(lr=1e-3),
    loss=losses.binary_crossentropy,
    metrics=[metrics.binary_accuracy],
)


history = model.fit_generator(
    # UPDATED: we need to call .flow before passing it to `fit_generator`
    train_gen.flow(unsupervised_samples), 
    epochs=epochs,
    verbose=1,
    use_multiprocessing=False,
    workers=4,
    shuffle=True,
)

# Node Embedding
x_inp_src = x_inp[0::2]
x_out_src = x_out[0]
embedding_model = Model(inputs=x_inp_src, outputs=x_out_src)
node_ids = node_data.index
node_gen = GraphSAGENodeGenerator(G, batch_size,num_samples).flow(node_ids)
node_embeddings = embedding_model.predict_generator(node_gen, workers=4, verbose=1)

print(node_embeddings)

我为我更新的每一行写了一条评论(注释)——除了一些小的打字错误,我怀疑主要问题来自于导入keras而不是tensorflow.keras。随着tensorflow的发布>;=2.0,stellargraph使用keras API,它是tensorflow核心API的一部分,它是recommended that users that use keras with the tensorflow backend switch to using ^{}

At this time, we recommend that Keras users who use multi-backend Keras with the TensorFlow backend switch to tf.keras in TensorFlow 2.0. tf.keras is better maintained and has better integration with TensorFlow features (eager execution, distribution support and other).

希望有帮助


作为旁注,正在使用的一些其他方法在0.11.0中已被弃用-它们目前应按原样工作,但会产生弃用警告,并将在将来删除:

从networkx构建星图:

G = sg.StellarGraph(Gnx, node_features=node_with_features)

# switch to
G = sg.StellarGraph.from_networkx(Gnx, node_features=node_with_features)

从星图模型获取输入和输出张量:

x_inp, x_out = graphsage.build()

# switch to
x_inp, x_out = graphsage.in_out_tensors()

相关问题 更多 >