python 工具包 NetworkX 教程翻譯

1簡(jiǎn)介

工具包NetworkX 可用于創(chuàng)建、操作和研究復(fù)雜網(wǎng)絡(luò)的結(jié)構(gòu)、動(dòng)態(tài)和功能。

2教程

2.1創(chuàng)建網(wǎng)絡(luò)拓?fù)鋱D

創(chuàng)建一個(gè)沒(méi)有節(jié)點(diǎn),沒(méi)有邊的網(wǎng)絡(luò)拓?fù)鋱D。

>>> import networkx as nx
>>> G = nx.Graph()

。。。
好吧,寫到這里發(fā)現(xiàn)了一個(gè)比我寫的好的。。。
基本操作教程的鏈接貼到這里:
http://www.itdecent.cn/p/e543dc63454f
這里說(shuō)一說(shuō)與上述文章不同的地方以及需要特別注意的地方
關(guān)于添加網(wǎng)絡(luò)節(jié)點(diǎn)時(shí)的兩個(gè)函數(shù)
add_node和add_nodes_from
對(duì)于add_node加一個(gè)點(diǎn)來(lái)說(shuō),字符串是只添加了名字為整個(gè)字符串的節(jié)點(diǎn)。但是對(duì)于add_nodes_from加一組點(diǎn)來(lái)說(shuō),字符串表示了添加了每一個(gè)字符都代表的多個(gè)節(jié)點(diǎn),exp:

g.add_node("spam") #添加了一個(gè)名為spam的節(jié)點(diǎn)
g.add_nodes_from("spam") #添加了4個(gè)節(jié)點(diǎn),名為s,p,a,m

加一組從0開(kāi)始的連續(xù)數(shù)字的節(jié)點(diǎn):

H = nx.path_graph(10)
g.add_nodes_from(H) #將0~9加入了節(jié)點(diǎn)

參考文中指出“但請(qǐng)勿使用g.add_node(H)”。但是官方的說(shuō)法是,使用g.add_node(H)以后,H就可以作為G的一個(gè)節(jié)點(diǎn)存在了,這種做法會(huì)使拓?fù)鋱D更加的靈活和強(qiáng)大。因?yàn)樗试S圖的圖、文件的圖、函數(shù)的圖等等。值得思考的是如何構(gòu)造應(yīng)用程序,使節(jié)點(diǎn)成為有用的實(shí)體。當(dāng)然,您總是可以在G中使用唯一的標(biāo)識(shí)符,并且如果您愿意,還可以使用一個(gè)單獨(dú)的字典,通過(guò)標(biāo)識(shí)符對(duì)節(jié)點(diǎn)信息進(jìn)行鍵控。

2.2向圖、節(jié)點(diǎn)、邊添加屬性

屬性包括:權(quán)重、標(biāo)簽、顏色或者其他的Python對(duì)象都可以添加到圖、節(jié)點(diǎn)和邊上。
每個(gè)圖、節(jié)點(diǎn)和邊緣都可以在關(guān)聯(lián)的屬性字典中保存鍵/值屬性對(duì)(鍵必須是可hashable的)。默認(rèn)的這些屬性都是空的,但是可以通過(guò)函數(shù)添加。

2.2.1圖屬性

向圖中添加屬性:

>>> G = nx.Graph(day="Friday")
>>> G.graph
{'day': 'Friday'}

然后使用下面代碼修改屬性:

>>> G.graph['day'] = "Monday"
>>> G.graph
{'day': 'Monday'}

2.2.2節(jié)點(diǎn)屬性

使用 add_node(), add_nodes_from()或者G.nodes添加屬性:

>>> G.add_node(1, time='5pm')
>>> G.add_nodes_from([3], time='2pm')
>>> G.nodes[1]
{'time': '5pm'}
>>> G.nodes[1]['room'] = 714
>>> G.nodes.data()
NodeDataView({1: {'time': '5pm', 'room': 714}, 3: {'time': '2pm'}})

注意使用 G.nodes并不會(huì)將它添加到圖中,而是只添加到節(jié)點(diǎn), 使用G.add_node() 來(lái)添加新節(jié)點(diǎn)到圖中. 邊界的操作類似.

