python - “激活”类型的对象没有 len()
问题描述
我正在尝试使用 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)
因为我不确定这个错误告诉我什么,因为 Keras API 中的 Activation 方法没有实现 len() 。我已经阅读了有关此错误的其他几个主题,但也没有成功。请帮忙。
解决方案
确切的问题/解决方案取决于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)
我为我更新的每一行(UPDATED
那些)写了一条评论——除了一些小错别字,我怀疑主要问题来自导入keras
而不是tensorflow.keras
. 随着 tensorflow >= 2.0 的发布,stellargraph
使用作为 tensorflow 核心 API 一部分的 keras API,建议使用带有 tensorflow 后端的 keras 的用户切换到使用tensorflow.keras
目前,我们建议在 TensorFlow 后端使用多后端 Keras 的 Keras 用户切换到 TensorFlow 2.0 中的 tf.keras。tf.keras 维护得更好,并且与 TensorFlow 功能(急切执行、分发支持等)有更好的集成。
希望有帮助!
作为旁注,正在使用的其他一些方法已被弃用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)
从 stellargraph 模型获取输入和输出张量:
x_inp, x_out = graphsage.build()
# switch to
x_inp, x_out = graphsage.in_out_tensors()
推荐阅读
- loopbackjs - 您如何通过 id 以外的其他内容在存储库中找到项目
- xamarin.forms - 如何在 Xamarin Shell MenuItem 中添加开关
- flutter - 应用程序在终止并重新打开后如何保持与 Google 的登录状态
- java - 如何通过单击按钮在拨号盘上自动执行数字而不向用户显示
- python - 使用 Django/python 在 amazon s3 中转换文件的最佳方法是什么?
- html - 如何在 Powershell Core 中解析 html
- sql-server - 来自其他数据库的内部连接
- python - DEAP:针对机票问题实施 NSGA-ii
- r - r 中的下拉菜单和复选框
- ios - 撰写电子邮件时设置 UINavigationBar 标题颜色