运行算法
在下面的示例中,我们假设已实例化一个名为 gds
的 GraphDataScience
对象。在此处了解更多信息:入门。
1. 简介
使用 Python 客户端运行大多数算法在结构上与使用 Cypher API 相似
result = gds[.<tier>].<algorithm>.<execution-mode>[.<estimate>](
G: Graph,
**configuration: dict[str, any]
)
这里我们可以注意到一些主要区别
-
作为第一个参数,我们使用 图对象,而不是图名称字符串。
-
我们使用命名关键字参数,而不是配置映射。
根据执行模式,运行过程的结果将作为 pandas DataFrame
或 pandas Series
返回。
为了说明这一点,我们引入一个小型的路网图
gds.run_cypher(
"""
CREATE
(a:City {name: "New York City", settled: 1624}),
(b:City {name: "Philadelphia", settled: 1682}),
(c:City:Capital {name: "Washington D.C.", settled: 1790}),
(d:City {name: "Baltimore"}),
(e:City {name: "Atlantic City"}),
(f:City {name: "Boston"}),
(a)-[:ROAD {cost: 50}]->(b),
(a)-[:ROAD {cost: 50}]->(c),
(a)-[:ROAD {cost: 100}]->(d),
(b)-[:ROAD {cost: 40}]->(d),
(c)-[:ROAD {cost: 40}]->(d),
(c)-[:ROAD {cost: 80}]->(e),
(d)-[:ROAD {cost: 30}]->(e),
(d)-[:ROAD {cost: 80}]->(f),
(e)-[:ROAD {cost: 40}]->(f);
"""
)
G, project_result = gds.graph.project("road_graph", "City", {"ROAD": {"properties": ["cost"]}})
assert G.relationship_count() == 9
现在我们准备好在图 G
上运行算法了。
louvain_result = gds.louvain.mutate(
G, # Graph object
maxIterations=5, # Configuration parameters
mutateProperty="community"
)
assert louvain_result["communityCount"] > 0
fastrp_result = gds.fastRP.write(
G, # Graph object
featureProperties=["community"], # Configuration parameters
embeddingDimension=256,
propertyRatio=0.3,
relationshipWeightProperty="cost",
writeProperty="embedding"
)
assert fastrp_result["nodePropertiesWritten"] == G.node_count()
某些算法偏离了标准的语法结构。我们将在下面的部分中描述如何在 Python 客户端中使用它们。
2. 执行模式
算法以由其执行模式控制的格式返回结果。这些模式在运行算法中有详细解释。在 Python 客户端中,stats
、mutate
和 write
模式返回一个包含算法运行摘要结果的 pandas Series
。estimate
过程也适用同样的情况。
3. 需要节点匹配的算法
某些算法将(数据库)节点 ID 作为输入。这些节点 ID 必须直接从 Neo4j 数据库中匹配。在 Cypher 中工作时,这很简单。在 Python 客户端中,有一个便捷方法 gds.find_node_id
,可以根据节点标签和属性键值对检索节点 ID。
例如,要在包含城市的图 G
中查找源节点和目标节点,以运行 Dijkstra 源-目标最短路径算法,我们可以执行以下操作
source_id = gds.find_node_id(["City"], {"name": "New York City"})
target_id = gds.find_node_id(["City"], {"name": "Boston"})
result = gds.shortestPath.dijkstra.stream(
G,
sourceNode=source_id,
targetNode=target_id,
relationshipWeightProperty="cost"
)
assert result["totalCost"][0] == 160
gds.find_node_id
接受节点标签列表和节点属性键值对字典。找到的节点是那些具有所有指定标签并完全匹配所有给定属性键值对的节点。请注意,每次方法调用必须精确匹配一个节点,否则将引发错误。
4. 拓扑链接预测
拓扑链接预测的方法略有不同。就像在 GDS 过程 API 中一样,它们不接受图作为参数,而是接受两个节点引用作为位置参数。它们只是简单地以浮点数形式返回刚做出的预测的相似度得分——而不是任何类型的 pandas 数据结构。
例如,要运行 Adamic Adar 算法,我们可以使用以下方法
node1 = gds.find_node_id(["City"], {"name": "Boston"})
node2 = gds.find_node_id(["City"], {"name": "Atlantic City"})
score = gds.alpha.linkprediction.adamicAdar(node1, node2)
assert round(score, 2) == 0.62