2.2.3邊界屬性

添加和改變邊界的屬性方法如下:

>>> G.add_edge(1, 2, weight=4.7 )
>>> G.add_edges_from([(3, 4), (4, 5)], color='red')
>>> G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
>>> G[1][2]['weight'] = 4.7
>>> G.edges[3, 4]['weight'] = 4.2

注意,在算法中使用權(quán)重的時(shí)候需要將權(quán)重?cái)?shù)值化。

2.3有向圖

DiGraph類提供了特定于有向邊的附加屬性,例如DiGraph.out_edges()、DiGraph.in_degree()、DiGraph.neighbors()、DiGraph.successors()等。為了讓算法能夠輕松地處理這兩個(gè)類,neighbors()的定向版本相當(dāng)于successors(),而degree報(bào)告in_degree和out_degree的總和,盡管有時(shí)可能感覺(jué)不一致。

>>> DG = nx.DiGraph()
>>> DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
>>> DG.out_degree(1, weight='weight')
0.5
>>> DG.degree(1, weight='weight')
1.25
>>> list(DG.successors(1))
[2]
>>> list(DG.neighbors(1))
[2]

注意:一些算法只適用于有向圖,而另一些算法則不適用于有向圖。所以,將有向圖和無(wú)向圖混為一談是十分危險(xiǎn)的?。?!。如果你想在某些度量中將有向圖視為無(wú)向圖,你應(yīng)該使用graph . to_undirection()或者下述代碼將其轉(zhuǎn)換為無(wú)向圖:

 H = nx.Graph(G)  # convert G to undirected graph

2.4Multigraphs (復(fù)雜的多重圖)

NetworkX為允許任意一對(duì)節(jié)點(diǎn)之間有多條邊的圖提供了類。MultiGraph和MultiDiGraph類允許你添加相同的邊兩次,可能使用不同的邊數(shù)據(jù)。對(duì)于某些應(yīng)用程序,這可能非常強(qiáng)大,但是許多算法在這樣的圖上是不適用的。在這種圖中只有某些函數(shù)可以用,例如MultiGraph.degree()。如果想用其它函數(shù)就需要將它轉(zhuǎn)換成標(biāo)準(zhǔn)圖,以使度量得到很好的定義。下面是一個(gè)例子:

>>> MG = nx.MultiGraph()
>>> MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
>>> dict(MG.degree(weight='weight'))
{1: 1.25, 2: 1.75, 3: 0.5}
>>> GG = nx.Graph()
>>> for n, nbrs in MG.adjacency():
...    for nbr, edict in nbrs.items():
...        minvalue = min([d['weight'] for d in edict.values()])
...        GG.add_edge(n, nbr, weight = minvalue)
...
>>> nx.shortest_path(GG, 1, 3)
[1, 2, 3]

2.5 圖生成器和圖操作

除了按節(jié)點(diǎn)構(gòu)造圖或按邊構(gòu)造圖外,還可以通過(guò)以下方法生成圖:

  1. 使用圖的類操作:
subgraph(G, nbunch)      - induced subgraph view of G on nodes in nbunch
union(G1,G2)             - graph union
disjoint_union(G1,G2)    - graph union assuming all nodes are different
cartesian_product(G1,G2) - return Cartesian product graph
compose(G1,G2)           - combine graphs identifying nodes common to both
complement(G)            - graph complement
create_empty_copy(G)     - return an empty copy of the same graph class
to_undirected(G) - return an undirected representation of G
to_directed(G)   - return a directed representation of G
  1. 調(diào)用一個(gè)經(jīng)典的小圖表:
>>> petersen = nx.petersen_graph()
>>> tutte = nx.tutte_graph()
>>> maze = nx.sedgewick_maze_graph()
>>> tet = nx.tetrahedral_graph()

3.對(duì)經(jīng)典圖使用(構(gòu)造)生成器,例如:

>>> K_5 = nx.complete_graph(5)
>>> K_3_5 = nx.complete_bipartite_graph(3, 5)
>>> barbell = nx.barbell_graph(10, 10)
>>> lollipop = nx.lollipop_graph(10, 20)
  1. 使用基于統(tǒng)計(jì)的生成器:
