You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用python-igraph计算加权中心性时遭遇TypeError错误求助

Fixing TypeError When Calculating Weighted Centrality in python-igraph

Hey there! Let's sort out that TypeError you're hitting when trying to compute weighted centrality metrics with python-igraph. The issue comes down to a small mistake in how you're using the weights parameter.

What's Going Wrong?

In python-igraph, the strength() and betweenness() methods don't accept a boolean value (like True) for the weights argument. Instead, you need to pass the string name of your edge weight attribute—which, based on your code, is "weight" (since you used weights=True when reading the NCOL file, which automatically assigns the weights to an edge attribute named weight).

When you pass weights=True, the library tries to look for an edge attribute literally named "True", which doesn't exist—hence the TypeError.

Corrected Code

Here's how to adjust your calls to get the weighted centrality metrics working:

from igraph import *

# Read your weighted undirected graph
g = Graph.Read_Ncol("sample.txt", names=True, directed=False, weights=True)

# Verify vertex names and edge weights (your original code)
print(g.vs["name"])
print(g.es["weight"])

# Calculate weighted strength centrality (sum of adjacent edge weights)
print(g.strength(weights="weight"))

# Calculate weighted betweenness centrality (considers edge weights as path "costs")
print(g.betweenness(weights="weight"))

Quick Notes

  • For strength(), using weights="weight" computes the weighted degree of each vertex (sum of all connected edge weights) instead of the raw count of edges.
  • For betweenness(), the weights are treated as the "length" or "cost" of traversing an edge. Higher weight edges are less likely to be included in the shortest paths used to calculate betweenness.

内容的提问来源于stack exchange,提问作者Claire Cui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:29:55