如何使用Graph::Easy为图的边分配频率得分的权重

3

我该如何使用Graph::Easy为图形的边分配权重或频率得分?

我有一个双弧和它们的频率列表。 我可以使用Graph::Easy轻松创建只包含双弧的(数学)图表。 输出恰好符合我的要求。 但是当我尝试“set_attribute”时,会出现错误,提示“'frequency'不是有效的属性名称”。我做错了什么? 使用Graph::Easy,我如何使频率成为一个有效的属性?

#!/usr/bin/perl

# graph.pl - given a list of bigrams and their frequencies, output graphml

# require
use Graph::Easy;
use strict;

# initialize
my $graph = Graph::Easy->new;

# process the data
while ( <DATA> ) {

    # parse
    chop;
    my ( $nodes, $frequency ) = split( "\t", $_ );
    my ( $source, $target )   = split( ' ', $nodes );

    # update the graph
    my $edge = $graph->add_edge( $source, $target );

    # error happen here
    $edge->set_attribute( 'frequency', $frequency );

}

# output & done
print $graph->as_graphml();
exit;


# a set of bigrams and their frequencies
__DATA__
cds classroom   4
maximum registration    4
may want    3
anomalies within    2
resulting analysis  2
participants may    2
corpus without  2
journal articles    2
quickly learn   2
active reading  2
text mining     2
literally count     2
find patterns   2
14 million  2
digital humanities  2
humanities research     2
2个回答

3

我试用了这个模块,似乎它不接受任意“属性”,只能接受一组特定的预定义属性。显然,“频率”不属于其中之一。

我从文档中挑选了一个样例,并替换了你的

$edge->set_attribute( 'frequency', $frequency );

使用

标签

$edge->set_attribute( 'label', $frequency );

在示例中,他们经常提到标签

print $graph->as_ascii();

然后打印:
+--------------+  2   +--------------+
|      14      | ---> |   million    |
+--------------+      +--------------+
+--------------+  2   +--------------+  2   +----------+
|   digital    | ---> |  humanities  | ---> | research |
+--------------+      +--------------+      +----------+
+--------------+  2   +--------------+  3   +----------+
| participants | ---> |     may      | ---> |   want   |
+--------------+      +--------------+      +----------+
...

您是想要这个吗?


最终,我找到了与Graph::Easy有关的完整文档。在属性部分中列出了允许的属性。我相信有一种方法可以拥有自定义属性,因为该模块有一个方法get_custom_attributes


1
唉,经过与开发人员的一番电子邮件交流后,我认为使用Graph::Easy无法添加任意属性到边缘。根据我的经验,Graph::Easy更多地是用于输出图形而不是生成graphml/XML。 - ericleasemorgan
1
Python模块--pygraphml--可能更适合我所需的。 - ericleasemorgan
@ericleasemorgan 哦,好的。看起来很合理。就像我说的,我只是随便玩了一下,并不知道你想创建XML。属性在那里很有意义。没关系。谢谢你向我展示另一个有趣的模块。 :-) - PerlDuck

0
对我来说,“最好”的答案是不要使用Graph::Easy,而是使用Python模块NetworkX
#!/usr/bin/python

# graph.py - given a CSV file of a specific shape, output graphml


# configure
DATA  = './data.csv'
GRAPH = './data.graphml'
LABEL = 'frequency'

# require
import networkx as nx
import csv

# initialize
g = nx.DiGraph()

# read the data
with open( DATA, 'r' ) as f :

    # initialize
    r = csv.reader( f, delimiter='\t')

    # process each record
    for source, target, frequency in r :

        # sanity check
        if len( source ) == 0 or len( target ) == 0 : continue

        # update the graph
        g.add_edge( source, target )    
        g[ source ][ target ][ LABEL ] = frequency

# output & done
nx.write_graphml( g, GRAPH )
exit()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接