>>> er = nx.erdos_renyi_graph(100, 0.15)
>>> ws = nx.watts_strogatz_graph(30, 3, 0.1)
>>> ba = nx.barabasi_albert_graph(100, 5)
>>> red = nx.random_lobster(100, 0.9, 0.9)

5.從文件讀取,文件應(yīng)該是edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others.

>>> nx.write_gml(red, "path.to.file")
>>> mygraph = nx.read_gml("path.to.file")

詳細(xì)的生成器可以參考:
https://networkx.github.io/documentation/stable/reference/generators.html

2.6 圖分析

生成的圖G可以利用各種圖論理論來(lái)進(jìn)行分析,這里簡(jiǎn)要介紹一下,后面專門再寫一篇:

>>> G = nx.Graph()
>>> G.add_edges_from([(1, 2), (1, 3)])
>>> G.add_node("spam")       # adds node "spam"
>>> list(nx.connected_components(G))
[{1, 2, 3}, {'spam'}]
>>> sorted(d for n, d in G.degree()) #排序
[0, 1, 1, 2]
>>> nx.clustering(G) #聚類
{1: 0, 2: 0, 3: 0, 'spam': 0}

一些具有很大輸出迭代量的函數(shù)在(節(jié)點(diǎn)、值)2元組上迭代。如果你愿意,可以很容易地將它們存儲(chǔ)在dict結(jié)構(gòu)中。

>>> sp = dict(nx.all_pairs_shortest_path(G))
>>> sp[3]
{3: [3], 1: [3, 1], 2: [3, 1, 2]}

這里給出算法相關(guān)連接:
https://networkx.github.io/documentation/stable/reference/algorithms/index.html

2.7 圖的可視化

NetworkX主要不是一個(gè)圖形繪制包,而是包含了Matplotlib的基本繪圖以及使用開(kāi)源Graphviz軟件包的接口。這些是networkx的一部分。
首先需要導(dǎo)入:

>>> import matplotlib.pyplot as plt

使用下述函數(shù)之一測(cè)試是否導(dǎo)入networkx并繪制G:

>>> G = nx.petersen_graph()
>>> plt.subplot(121)
<matplotlib.axes._subplots.AxesSubplot object at ...>
>>> nx.draw(G, with_labels=True, font_weight='bold')
>>> plt.subplot(122)
<matplotlib.axes._subplots.AxesSubplot object at ...>
>>> nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 二、圖 原文:Chapter 2 Graphs 譯者:飛龍 協(xié)議:CC BY-NC-SA 4.0 自豪地采用谷歌...
    布客飛龍閱讀 1,172評(píng)論 1 6
  • 目錄 創(chuàng)建一個(gè)圖 節(jié)點(diǎn) 邊 查看圖上點(diǎn)和邊的信息 圖的屬性設(shè)置 點(diǎn)的屬性設(shè)置 邊的屬性設(shè)置 不同類型的圖(有向圖D...
    Forget_ever閱讀 55,932評(píng)論 0 33
  • 一群筆桿子,在簡(jiǎn)書里攪拌風(fēng)云。我這根桔梗也混進(jìn)來(lái)攪和攪和。 今天我就奉上,幾句自編的順口溜助助興。 求粉絲,博眼球...
    秀火儒林閱讀 678評(píng)論 0 4
  • 起床:6:30 就寢:11:30 天氣:晴 今日行程1)早上閱讀半小時(shí)+準(zhǔn)備簽證材料+寫清單和下周計(jì)劃 2)準(zhǔn)備會(huì)...
    雅Younger閱讀 179評(píng)論 0 0
  • 周六,你也沒(méi)來(lái)找我。沒(méi)有來(lái)。一點(diǎn)消息都沒(méi)有,我賭氣說(shuō)要把你送的包賣掉,可是我哪里舍得呢?我希望我舍得,可是,我好沒(méi)...
    努力的小暖閱讀 252評(píng)論 0 0

友情鏈接更多精彩內(nèi)容