<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.3">Jekyll</generator><link href="https://wumorfr.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://wumorfr.github.io/" rel="alternate" type="text/html" /><updated>2023-02-22T08:48:25+00:00</updated><id>https://wumorfr.github.io/feed.xml</id><title type="html">乌墨的博客</title><subtitle>个人/学生/本科/在校</subtitle><entry><title type="html">【Datawhalw】【CS224W】图神经网络（五）</title><link href="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%BA%94)/" rel="alternate" type="text/html" title="【Datawhalw】【CS224W】图神经网络（五）" /><published>2023-02-22T00:00:00+00:00</published><updated>2023-02-22T00:00:00+00:00</updated><id>https://wumorfr.github.io/%5BDatawhale%5D%5BCS224W%5D%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%BA%94)</id><content type="html" xml:base="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%BA%94)/">&lt;h2 id=&quot;一deepwalk&quot;&gt;一、Deepwalk&lt;/h2&gt;

&lt;h3 id=&quot;11-预备知识&quot;&gt;1.1 预备知识&lt;/h3&gt;

&lt;p&gt;机器学习，深度学习基础，语言模型，word2vec&lt;/p&gt;

&lt;h3 id=&quot;12-deepwalk介绍&quot;&gt;1.2 Deepwalk介绍&lt;/h3&gt;

&lt;p&gt;DeepWalk的思想类似word2vec，使用&lt;strong&gt;图中节点与节点的共现关系&lt;/strong&gt;来学习节点的向量表示。那么关键的问题就是如何来描述节点与节点的共现关系，DeepWalk给出的方法是使用随机游走(RandomWalk)的方式在图中进行节点采样。&lt;/p&gt;

&lt;p&gt;$Deepwalk$将$graph$的每一个节点编码为一个$D$维向量(Embedding)(无监督学习)&lt;/p&gt;

&lt;p&gt;Embedding中隐式包含了$Graph$中的社群，连接，结构信息，可用于后续节点分类等下游任务（监督学习）&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222142856728.png&quot; alt=&quot;image-20230222142856728&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Deepwalk通过套用随机游走(Random walk generation)将图像转化为D维向量&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222153354939.png&quot; alt=&quot;image-20230222153354939&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;13-embedding&quot;&gt;1.3 Embedding&lt;/h3&gt;

&lt;p&gt;我们需要将图转化为计算机了解的向量，所以我们需要使用embedding&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222143330826.png&quot; alt=&quot;image-20230222143330826&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;14-word2vec-词向量词嵌入&quot;&gt;1.4 word2Vec 词向量，词嵌入&lt;/h3&gt;

&lt;p&gt;word2vec通过语料库中的句子序列来描述词与词的共现关系，进而学习到词语的向量表示。&lt;/p&gt;

&lt;p&gt;主要有两种方法&lt;/p&gt;

&lt;p&gt;CBOW：用边缘词去预测中心词&lt;/p&gt;

&lt;p&gt;Skip-gram：用输入的中心词去预测周围词&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222143852663.png&quot; alt=&quot;image-20230222143852663&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;15-random-walk随机游走&quot;&gt;1.5 random Walk随机游走&lt;/h3&gt;

&lt;p&gt;RandomWalk是一种&lt;strong&gt;可重复访问已访问节点的深度优先遍历&lt;/strong&gt;算法。给定当前访问起始节点，从其邻居中随机采样节点作为下一个访问节点，重复此过程，直到访问序列长度满足预设条件。&lt;/p&gt;

&lt;p&gt;获取足够数量的节点访问序列后，使用skip-gram model 进行向量学习。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic1.zhimg.com/80/v2-fdcb0babe4a168df85243b548fd86d30_720w.webp&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;具体见[[Datawhale][CS224W]图机器学习(四)](https://blog.csdn.net/weixin_45856170/article/details/129070015)&lt;/p&gt;

&lt;h3 id=&quot;16-deepwalk-核心代码&quot;&gt;1.6 DeepWalk 核心代码&lt;/h3&gt;

&lt;p&gt;DeepWalk算法主要包括两个步骤，第一步为随机游走采样节点序列，第二步为使用skip-gram modelword2vec学习表达向量。&lt;/p&gt;

&lt;p&gt;①构建同构网络，从网络中的每个节点开始分别进行Random Walk 采样，得到局部相关联的训练数据； ②对采样数据进行SkipGram训练，将离散的网络节点表示成向量化，最大化节点共现，使用Hierarchical Softmax来做超大规模分类的分类器&lt;/p&gt;

&lt;h4 id=&quot;random-walk&quot;&gt;Random Walk&lt;/h4&gt;

&lt;p&gt;我们可以通过并行的方式加速路径采样，在采用多进程进行加速时，相比于开一个进程池让每次外层循环启动一个进程，我们采用固定为每个进程分配指定数量的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;num_walks&lt;/code&gt;的方式，这样可以最大限度减少进程频繁创建与销毁的时间开销。&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;deepwalk_walk&lt;/code&gt;方法对应上一节伪代码中第6行，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;_simulate_walks&lt;/code&gt;对应伪代码中第3行开始的外层循环。最后的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Parallel&lt;/code&gt;为多进程并行时的任务分配操作。&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;deepwalk_walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;start_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cur&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cur_nbrs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cur&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cur_nbrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cur_nbrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_simulate_walks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_walks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;walks&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_walks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;           
            &lt;span class=&quot;n&quot;&gt;walks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deepwalk_walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alk_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_node&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walks&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Parallel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_jobs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;workers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;verbose&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;verbose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;delayed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_simulate_walks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;partition_num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_walks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;workers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;walks&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;itertools&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chain&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;word2vec&quot;&gt;Word2vec&lt;/h4&gt;

&lt;p&gt;这里就偷个懒直接用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gensim&lt;/code&gt;里的Word2Vec了。&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;gensim.models&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Word2Vec&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;w2v_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Word2Vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;walks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sg&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;deepwalk应用&quot;&gt;DeepWalk应用&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;read_edgelist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'../data/wiki/Wiki_edgelist.txt'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;create_using&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiGraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodetype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'weight'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DeepWalk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_walks&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;80&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;workers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;evaluate_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plot_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;17-deepwalk优缺点&quot;&gt;1.7 DeepWalk优缺点&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;优点
    &lt;ul&gt;
      &lt;li&gt;首个将深度学习和自然语言处理的思想用于图机器学习&lt;/li&gt;
      &lt;li&gt;在系数标注节点分类场景下，嵌入性能卓越&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;缺点
    &lt;ul&gt;
      &lt;li&gt;均匀随机游走，没有偏向的游走方向（Node2Vec）&lt;/li&gt;
      &lt;li&gt;需要大量随机游走序列训练&lt;/li&gt;
      &lt;li&gt;基于随机游走，管中窥豹。距离较远的两个节点无法相互影响。看不到全图信息。（图神经网络）&lt;/li&gt;
      &lt;li&gt;无监督，仅编码图的连接信息，没有利用节点的属性特征&lt;/li&gt;
      &lt;li&gt;没有真正用到神经网络和深度学习&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;二node2vec&quot;&gt;二、Node2Vec&lt;/h2&gt;

&lt;h3 id=&quot;21-图嵌入&quot;&gt;2.1 图嵌入&lt;/h3&gt;

&lt;p&gt;将数据转化为D维连续稠密的向量，包含了原来的节点的多种信息&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222153010863.png&quot; alt=&quot;image-20230222153010863&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222153329769.png&quot; alt=&quot;image-20230222153329769&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;22-node2vec&quot;&gt;2.2 Node2Vec&lt;/h3&gt;

&lt;h4 id=&quot;优化目标&quot;&gt;优化目标&lt;/h4&gt;

&lt;p&gt;设 $f(u)$是将顶点 $u$ 映射为embedding向量的映射函数,对于图中每个顶点$u$，定义 $N_s(u)$ 为通过采样策略 $S$采样出的顶点 $u$的近邻顶点集合。&lt;/p&gt;

&lt;p&gt;node2vec优化的目标是给定每个顶点条件下，令其近邻顶点（&lt;strong&gt;如何定义近邻顶点很重要&lt;/strong&gt;）出现的概率最大。&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;$max_f\sum_{u\in V}log Pr(N_s(U)&lt;/td&gt;
      &lt;td&gt;f(u))$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;为了将上述最优化问题可解，文章提出两个假设：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;条件独立性假设&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;假设给定源顶点下，其近邻顶点出现的概率与近邻集合中其余顶点无关。 $Pr(N_s(u)&lt;/td&gt;
      &lt;td&gt;f(u))=\prod_{n_i&lt;/td&gt;
      &lt;td&gt;f(u)}Pr(n_i&lt;/td&gt;
      &lt;td&gt;f(u))$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ul&gt;
  &lt;li&gt;特征空间对称性假设&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;这里是说一个顶点作为源顶点和作为近邻顶点的时候&lt;strong&gt;共享同一套embedding向量&lt;/strong&gt;。(对比LINE中的2阶相似度，一个顶点作为源点和近邻点的时候是拥有不同的embedding向量的) 在这个假设下，上述条件概率公式可表示为 $Pr(n_i&lt;/td&gt;
      &lt;td&gt;f(u))={expf(n_i)\cdot  f(u)}\over{\sum_{v\in V}expf(v)\cdot f(u)}$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;根据以上两个假设条件，最终的目标函数表示为&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222163604126.png&quot; alt=&quot;image-20230222163604126&quot; /&gt;&lt;/p&gt;

&lt;p&gt;由于归一化因子 &lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222163615301.png&quot; alt=&quot;image-20230222163615301&quot; /&gt;的计算代价高，所以采用负采样技术优化。&lt;/p&gt;

&lt;h4 id=&quot;顶点序列采样策略&quot;&gt;顶点序列采样策略&lt;/h4&gt;

&lt;p&gt;node2vec依然采用随机游走的方式获取顶点的近邻序列，不同的是node2vec采用的是一种有偏的随机游走。&lt;/p&gt;

&lt;p&gt;给定当前顶点 v ，访问下一个顶点 x 的概率为&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic2.zhimg.com/80/v2-84cc0b66ec34043f82649f0d799997e1_720w.webp&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;$\pi_{vx}$ 是顶点 v 和顶点 x 之间的未归一化转移概率， Z 是归一化常数。&lt;/p&gt;

&lt;p&gt;node2vec引入两个超参数 p 和 q 来控制随机游走的策略，假设当前随机游走经过边 (t,v) 到达顶点 �v设 &lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222163711950.png&quot; alt=&quot;image-20230222163711950&quot; /&gt;，$\omega_{vx}$ 是顶点 v 和 x 之间的边权，&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic3.zhimg.com/80/v2-0d170e5c120681823ed6880411a0478e_720w.webp&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;$d_{tx}$为顶点 t 和顶点 x 之间的最短路径距离。&lt;/p&gt;

&lt;p&gt;下面讨论超参数 p 和 q 对游走策略的影响&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Return parameter,p&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;参数p控制重复访问刚刚访问过的顶点的概率。 注意到p仅作用于 $d_{tx}$=0 的情况，而$d_{tx}$=0 表示顶点 x 就是访问当前顶点 v 之前刚刚访问过的顶点。 那么若 p 较高，则访问刚刚访问过的顶点的概率会变低，反之变高。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;In-out papameter,q&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;q 控制着游走是向外还是向内，若 q&amp;gt;1 ，随机游走倾向于访问和 t 接近的顶点(偏向BFS)。若 q&amp;lt;1 ，倾向于访问远离 t 的顶点(偏向DFS)。&lt;/p&gt;

&lt;p&gt;下面的图描述的是当从 t 访问到 v 时，决定下一个访问顶点时每个顶点对应的 $\alpha$ 。&lt;/p&gt;

&lt;p&gt;设定p,q进行有偏随机游走&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222153738097.png&quot; alt=&quot;image-20230222153738097&quot; /&gt;&lt;/p&gt;

&lt;p&gt;q节点小时更愿意进行BFS,p节点小时更愿意进行DFS&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222153919325.png&quot; alt=&quot;image-20230222153919325&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;23-理论上的实现&quot;&gt;2.3 理论上的实现&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222154012450.png&quot; alt=&quot;image-20230222154012450&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;24-node2vec代码实现&quot;&gt;2.4 Node2Vec代码实现&lt;/h3&gt;

&lt;h4 id=&quot;学习算法&quot;&gt;学习算法&lt;/h4&gt;

&lt;p&gt;采样完顶点序列后，剩下的步骤就和deepwalk一样了，用word2vec去学习顶点的embedding向量。 值得注意的是node2vecWalk中不再是随机抽取邻接点，而是按概率抽取，node2vec采用了Alias算法进行顶点采样。&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://zhuanlan.zhihu.com/p/54867139&quot;&gt;Alias Method:时间复杂度O(1)的离散采样方法125 赞同 · 23 评论文章&lt;img src=&quot;https://pic2.zhimg.com/v2-775c1610ad114ca7d2107348c70345cd_180x120.jpg&quot; alt=&quot;img&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4 id=&quot;node2vec核心代码&quot;&gt;node2vec核心代码&lt;/h4&gt;

&lt;p&gt;&lt;img src=&quot;https://pic4.zhimg.com/80/v2-dae49695db78fda4ff11284e932a7c43_720w.webp&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;node2vecwalk&quot;&gt;node2vecWalk&lt;/h4&gt;

&lt;p&gt;通过上面的伪代码可以看到，node2vec和deepwalk非常类似，主要区别在于顶点序列的采样策略不同，所以这里我们主要关注&lt;strong&gt;node2vecWalk&lt;/strong&gt;的实现。&lt;/p&gt;

&lt;p&gt;由于采样时需要考虑前面2步访问过的顶点，所以当访问序列中只有1个顶点时，直接使用当前顶点和邻居顶点之间的边权作为采样依据。 当序列多余2个顶点时，使用文章提到的有偏采样。&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;node2vec_walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;alias_nodes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_nodes&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;alias_edges&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_edges&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;start_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;cur&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;cur_nbrs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cur&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cur_nbrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;            
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;                
                &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cur_nbrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cur&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alias_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cur&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])])&lt;/span&gt;            
            &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;                
                &lt;span class=&quot;n&quot;&gt;prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;                
                &lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cur&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                
                &lt;span class=&quot;n&quot;&gt;next_node&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cur_nbrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])]&lt;/span&gt;                
                &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;            
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;walk&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;构造采样表&quot;&gt;构造采样表&lt;/h4&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;preprocess_transition_probs&lt;/code&gt;分别生成&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alias_nodes&lt;/code&gt;和&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alias_edges&lt;/code&gt;，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alias_nodes&lt;/code&gt;存储着在每个顶点时决定下一次访问其邻接点时需要的alias表（&lt;strong&gt;不考虑当前顶点之前访问的顶点&lt;/strong&gt;）。&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alias_edges&lt;/code&gt;存储着在前一个访问顶点为 t ，当前顶点为 v 时决定下一次访问哪个邻接点时需要的alias表。&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;get_alias_edge&lt;/code&gt;方法返回的是在上一次访问顶点 t ，当前访问顶点为 v 时到下一个顶点 x 的未归一化转移概率 &lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230222164222830.png&quot; alt=&quot;image-20230222164222830&quot; /&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_alias_edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'weight'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# w_vx        
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# d_tx == 0            
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;has_edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# d_tx == 1            
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# d_tx == 2            
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;norm_const&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;normalized_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_const&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u_prob&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;create_alias_table&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;normalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;preprocess_transition_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alias_nodes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;node&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nbr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'weight'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nbr&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;norm_const&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;normalized_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;norm_const&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u_prob&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;unnormalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;                 
        &lt;span class=&quot;n&quot;&gt;alias_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;create_alias_table&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;normalized_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alias_edges&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;alias_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get_alias_edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_nodes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alias_nodes&lt;/span&gt;    
    &lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alias_edges&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alias_edges&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;node2vec应用&quot;&gt;node2vec应用&lt;/h4&gt;

&lt;p&gt;使用node2vec在wiki数据集上进行节点分类任务和可视化任务。 wiki数据集包含 2,405 个网页和17,981条网页之间的链接关系，以及每个网页的所属类别。 通过简单的超参搜索，这里使用p=0.25,q=4的设置。&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;read_edgelist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'../data/wiki/Wiki_edgelist.txt'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;create_using&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiGraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodetype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'weight'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Node2Vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;walk_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_walks&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;80&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;workers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    
&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;evaluate_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plot_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;25-node2vec与deepwalk相比的优点与特点&quot;&gt;2.5 Node2Vec与DeepWalk相比的优点与特点&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;优点
    &lt;ul&gt;
      &lt;li&gt;Node2Vec解决图嵌入问题，将图中的每个节点映射为一个向量（嵌入）&lt;/li&gt;
      &lt;li&gt;向量（嵌入）包含了节点的语义信息（相邻社群和功能角色）&lt;/li&gt;
      &lt;li&gt;语义相似的节点，向量（嵌入）的距离也近。&lt;/li&gt;
      &lt;li&gt;向量（嵌入）用于后续的分类，聚类，link Predictin，推荐等任务。&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;特点
    &lt;ul&gt;
      &lt;li&gt;在DeepWalk完全随机游走的基础上，Node2Vec增加p,q参数，实现有偏随机游走。不同的p,q组合，对应了不同的探索范围和节点语义。&lt;/li&gt;
      &lt;li&gt;DFS深度优先探索，相邻的节点，向量（嵌入）距离相近&lt;/li&gt;
      &lt;li&gt;BFS广度优先探索，相同功能角色的节点，向量（嵌入）距离相近。&lt;/li&gt;
      &lt;li&gt;DeepWalk时Node2Vec在p=1,q=1的特例&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;26-node2vec的优缺点&quot;&gt;2.6 Node2Vec的优缺点&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;优点
    &lt;ul&gt;
      &lt;li&gt;首次通过调节p,q值，实现了有偏随机游走，探索节点社群，功能等不同属性&lt;/li&gt;
      &lt;li&gt;首次将节点分类用于Link Prediction&lt;/li&gt;
      &lt;li&gt;可解释性，可扩展性好，性能卓越&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;缺点
    &lt;ul&gt;
      &lt;li&gt;需要大量随机游走序列训练&lt;/li&gt;
      &lt;li&gt;距离较远的两个界定啊无法直接相互影响。看不到全图信息。（图神经网络）&lt;/li&gt;
      &lt;li&gt;无监督，仅编码图的连接信息，没有利用节点的属性特征（图卷积）&lt;/li&gt;
      &lt;li&gt;没有真正用到神经网络和深度学习&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;参考文献&quot;&gt;参考文献&lt;/h1&gt;

&lt;p&gt;[1]  &lt;a href=&quot;https://www.bilibili.com/video/BV1pR4y1S7GA?vd_source=872fc2755b4c0ffb1be2bc7240a69fed&quot;&gt;斯坦福CS224W图机器学习、图神经网络、知识图谱【同济子豪兄】&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[2] &lt;a href=&quot;https://zhuanlan.zhihu.com/p/56380812&quot;&gt;【Graph Embedding】DeepWalk：算法原理，实现和应用&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[3] &lt;a href=&quot;https://zhuanlan.zhihu.com/p/56542707&quot;&gt;【Graph Embedding】node2vec：算法原理，实现和应用&lt;/a&gt;&lt;/p&gt;</content><author><name>乌墨_rfr</name></author><category term="Datawhale" /><category term="CS224W" /><category term="图神经网络" /><summary type="html">一、Deepwalk 1.1 预备知识 机器学习，深度学习基础，语言模型，word2vec 1.2 Deepwalk介绍 DeepWalk的思想类似word2vec，使用图中节点与节点的共现关系来学习节点的向量表示。那么关键的问题就是如何来描述节点与节点的共现关系，DeepWalk给出的方法是使用随机游走(RandomWalk)的方式在图中进行节点采样。 $Deepwalk$将$graph$的每一个节点编码为一个$D$维向量(Embedding)(无监督学习) Embedding中隐式包含了$Graph$中的社群，连接，结构信息，可用于后续节点分类等下游任务（监督学习） Deepwalk通过套用随机游走(Random walk generation)将图像转化为D维向量 1.3 Embedding 我们需要将图转化为计算机了解的向量，所以我们需要使用embedding 1.4 word2Vec 词向量，词嵌入 word2vec通过语料库中的句子序列来描述词与词的共现关系，进而学习到词语的向量表示。 主要有两种方法 CBOW：用边缘词去预测中心词 Skip-gram：用输入的中心词去预测周围词 1.5 random Walk随机游走 RandomWalk是一种可重复访问已访问节点的深度优先遍历算法。给定当前访问起始节点，从其邻居中随机采样节点作为下一个访问节点，重复此过程，直到访问序列长度满足预设条件。 获取足够数量的节点访问序列后，使用skip-gram model 进行向量学习。 具体见[[Datawhale][CS224W]图机器学习(四)](https://blog.csdn.net/weixin_45856170/article/details/129070015) 1.6 DeepWalk 核心代码 DeepWalk算法主要包括两个步骤，第一步为随机游走采样节点序列，第二步为使用skip-gram modelword2vec学习表达向量。 ①构建同构网络，从网络中的每个节点开始分别进行Random Walk 采样，得到局部相关联的训练数据； ②对采样数据进行SkipGram训练，将离散的网络节点表示成向量化，最大化节点共现，使用Hierarchical Softmax来做超大规模分类的分类器 Random Walk 我们可以通过并行的方式加速路径采样，在采用多进程进行加速时，相比于开一个进程池让每次外层循环启动一个进程，我们采用固定为每个进程分配指定数量的num_walks的方式，这样可以最大限度减少进程频繁创建与销毁的时间开销。 deepwalk_walk方法对应上一节伪代码中第6行，_simulate_walks对应伪代码中第3行开始的外层循环。最后的Parallel为多进程并行时的任务分配操作。 def deepwalk_walk(self, walk_length, start_node): walk = [start_node] while len(walk) &amp;lt; walk_length: cur = walk[-1] cur_nbrs = list(self.G.neighbors(cur)) if len(cur_nbrs) &amp;gt; 0: walk.append(random.choice(cur_nbrs)) else: break return walk def _simulate_walks(self, nodes, num_walks, walk_length,): walks = [] for _ in range(num_walks): random.shuffle(nodes) for v in nodes: walks.append(self.deepwalk_walk(alk_length=walk_length, start_node=v)) return walks results = Parallel(n_jobs=workers, verbose=verbose, )( delayed(self._simulate_walks)(nodes, num, walk_length) for num in partition_num(num_walks, workers)) walks = list(itertools.chain(*results)) Word2vec 这里就偷个懒直接用gensim里的Word2Vec了。 from gensim.models import Word2Vec w2v_model = Word2Vec(walks,sg=1,hs=1) DeepWalk应用 G = nx.read_edgelist('../data/wiki/Wiki_edgelist.txt',create_using=nx.DiGraph(),nodetype=None,data=[('weight',int)]) model = DeepWalk(G,walk_length=10,num_walks=80,workers=1) model.train(window_size=5,iter=3) embeddings = model.get_embeddings() evaluate_embeddings(embeddings) plot_embeddings(embeddings) 1.7 DeepWalk优缺点 优点 首个将深度学习和自然语言处理的思想用于图机器学习 在系数标注节点分类场景下，嵌入性能卓越 缺点 均匀随机游走，没有偏向的游走方向（Node2Vec） 需要大量随机游走序列训练 基于随机游走，管中窥豹。距离较远的两个节点无法相互影响。看不到全图信息。（图神经网络） 无监督，仅编码图的连接信息，没有利用节点的属性特征 没有真正用到神经网络和深度学习 二、Node2Vec 2.1 图嵌入 将数据转化为D维连续稠密的向量，包含了原来的节点的多种信息 2.2 Node2Vec 优化目标 设 $f(u)$是将顶点 $u$ 映射为embedding向量的映射函数,对于图中每个顶点$u$，定义 $N_s(u)$ 为通过采样策略 $S$采样出的顶点 $u$的近邻顶点集合。 node2vec优化的目标是给定每个顶点条件下，令其近邻顶点（如何定义近邻顶点很重要）出现的概率最大。 $max_f\sum_{u\in V}log Pr(N_s(U) f(u))$ 为了将上述最优化问题可解，文章提出两个假设： 条件独立性假设 假设给定源顶点下，其近邻顶点出现的概率与近邻集合中其余顶点无关。 $Pr(N_s(u) f(u))=\prod_{n_i f(u)}Pr(n_i f(u))$ 特征空间对称性假设 这里是说一个顶点作为源顶点和作为近邻顶点的时候共享同一套embedding向量。(对比LINE中的2阶相似度，一个顶点作为源点和近邻点的时候是拥有不同的embedding向量的) 在这个假设下，上述条件概率公式可表示为 $Pr(n_i f(u))={expf(n_i)\cdot f(u)}\over{\sum_{v\in V}expf(v)\cdot f(u)}$ 根据以上两个假设条件，最终的目标函数表示为 由于归一化因子 的计算代价高，所以采用负采样技术优化。 顶点序列采样策略 node2vec依然采用随机游走的方式获取顶点的近邻序列，不同的是node2vec采用的是一种有偏的随机游走。 给定当前顶点 v ，访问下一个顶点 x 的概率为 $\pi_{vx}$ 是顶点 v 和顶点 x 之间的未归一化转移概率， Z 是归一化常数。 node2vec引入两个超参数 p 和 q 来控制随机游走的策略，假设当前随机游走经过边 (t,v) 到达顶点 �v设 ，$\omega_{vx}$ 是顶点 v 和 x 之间的边权， $d_{tx}$为顶点 t 和顶点 x 之间的最短路径距离。 下面讨论超参数 p 和 q 对游走策略的影响 Return parameter,p 参数p控制重复访问刚刚访问过的顶点的概率。 注意到p仅作用于 $d_{tx}$=0 的情况，而$d_{tx}$=0 表示顶点 x 就是访问当前顶点 v 之前刚刚访问过的顶点。 那么若 p 较高，则访问刚刚访问过的顶点的概率会变低，反之变高。 In-out papameter,q q 控制着游走是向外还是向内，若 q&amp;gt;1 ，随机游走倾向于访问和 t 接近的顶点(偏向BFS)。若 q&amp;lt;1 ，倾向于访问远离 t 的顶点(偏向DFS)。 下面的图描述的是当从 t 访问到 v 时，决定下一个访问顶点时每个顶点对应的 $\alpha$ 。 设定p,q进行有偏随机游走 q节点小时更愿意进行BFS,p节点小时更愿意进行DFS 2.3 理论上的实现 2.4 Node2Vec代码实现 学习算法 采样完顶点序列后，剩下的步骤就和deepwalk一样了，用word2vec去学习顶点的embedding向量。 值得注意的是node2vecWalk中不再是随机抽取邻接点，而是按概率抽取，node2vec采用了Alias算法进行顶点采样。 Alias Method:时间复杂度O(1)的离散采样方法125 赞同 · 23 评论文章 node2vec核心代码 node2vecWalk 通过上面的伪代码可以看到，node2vec和deepwalk非常类似，主要区别在于顶点序列的采样策略不同，所以这里我们主要关注node2vecWalk的实现。 由于采样时需要考虑前面2步访问过的顶点，所以当访问序列中只有1个顶点时，直接使用当前顶点和邻居顶点之间的边权作为采样依据。 当序列多余2个顶点时，使用文章提到的有偏采样。 def node2vec_walk(self, walk_length, start_node): G = self.G alias_nodes = self.alias_nodes alias_edges = self.alias_edges walk = [start_node] while len(walk) &amp;lt; walk_length: cur = walk[-1] cur_nbrs = list(G.neighbors(cur)) if len(cur_nbrs) &amp;gt; 0: if len(walk) == 1: walk.append(cur_nbrs[alias_sample(alias_nodes[cur][0], alias_nodes[cur][1])]) else: prev = walk[-2] edge = (prev, cur) next_node = cur_nbrs[alias_sample(alias_edges[edge][0],alias_edges[edge][1])] walk.append(next_node) else: break return walk 构造采样表 preprocess_transition_probs分别生成alias_nodes和alias_edges，alias_nodes存储着在每个顶点时决定下一次访问其邻接点时需要的alias表（不考虑当前顶点之前访问的顶点）。alias_edges存储着在前一个访问顶点为 t ，当前顶点为 v 时决定下一次访问哪个邻接点时需要的alias表。 get_alias_edge方法返回的是在上一次访问顶点 t ，当前访问顶点为 v 时到下一个顶点 x 的未归一化转移概率 def get_alias_edge(self, t, v): G = self.G p = self.p q = self.q unnormalized_probs = [] for x in G.neighbors(v): weight = G[v][x].get('weight', 1.0)# w_vx if x == t:# d_tx == 0 unnormalized_probs.append(weight/p) elif G.has_edge(x, t):# d_tx == 1 unnormalized_probs.append(weight) else:# d_tx == 2 unnormalized_probs.append(weight/q) norm_const = sum(unnormalized_probs) normalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs] return create_alias_table(normalized_probs) def preprocess_transition_probs(self): G = self.G alias_nodes = {} for node in G.nodes(): unnormalized_probs = [G[node][nbr].get('weight', 1.0) for nbr in G.neighbors(node)] norm_const = sum(unnormalized_probs) normalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs] alias_nodes[node] = create_alias_table(normalized_probs) alias_edges = {} for edge in G.edges(): alias_edges[edge] = self.get_alias_edge(edge[0], edge[1]) self.alias_nodes = alias_nodes self.alias_edges = alias_edges return node2vec应用 使用node2vec在wiki数据集上进行节点分类任务和可视化任务。 wiki数据集包含 2,405 个网页和17,981条网页之间的链接关系，以及每个网页的所属类别。 通过简单的超参搜索，这里使用p=0.25,q=4的设置。 G = nx.read_edgelist('../data/wiki/Wiki_edgelist.txt',create_using=nx.DiGraph(),nodetype=None,data=[('weight',int)]) model = Node2Vec(G,walk_length=10,num_walks=80,p=0.25,q=4,workers=1) model.train(window_size=5,iter=3) embeddings = model.get_embeddings() evaluate_embeddings(embeddings) plot_embeddings(embeddings) 2.5 Node2Vec与DeepWalk相比的优点与特点 优点 Node2Vec解决图嵌入问题，将图中的每个节点映射为一个向量（嵌入） 向量（嵌入）包含了节点的语义信息（相邻社群和功能角色） 语义相似的节点，向量（嵌入）的距离也近。 向量（嵌入）用于后续的分类，聚类，link Predictin，推荐等任务。 特点 在DeepWalk完全随机游走的基础上，Node2Vec增加p,q参数，实现有偏随机游走。不同的p,q组合，对应了不同的探索范围和节点语义。 DFS深度优先探索，相邻的节点，向量（嵌入）距离相近 BFS广度优先探索，相同功能角色的节点，向量（嵌入）距离相近。 DeepWalk时Node2Vec在p=1,q=1的特例 2.6 Node2Vec的优缺点 优点 首次通过调节p,q值，实现了有偏随机游走，探索节点社群，功能等不同属性 首次将节点分类用于Link Prediction 可解释性，可扩展性好，性能卓越 缺点 需要大量随机游走序列训练 距离较远的两个界定啊无法直接相互影响。看不到全图信息。（图神经网络） 无监督，仅编码图的连接信息，没有利用节点的属性特征（图卷积） 没有真正用到神经网络和深度学习 参考文献 [1] 斯坦福CS224W图机器学习、图神经网络、知识图谱【同济子豪兄】 [2] 【Graph Embedding】DeepWalk：算法原理，实现和应用 [3] 【Graph Embedding】node2vec：算法原理，实现和应用</summary></entry><entry><title type="html">【Datawhalw】【CS224W】图神经网络（四）</title><link href="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E5%9B%9B)/" rel="alternate" type="text/html" title="【Datawhalw】【CS224W】图神经网络（四）" /><published>2023-02-20T00:00:00+00:00</published><updated>2023-02-20T00:00:00+00:00</updated><id>https://wumorfr.github.io/%5BDatawhale%5D%5BCS224W%5D%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E5%9B%9B)</id><content type="html" xml:base="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E5%9B%9B)/">&lt;p&gt;Datawhale开源学习社区 x 同济子豪兄 Stanford课程中文精讲系列笔记&lt;/p&gt;

&lt;h2 id=&quot;一回顾&quot;&gt;一、回顾&lt;/h2&gt;

&lt;p&gt;本门课程主线是将图转化为连续稠密的向量，本文及之前的文章均为不讲属性特征，只讲社群连接特征。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;如何将节点转化为D维向量&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;人工特征学习：节点重要度，集群系数，Graphlet&lt;/li&gt;
  &lt;li&gt;图表式学习：通过&lt;strong&gt;随机游走&lt;/strong&gt;构造&lt;strong&gt;自监督学习网络&lt;/strong&gt;。DeepWalk,Node2Vec&lt;/li&gt;
  &lt;li&gt;矩阵分解&lt;/li&gt;
  &lt;li&gt;深度学习：图神经网络&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;本文主要讲的是&lt;strong&gt;图嵌入&lt;/strong&gt;(Graph Embedding)&lt;/p&gt;

&lt;p&gt;由节点，边，子图，全图，基于手工构造特征，矩阵分解，随机游走，图神经网络&lt;/p&gt;

&lt;h2 id=&quot;二图嵌入概述&quot;&gt;二、图嵌入概述&lt;/h2&gt;

&lt;h3 id=&quot;21-补充知识表示学习&quot;&gt;2.1 补充知识——表示学习&lt;/h3&gt;

&lt;p&gt;表示学习：自动学习特征。将各模态输入转为向量&lt;/p&gt;

&lt;h3 id=&quot;22-图嵌入&quot;&gt;2.2 图嵌入&lt;/h3&gt;

&lt;p&gt;只利用节点&lt;strong&gt;连接信息&lt;/strong&gt;，没有节点&lt;strong&gt;属性信息&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;将节点映射为d维向量&lt;/p&gt;

&lt;p&gt;低维：向量维度远小于节点数&lt;/p&gt;

&lt;p&gt;连续：每个元素都是实数（有正有负，有大有小）&lt;/p&gt;

&lt;p&gt;稠密：每个元素都不为0&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220185833863.png&quot; alt=&quot;image-20230220185833863&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;23-图嵌入-基本框架-编码器解码器&quot;&gt;2.3 图嵌入-基本框架 编码器——解码器&lt;/h3&gt;

&lt;h4 id=&quot;231-编码器&quot;&gt;2.3.1 编码器&lt;/h4&gt;

&lt;ol&gt;
  &lt;li&gt;实现功能：输入一个节点，输出这个节点对应的D维向量&lt;/li&gt;
  &lt;li&gt;最简单的编码器：查表（将所有节点的相关度直接写为一张表）$ENC(v)=z_v=Z\cdot v$&lt;/li&gt;
  &lt;li&gt;Z表示一个矩阵，每一列表示一个节点，行数表示向量的维度&lt;/li&gt;
  &lt;li&gt;优化Z矩阵的方法：DeepWalk、Node2Vec&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220192547135.png&quot; alt=&quot;image-20230220192547135&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;232-解码器&quot;&gt;2.3.2 解码器&lt;/h4&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;实现功能：输入需人为定义的节点相似度，输出向量点乘数值（余弦相似度）。&lt;/p&gt;

\[{similarity(u,v)\approx z_v^Tz_u}\]

    &lt;p&gt;e.g若定义两节点相连即位相似，则$if$两节点之间相连，则向量点乘数值会接近1；$else$节点不相连，则节点向量会接近垂直，向量点乘数值会接近0.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;直接优化嵌入向量，使用随机游走方式，如果两个节点出现在同一个随机游走序列中，就反映了这两个节点是相似的，并与下游任务无关&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h4 id=&quot;233-执行步骤&quot;&gt;2.3.3 执行步骤&lt;/h4&gt;

&lt;ol&gt;
  &lt;li&gt;编码器：节点-&amp;gt;D维向量。&lt;/li&gt;
  &lt;li&gt;定义一个节点相似度函数。&lt;/li&gt;
  &lt;li&gt;解码器DEC地图从嵌入到相似度评分。&lt;/li&gt;
  &lt;li&gt;迭代优化每个节点的D维向量，使得图中相似节点向量数量积大，不相似节点向量数量积小。&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;24-随机游走&quot;&gt;2.4 随机游走&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;定义：随机游走（英语：Random Walk，缩写为 RW），是一种数学统计模型，它是一连串的轨迹所组成，其中每一次都是随机的。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;可以与NLP一一对应&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220194958763.png&quot; alt=&quot;image-20230220194958763&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;241-随机游走的方法步骤&quot;&gt;2.4.1 随机游走的方法步骤&lt;/h4&gt;

&lt;ul&gt;
  &lt;li&gt;$P(v∣z_u)$：从$u$节点触发的随机游走序列经过$v$节点的概率&lt;/li&gt;
  &lt;li&gt;使用softmax方法计算$P(v∣z_u)$：$σ(z)[i]=\frac{e^{z[i]}}{∑^K_{j-1}e^{z[j]}}$&lt;/li&gt;
  &lt;li&gt;具体步骤：
    &lt;ol&gt;
      &lt;li&gt;采样得到若干随机游走序列，计算条件概率$P(v∣z_u)$&lt;/li&gt;
      &lt;li&gt;迭代优化每个节点的D维，使得序列中共现节点向量数量积大，不共现节点向量数量积小，计算结果反映了向量相似度&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
  &lt;li&gt;优点：表示能力、计算便捷、无监督/自监督学习问题（没用到任何标签）&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;使用极大似然估计，优化目标函数$\underset{f}{max}\mathop{\sum}\limits_{u\in V}logP(N_R(u)&lt;/td&gt;
          &lt;td&gt;z_u)$其中$N_R(u)$表示从&lt;em&gt;u&lt;/em&gt;节点出发的随机游走序列的所有邻域节点&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;整个优化的目标函数：&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220200120474.png&quot; alt=&quot;image-20230220200120474&quot; /&gt;其中&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220200137887.png&quot; alt=&quot;image-20230220200137887&quot; /&gt;遍历所有节点，并遍历从&lt;em&gt;u&lt;/em&gt;节点出发的随机游走序列的所有邻域节点，计算节点u&lt;em&gt;和节点v&lt;/em&gt;在该随机游走序列中共现。&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;242-计算优化&quot;&gt;2.4.2 计算优化&lt;/h4&gt;

&lt;p&gt;1.负采样&lt;/p&gt;

&lt;p&gt;$log(\frac{exp(z_u^Tz_v)}{\mathop{\sum}\limits_{n\in V}exp(z_u^Tz_{n})})\approx log(\sigma(z_u^Tz_{v}))-\mathop{\sum}\limits_{i=1}^{k}log(\sigma(z_u^Tz_{ni})),n_i ~P_v(非均匀分布采样)$&lt;/p&gt;

&lt;p&gt;2.k的选择，最好在5~20之间&lt;/p&gt;

&lt;p&gt;3.理论上同一个随机游走序列中的节点不应当被用为负样本，但是在图神经网络中，图的样本足够大，使得很难重复，因此使用同一图&lt;/p&gt;

&lt;h2 id=&quot;三随机梯度下降&quot;&gt;三、随机梯度下降&lt;/h2&gt;

&lt;h3 id=&quot;31-sgd步骤&quot;&gt;3.1 SGD步骤&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;采样，生成Mini-batch&lt;/li&gt;
  &lt;li&gt;前向推断，或损失函数&lt;/li&gt;
  &lt;li&gt;反向传播，求每个权重的更新速度&lt;/li&gt;
  &lt;li&gt;优化更新权重&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;32-批处理&quot;&gt;3.2 批处理&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220203022270.png&quot; alt=&quot;image-20230220203022270&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;四node2vec&quot;&gt;四、node2vec&lt;/h2&gt;

&lt;p&gt;可设置深度优先还是广度优先&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220203236213.png&quot; alt=&quot;image-20230220203236213&quot; /&gt;&lt;/p&gt;

&lt;p&gt;由两个参数p,q控制是上回还是去下一个节点&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220203223341.png&quot; alt=&quot;image-20230220203223341&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Node2Vec算法：&lt;/p&gt;

&lt;p&gt;计算每条边的随机游走概率&lt;/p&gt;

&lt;p&gt;以&lt;em&gt;u&lt;/em&gt;节点为出发点，长度为l&lt;em&gt;，生成r&lt;/em&gt;个随机游走序列&lt;/p&gt;

&lt;p&gt;用随机梯度下降优化目标函数&lt;/p&gt;

&lt;h2 id=&quot;五基于随机游走的图嵌入的缺点&quot;&gt;五、基于随机游走的图嵌入的缺点：&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;随机游走的图嵌入方法都是对图中已有的节点计算特征，无法立刻泛化到新加入的节点，其实是某种程度的过拟合&lt;/li&gt;
  &lt;li&gt;只是探索相邻局部信息，只能采样出地理上相近的节点&lt;/li&gt;
  &lt;li&gt;仅利用图本身的连接信息，并没有使用属性信息&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;六deepwalk优缺点&quot;&gt;六、deepwalk优缺点&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230220204037089.png&quot; alt=&quot;image-20230220204037089&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;参考文献&quot;&gt;参考文献&lt;/h1&gt;

&lt;p&gt;[1] &lt;a href=&quot;[斯坦福CS224W图机器学习、图神经网络、知识图谱[同济子豪兄]]https://www.bilibili.com/video/BV1pR4y1S7GA?vd_source=872fc2755b4c0ffb1be2bc7240a69fed&quot;&gt;斯坦福CS224W图机器学习、图神经网络、知识图谱【同济子豪兄】&lt;/a&gt;&lt;/p&gt;</content><author><name>乌墨_rfr</name></author><category term="Datawhale" /><category term="CS224W" /><category term="图神经网络" /><summary type="html">Datawhale开源学习社区 x 同济子豪兄 Stanford课程中文精讲系列笔记 一、回顾 本门课程主线是将图转化为连续稠密的向量，本文及之前的文章均为不讲属性特征，只讲社群连接特征。 如何将节点转化为D维向量 人工特征学习：节点重要度，集群系数，Graphlet 图表式学习：通过随机游走构造自监督学习网络。DeepWalk,Node2Vec 矩阵分解 深度学习：图神经网络 本文主要讲的是图嵌入(Graph Embedding) 由节点，边，子图，全图，基于手工构造特征，矩阵分解，随机游走，图神经网络 二、图嵌入概述 2.1 补充知识——表示学习 表示学习：自动学习特征。将各模态输入转为向量 2.2 图嵌入 只利用节点连接信息，没有节点属性信息 将节点映射为d维向量 低维：向量维度远小于节点数 连续：每个元素都是实数（有正有负，有大有小） 稠密：每个元素都不为0 2.3 图嵌入-基本框架 编码器——解码器 2.3.1 编码器 实现功能：输入一个节点，输出这个节点对应的D维向量 最简单的编码器：查表（将所有节点的相关度直接写为一张表）$ENC(v)=z_v=Z\cdot v$ Z表示一个矩阵，每一列表示一个节点，行数表示向量的维度 优化Z矩阵的方法：DeepWalk、Node2Vec 2.3.2 解码器 实现功能：输入需人为定义的节点相似度，输出向量点乘数值（余弦相似度）。 \[{similarity(u,v)\approx z_v^Tz_u}\] e.g若定义两节点相连即位相似，则$if$两节点之间相连，则向量点乘数值会接近1；$else$节点不相连，则节点向量会接近垂直，向量点乘数值会接近0. 直接优化嵌入向量，使用随机游走方式，如果两个节点出现在同一个随机游走序列中，就反映了这两个节点是相似的，并与下游任务无关 2.3.3 执行步骤 编码器：节点-&amp;gt;D维向量。 定义一个节点相似度函数。 解码器DEC地图从嵌入到相似度评分。 迭代优化每个节点的D维向量，使得图中相似节点向量数量积大，不相似节点向量数量积小。 2.4 随机游走 定义：随机游走（英语：Random Walk，缩写为 RW），是一种数学统计模型，它是一连串的轨迹所组成，其中每一次都是随机的。 可以与NLP一一对应 2.4.1 随机游走的方法步骤 $P(v∣z_u)$：从$u$节点触发的随机游走序列经过$v$节点的概率 使用softmax方法计算$P(v∣z_u)$：$σ(z)[i]=\frac{e^{z[i]}}{∑^K_{j-1}e^{z[j]}}$ 具体步骤： 采样得到若干随机游走序列，计算条件概率$P(v∣z_u)$ 迭代优化每个节点的D维，使得序列中共现节点向量数量积大，不共现节点向量数量积小，计算结果反映了向量相似度 优点：表示能力、计算便捷、无监督/自监督学习问题（没用到任何标签） 使用极大似然估计，优化目标函数$\underset{f}{max}\mathop{\sum}\limits_{u\in V}logP(N_R(u) z_u)$其中$N_R(u)$表示从u节点出发的随机游走序列的所有邻域节点 整个优化的目标函数：其中遍历所有节点，并遍历从u节点出发的随机游走序列的所有邻域节点，计算节点u和节点v在该随机游走序列中共现。 2.4.2 计算优化 1.负采样 $log(\frac{exp(z_u^Tz_v)}{\mathop{\sum}\limits_{n\in V}exp(z_u^Tz_{n})})\approx log(\sigma(z_u^Tz_{v}))-\mathop{\sum}\limits_{i=1}^{k}log(\sigma(z_u^Tz_{ni})),n_i ~P_v(非均匀分布采样)$ 2.k的选择，最好在5~20之间 3.理论上同一个随机游走序列中的节点不应当被用为负样本，但是在图神经网络中，图的样本足够大，使得很难重复，因此使用同一图 三、随机梯度下降 3.1 SGD步骤 采样，生成Mini-batch 前向推断，或损失函数 反向传播，求每个权重的更新速度 优化更新权重 3.2 批处理 四、node2vec 可设置深度优先还是广度优先 由两个参数p,q控制是上回还是去下一个节点 Node2Vec算法： 计算每条边的随机游走概率 以u节点为出发点，长度为l，生成r个随机游走序列 用随机梯度下降优化目标函数 五、基于随机游走的图嵌入的缺点： 随机游走的图嵌入方法都是对图中已有的节点计算特征，无法立刻泛化到新加入的节点，其实是某种程度的过拟合 只是探索相邻局部信息，只能采样出地理上相近的节点 仅利用图本身的连接信息，并没有使用属性信息 六、deepwalk优缺点 参考文献 [1] 斯坦福CS224W图机器学习、图神经网络、知识图谱【同济子豪兄】</summary></entry><entry><title type="html">【Datawhalw】【CS224W】图神经网络（三）</title><link href="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%B8%89)/" rel="alternate" type="text/html" title="【Datawhalw】【CS224W】图神经网络（三）" /><published>2023-02-15T00:00:00+00:00</published><updated>2023-02-15T00:00:00+00:00</updated><id>https://wumorfr.github.io/%5BDatawhale%5D%5BCS224W%5D%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%B8%89)</id><content type="html" xml:base="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%B8%89)/">&lt;p&gt;Datawhale开源学习社区 x 同济子豪兄 Stanford课程中文精讲系列笔记&lt;/p&gt;

&lt;h2 id=&quot;一简介与准备&quot;&gt;一、简介与准备&lt;/h2&gt;

&lt;p&gt;NetworkX用于实现创建，操作和研究复杂网络的结构，动态功能&lt;/p&gt;

&lt;p&gt;几个常用链接&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;http://networkx.github.io/&quot;&gt;NetworkX 主页&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://networkx.github.io/documentation/stable/&quot;&gt;NetworkX 文档&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://networkx.github.io/documentation/stable/_downloads/networkx_reference.pdf&quot;&gt;NetworkX 文档 PDF&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;本文接下来使用环境包括&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;networkx&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;networkx&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mpl&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pandas&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib.colors&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mcolors&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# %matplotlib inline #anconda中使用时要添加
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# windows系统
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rcParams&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'font.sans-serif'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'SimHei'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 用来正常显示中文标签
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rcParams&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'axes.unicode_minus'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 用来正常显示正负号
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;二教程&quot;&gt;二、教程&lt;/h2&gt;

&lt;h3 id=&quot;21-下载安装&quot;&gt;2.1 下载安装&lt;/h3&gt;

&lt;p&gt;本人是使用pip安装（使用了清华源）&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;pip&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;install&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;networkx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;https&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pypi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tuna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tsinghua&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;simple&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;安装好后可在python环境下运行&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;networkx&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;nx.__version__: &quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;__version__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;进行校验输出，结果类似如下&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/93bb058b64864b8ea6118dd7264eb6b1.png&quot; alt=&quot;请添加图片描述&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;22-创建图&quot;&gt;2.2 创建图&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;本列表中2.2.2至2.2.9暂时视为不常用，因为本人初学使用时基本很少看到，了解即可，可视作资料库，用的时候再查。不过2.2.7中数据集有的时候会用可以多看两眼（笑）&lt;/strong&gt;&lt;/p&gt;

&lt;h4 id=&quot;221-常用图创建自定义图创建&quot;&gt;2.2.1 常用图创建（自定义图创建）&lt;/h4&gt;

&lt;h5 id=&quot;1创建图对象&quot;&gt;1.创建图对象&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;# 空无向图 （重要）
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiGraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# 空有向图 （重要）
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MultiGraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;# 空多重无向图 
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MultiDigraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 空多重有向图 
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;               &lt;span class=&quot;c1&quot;&gt;# 清空图
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h5 id=&quot;2添加图节点&quot;&gt;2.添加图节点&lt;/h5&gt;

&lt;p&gt;此处先创建一个无节点无连接的空图G和另一个首尾相连成串的Path Graph H&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'刘备'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  					   &lt;span class=&quot;c1&quot;&gt;# 添加单个节点
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_nodes_from&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'诸葛亮'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'曹操'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;		 &lt;span class=&quot;c1&quot;&gt;# 三、添加多个节点
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_nodes_from&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'关羽'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'武器'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'青龙偃月刀'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'武力值'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;90&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'智力值'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;80&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'张飞'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'武器'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'八丈蛇矛'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'武力值'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;85&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'智力值'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;75&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'吕布'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'武器'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'方天画戟'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'武力值'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'智力值'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;										&lt;span class=&quot;c1&quot;&gt;# 添加带属性的节点
&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_nodes_from&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;						&lt;span class=&quot;c1&quot;&gt;# 将H的节点添加到G中
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;G.nodes&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;G.len&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;							&lt;span class=&quot;c1&quot;&gt;# 将H本身作为一个节点添加进G中
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;G.nodes&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;G.len&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;结果：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/4bfa8b7a1df5515938e096ece8efbd9d.png&quot; alt=&quot;image-20230215163958329&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;注意：&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;add_node和add_nodes_from
 对于add_node加一个点来说，字符串是只添加了名字为整个字符串的节点。但是对于add_nodes_from加一组点来说，字符串表示了添加了每一个字符都代表的多个节点，exp：&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;spam&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#添加了一个名为spam的节点
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_nodes_from&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;spam&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#添加了4个节点，名为s,p,a,m
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;小结&lt;/strong&gt;
节点可以为任意可哈希的对象，比如字符串、图像、XML对象，甚至另一个Graph、自定义的节点对象
通过这种方式可以根据自己的使用灵活的自由构建：以图、文件、函数为节点等灵活的图的形式&lt;/p&gt;

&lt;h5 id=&quot;3创建连接&quot;&gt;3.创建连接&lt;/h5&gt;

&lt;p&gt;此处先创建无向空图G和有向空图H&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 创建无向空图
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_directed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 给整张图添加属性特征
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Name'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;HelloWord&quot;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 创建有向空图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiGraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_directed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;输出：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/beef0490f52a4140a6f087bfe99bd5f8.png&quot; alt=&quot;请添加图片描述&quot; /&gt;
&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/ece5f9d1a50786bf396c1a50464cb42a.png&quot; alt=&quot;image-20230215164244721&quot; /&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;feature&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;zihao&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;		&lt;span class=&quot;c1&quot;&gt;# 创建单个节点，此处为创建0号节点，并添加特征属性
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_nodes_from&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'feature'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'label'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'zihao'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'feature'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'label'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'zihao'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;											&lt;span class=&quot;c1&quot;&gt;# 创建多个节点
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;全图节点信息：&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;number_of_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 遍历所有节点，data=True表示输出节点特征属性信息
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;node&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/1f3d02295a24cd24c644de0725591578.png&quot; alt=&quot;image-20230215164450313&quot; /&gt;&lt;/p&gt;

&lt;p&gt;此时点均为散点，后创立连接&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;like&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;	&lt;span class=&quot;c1&quot;&gt;# 创建单个连接，设置属性特征
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_edges_from&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'weight'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'like'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'weight'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'like'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;									&lt;span class=&quot;c1&quot;&gt;# 创建多个连接
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;连接情况&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215164802782.png&quot; alt=&quot;image-20230215164802782&quot; style=&quot;zoom: 80%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;全图连接信息&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;number_of_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 遍历所有连接，data=True表示输出连接特征属性信息
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/d991822e1d04acaacd891afc05b99189.png&quot; alt=&quot;image-20230215164857264&quot; /&gt;&lt;/p&gt;

&lt;p&gt;查询节点的连接数&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;指定节点&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;指定节点的所有相邻节点&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;neighbor&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Node {} has neighbor {}&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;format&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/3e5ed1b60daaac6fc42db7c2671a316a.png&quot; alt=&quot;image-20230215165055688&quot; /&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;所有节点&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;neighbor&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Node {} has neighbor {}&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;format&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/844c6645995cc798081319007d67808f.png&quot; alt=&quot;image-20230215165109487&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;222-经典图结构&quot;&gt;2.2.2 经典图结构&lt;/h4&gt;

&lt;h5 id=&quot;1全连接无向图&quot;&gt;1.全连接无向图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;complete_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 全图连接数
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;全图连接数:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215152516233.png&quot; alt=&quot;image-20230215152516233&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;2全连接有向图&quot;&gt;2.全连接有向图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;complete_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiGraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 是否是有向图
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;是否是有向图:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_directed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215152629209.png&quot; alt=&quot;image-20230215152629209&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;3环状图&quot;&gt;3.环状图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cycle_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215152737274.png&quot; alt=&quot;image-20230215152737274&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;4梯状图&quot;&gt;4.梯状图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ladder_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215153016675.png&quot; alt=&quot;image-20230215153016675&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;5线性串珠图&quot;&gt;5.线性串珠图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;path_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215153022746.png&quot; alt=&quot;image-20230215153022746&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;6星状图&quot;&gt;6.星状图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;star_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215153145635.png&quot; alt=&quot;image-20230215153145635&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;7轮辐图&quot;&gt;7.轮辐图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;wheel_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215160313034.png&quot; alt=&quot;image-20230215160313034&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;8二项树&quot;&gt;8.二项树&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;binomial_tree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215160429336.png&quot; alt=&quot;image-20230215160429336&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;223-栅格图&quot;&gt;2.2.3 栅格图&lt;/h4&gt;

&lt;h5 id=&quot;1二维矩形栅格图&quot;&gt;1.二维矩形栅格图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_2d_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215160351008.png&quot; alt=&quot;image-20230215160351008&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;2多维矩形栅格图&quot;&gt;2.多维矩形栅格图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215160508449.png&quot; alt=&quot;image-20230215160508449&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;3二维三角形栅格图&quot;&gt;3.二维三角形栅格图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;triangular_lattice_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161233443.png&quot; alt=&quot;image-20230215161233443&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;3二维六边形栅格图&quot;&gt;3.二维六边形栅格图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hexagonal_lattice_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161255890.png&quot; alt=&quot;image-20230215161255890&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;4n维超立方体图&quot;&gt;4.n维超立方体图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hypercube_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161303145.png&quot; alt=&quot;image-20230215161303145&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;224-networkx内置图&quot;&gt;2.2.4 NetworkX内置图&lt;/h4&gt;

&lt;h5 id=&quot;1钻石图&quot;&gt;1.钻石图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diamond_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161308922.png&quot; alt=&quot;image-20230215161308922&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;2牛角图&quot;&gt;2.牛角图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bull_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161314465.png&quot; alt=&quot;image-20230215161314465&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;3荔枝图虽然看不出跟荔枝有啥联系&quot;&gt;3.荔枝图？（虽然看不出跟荔枝有啥联系）&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;frucht_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161319011.png&quot; alt=&quot;image-20230215161319011&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;4房子图&quot;&gt;4.房子图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;house_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161324489.png&quot; alt=&quot;image-20230215161324489&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;5房子x图&quot;&gt;5.房子x图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;house_x_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161331817.png&quot; alt=&quot;image-20230215161331817&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;6风筝图&quot;&gt;6.风筝图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;krackhardt_kite_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161337898.png&quot; alt=&quot;image-20230215161337898&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;225-随机图&quot;&gt;2.2.5 随机图&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;erdos_renyi_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161343699.png&quot; alt=&quot;image-20230215161343699&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;226-无标量有向图&quot;&gt;2.2.6 无标量有向图&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale_free_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161510350.png&quot; alt=&quot;image-20230215161510350&quot; style=&quot;zoom:33%;&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;227-社交网络&quot;&gt;2.2.7 社交网络&lt;/h4&gt;

&lt;h5 id=&quot;1空手道俱乐部数据集&quot;&gt;1.空手道俱乐部数据集&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;karate_club_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;club&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;club&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161738105.png&quot; alt=&quot;image-20230215161738105&quot; style=&quot;zoom: 80%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;2雨果悲惨世界任务关系&quot;&gt;2.雨果《悲惨世界》任务关系&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;networkx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;les_miserables_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161745061.png&quot; alt=&quot;image-20230215161745061&quot; style=&quot;zoom: 80%;&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;3家庭关系图&quot;&gt;3.家庭关系图&lt;/h5&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;florentine_families_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161821925.png&quot; alt=&quot;image-20230215161821925&quot; style=&quot;zoom: 80%;&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;228-社群聚类图&quot;&gt;2.2.8 社群聚类图&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;caveman_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/image-20230215161817189.png&quot; alt=&quot;image-20230215161817189&quot; style=&quot;zoom:80%;&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;229-树结构&quot;&gt;2.2.9 树结构&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;tree&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random_tree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;forest_str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sources&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/f49484e043802abb579ac538b8566a4d.png&quot; alt=&quot;image-20230215161933569&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;23-常用信息获取&quot;&gt;2.3 常用信息获取&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;info&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# 图信息的概览
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;number_of_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;number_of_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 获取和节点idx连接的边的attr属性之和
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_degree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'attr'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 如果想知道某个结点相连的某个边权之和：
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodeIdx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'weightName'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 获取结点或者边的属性集合，返回的是元组的列表
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'attrName'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'attrName'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 获取n1 n2的边的length权重，那么:
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'length'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 如果是有重边的图，选择n1,n2第一条边的length权重，则:
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'length'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 获取n1结点的所有邻居
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;all_neighbors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 判断图中n1到n2是否存在路径
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;has_path&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 根据一个结点的list，获取子图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subG&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subgraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nodeList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;24-图可视化&quot;&gt;2.4 图可视化&lt;/h3&gt;

&lt;h4 id=&quot;241-初始化&quot;&gt;2.4.1 初始化&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;创建4&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;网格图&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;（&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;无向图&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;）&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_2d_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;242-原生可视化&quot;&gt;2.4.2 原生可视化&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;123&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;243-不显示节点&quot;&gt;2.4.3 不显示节点&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;244-设置颜色&quot;&gt;2.4.4 设置颜色&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;node_color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'#66ccff'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 节点颜色
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'red'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;# 节点外边缘颜色
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;edge_color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'blue'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# edge的颜色
&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# edge_cmap=plt.cm.coolwarm,# 配色方案
&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;800&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;245-无向图转有向图后显示&quot;&gt;2.4.5 无向图转有向图后显示&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;to_directed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;		&lt;span class=&quot;c1&quot;&gt;# 关键是这一句
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;node_color&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'#66ccff'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 节点颜色
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'red'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;# 节点外边缘颜色
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;edge_color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'tab:gray'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# edge的颜色
&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# edge_cmap=plt.cm.coolwarm,# 配色方案
&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;800&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;arrowsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;246-通过设置每个节点的坐标来显示图&quot;&gt;2.4.6 通过设置每个节点的坐标来显示图&lt;/h4&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# 无向图
# 初始化图
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(1,5)
G.add_edge(2,3)
G.add_edge(3,4)
G.add_edge(4,5)
nx.draw(G,with_labels=True)
plt.show()

# 关键代码
# 设置每个节点可视化的坐标
pos={1:(0,0),2:(-1,0.3),3:(2,0.17),4:(4,0.255),5:(5,0.03)}

# 设置其他可视化格式
options = {
    &quot;font_size&quot;:36,
    &quot;node_size&quot;:3000,
    &quot;node_color&quot;:&quot;white&quot;,
    &quot;edgecolors&quot;:&quot;black&quot;,
    &quot;linewidths&quot;:5, # 节点线宽
    &quot;width&quot;: 5,     # edge线宽
}

nx.draw_networkx(G,pos,**options)

ax=plt.gca()
ax.margins(0.20)    # 在图的边缘留白，防止节点被截断
plt.axis(&quot;off&quot;)
plt.show()


# 有向图
G = nx.DiGraph([(0,3),(1,3),(2,4),(3,5),(3,6),(4,6),(5,6)])
nx.draw(G,with_labels=True)
plt.show()


# 可视化每一列包含的节点
left_nodes=[0,1,2]
middle_nodes=[3,4]
right_nodes=[5,6]

# 可视化时每个节点的坐标
pos = {n:(0,i) for i ,n in enumerate(left_nodes)}
pos.update({n:(1,i+0.5)for i,n in enumerate(middle_nodes)})
pos.update({n:(2,i+0.5)for i,n in enumerate(right_nodes)})

print(pos)


nx.draw_networkx(G,pos,**options)

ax=plt.gca()
ax.margins(0.20)    # 在图的边缘留白，防止节点被截断
plt.axis(&quot;off&quot;)
plt.show()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;247-绘制房子图例子&quot;&gt;2.4.7 绘制房子图（例子）&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 尝试绘制房子图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodelist&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;#66ccff&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodelist&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;tab:orange&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;off&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;# 关闭坐标轴
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;248-可视化模板重要&quot;&gt;2.4.8 可视化模板（重要）&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 一、基础可视化
# 创建有向图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;114514&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random_k_out_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 初步可视化
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 二、高级可视化
# 节点大小
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 节点颜色
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;M&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;number_of_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;edge_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;M&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 节点透明度
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge_alphas&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;M&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;M&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge_alphas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 配色方案
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get_cmap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'plasma'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# cmap = plt.cm.Blues
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 绘制节点
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;indigo&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 绘制链接
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# 节点尺寸
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;arrowstyle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;-&amp;gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# 箭头样式
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;arrowsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# 箭头尺寸
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;edge_color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 连接颜色
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;edge_cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;         &lt;span class=&quot;c1&quot;&gt;# 连接配色方案
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;                 &lt;span class=&quot;c1&quot;&gt;# 连接线宽
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 设置每个连接的透明度
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;M&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set_alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge_alphas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 调色图例
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mpl&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;collections&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PathCollection&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;colorbar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gca&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set_axis_off&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;249-自我中心图ego图&quot;&gt;2.4.9 自我中心图(ego图)&lt;/h4&gt;

&lt;p&gt;Ego graph指距离中心节点小于特定距离（特定路径长度）的所有结点构成的图，特定距离通常为1，即与中心节点直接有边连接。例如，假设下图左为一个完整的图，图右为以$D$为中心节点的ego-graph。换句话说，所谓的ego network，它的节点是由唯一的一个中心节点(ego)，以及这个节点的邻居(alters)组成的，它的边只包括了ego和alter之间，以及alter与alter之间的边。&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;有的也称为Ego Network。&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/f306f47efd404bbea43eb9d9cf131196.png&quot; alt=&quot;ego-graph&quot; style=&quot;zoom: 25%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/1067417632d770c55e3a3875738bf4d5.jpeg&quot; alt=&quot;egonet3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;其中，图里面的每个alter和它自身的邻居又可以构成一个ego network，而所有节点的ego network合并起来，就可以组成真实的social network了。&lt;/p&gt;

&lt;p&gt;Ego graph中的中心被称为ego（$D$），而其它与ego连接的节点被称为alter（$A,B,C,E,F$）。&lt;/p&gt;

&lt;p&gt;在ego图中，除了ego与alter之间有边外，例如${DA, DB,DC,DE,DF}$，alter和alter之间也可以存在边（可选的，可能存在也可能不存在），例如${AC,AB,AE,BC,CE}$。&lt;/p&gt;

&lt;p&gt;跟ego graph有关联的有一个称之为N-step neighborhood的概念，它指的是与同ego间路径长度为$N$的所有“邻居”。&lt;/p&gt;

&lt;h3 id=&quot;25-图相关数据分析&quot;&gt;2.5 图相关数据分析&lt;/h3&gt;

&lt;h4 id=&quot;251-计算pagerank节点重要度&quot;&gt;2.5.1 计算PageRank节点重要度&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;star_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 计算PageRank节点重要度
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;PageRank&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pagerank&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PageRank&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;252-最大连通域子图&quot;&gt;2.5.2 最大连通域子图&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 一、创建图
# 创建 Erdos-Renyi 随机图，也称作 binomial graph
# n-节点数
# p-任意两个节点产生连接的概率
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gnp_random_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10374196&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 初步可视化
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 二、最大连通阈子图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gcc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subgraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;connected_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reverse&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gcc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1039653&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gcc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gcc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;253-每个节点的连接数degree&quot;&gt;2.5.3 每个节点的连接数（degree）&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gnp_random_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10374196&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 排序一下
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree_sequence&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reverse&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree_sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;254-一些可能用到的图的基础数据&quot;&gt;2.5.4 一些可能用到的图的基础数据&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &lt;span class=&quot;n&quot;&gt;导入图&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 第一个参数指定头部节点数，第二个参数指定尾部节点数
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lollipop_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 可视化
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3068&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 图数据分析
# 半径
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 直径
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 偏心度：每个节点到图中其它节点的最远距离
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eccentricity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 中心节点，偏心度与半径相等的节点
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 外围节点，偏心度与直径相等的节点
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;periphery&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 3号节点到图中其它节点的最短距离
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;single_source_shortest_path_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;node_id&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 每两个节点之间的最短距离
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pathlengths&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;spl&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;single_source_shortest_path_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;spl&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'{} --&amp;gt; {} 最短距离 {}'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;format&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;spl&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pathlengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spl&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 平均最短距离
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pathlengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pathlengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 不同距离的节点对个数
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pathlengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;255-节点特征重要&quot;&gt;2.5.5 节点特征（重要）&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 可视化辅助函数
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;measures&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;measure_name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;250&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get_cmap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'plasma'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                                   &lt;span class=&quot;n&quot;&gt;node_color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;measures&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()),&lt;/span&gt;
                                   &lt;span class=&quot;n&quot;&gt;nodelist&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;measures&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keys&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mcolors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SymLogNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linthresh&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linscale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# labels = nx.draw_networkx_labels(G, pos)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw_networkx_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# plt.figure(figsize=(10,8))
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;measure_name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;colorbar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'off'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# 导入无向图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;karate_club_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;675&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 导入有向图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiGraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_edges_from&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# dpos = {1: [0.1, 0.9], 2: [0.4, 0.8], 3: [0.8, 0.9], 4: [0.15, 0.55],
#         5: [0.5,  0.5], 6: [0.8,  0.5], 7: [0.22, 0.3], 8: [0.30, 0.27],
#         9: [0.38, 0.24], 10: [0.7,  0.3], 11: [0.75, 0.35]}
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Node Degree
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 字典按值排序
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reverse&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'Node Degree'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 节点重要度特征(节点的度，相当于将节点数归一化后的结果) Centrality
# Degree Centrality-无向图
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;degree_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'Degree Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Degree Centrality-有向图
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_degree_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_degree_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_degree_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'DiGraph Degree Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_degree_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'DiGraph Degree Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Eigenvector Centrality-无向图（特征向量重要度）
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvector_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvector_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'Eigenvector Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Eigenvector Centrality-有向图（特征向量重要度）
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvector_centrality_numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigenvector_centrality_numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'DiGraph Eigenvector Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Betweenness Centrality（必经之地）
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;betweenness_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;betweenness_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'Betweenness Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Closeness Centrality（去哪儿都近）
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;closeness_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;closeness_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'Closeness Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# PageRank
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pagerank&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.85&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pagerank&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.85&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'DiGraph PageRank'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Katz Centrality
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;katz_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;katz_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'Katz Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;katz_centrality&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'DiGraph Katz Centrality'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# HITS Hubs and Authorities
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'DiGraph HITS Hubs'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DiG&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'DiGraph HITS Authorities'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# NetworkX文档：社群属性 Clustering
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 三角形个数
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;triangles&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;triangles&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;triangles&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'Triangles'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Clustering Coefficient
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clustering&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clustering&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clustering&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'Clustering Coefficient'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Bridges
# 如果某个连接断掉，会使连通域个数增加，则该连接是bridge。
# bridge连接不属于环的一部分。
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;675&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bridges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Common Neighbors 和 Jaccard Coefficient
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;675&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sorted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;common_neighbors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;preds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;jaccard_coefficient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;preds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;(&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) -&amp;gt; &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adamic_adar_index&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;(&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) -&amp;gt; &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Katz Index
# 节点u到节点v，路径为k的路径个数。
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy.linalg&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inv&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;karate_club_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 计算主特征向量
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;normalized_laplacian_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigvals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'最大特征值'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 折减系数
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 创建单位矩阵
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;I&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 计算 Katz Index
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;S&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;I&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;to_numpy_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;I&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;S&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;S&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;256-计算全图的graphlet&quot;&gt;2.5.6 计算全图的Graphlet&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 导入全图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;karate_club_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spring_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;123&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;with_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 指定Graphlet
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;complete_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;draw&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 匹配Graphlet，统计个数
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sub_nodes&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;itertools&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combinations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 遍历全图中，符合graphlet节点个数的所有节点组合
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;subg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subgraph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sub_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                                          &lt;span class=&quot;c1&quot;&gt;# 从全图中抽取出子图
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_connected&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_isomorphic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;# 如果子图是完整连通域，并且符合graphlet特征，输出原图节点编号
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;num&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;subg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;2.6.7 拉普拉斯矩阵特征值分解&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy.linalg&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 线性代数
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 创建图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 节点个数
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5000&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 连接个数
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gnm_random_graph&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5040&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 邻接矩阵（Adjacency Matrix）
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adjacency_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;todense&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 拉普拉斯矩阵（Laplacian Matrix）
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;laplacian_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 节点degree对角矩阵
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;D&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;todense&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 归一化拉普拉斯矩阵（Normalized Laplacian Matrix）
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L_n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;normalized_laplacian_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;todense&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;imshow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;todense&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 特征值分解
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eigvals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 最大特征值
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 最小特征值
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 特征值分布直方图
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bins&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xlim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# eigenvalues between 0 and 2
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Eigenvalue Histogram'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Frequency'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Eigenvalue'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fontsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tick_params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labelsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 设置坐标文字大小
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;参考文献&quot;&gt;参考文献&lt;/h1&gt;

&lt;p&gt;[1] &lt;a href=&quot;https://www.cnblogs.com/Rosebud/p/10483560.html&quot;&gt;NetworkX 图网络处理工具包 &lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[2] &lt;a href=&quot;https://www.jianshu.com/p/32ad1cec4eaf&quot;&gt;python 工具包 NetworkX 教程翻译&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[3] &lt;a href=&quot;https://blog.csdn.net/qq_42103091/article/details/124540809&quot;&gt;Ego Graph概念介绍&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[4] &lt;a href=&quot;https://greatpowerlaw.wordpress.com/2013/01/05/ego-network/&quot;&gt;ego network的概念&lt;/a&gt;&lt;/p&gt;</content><author><name>乌墨_rfr</name></author><category term="Datawhale" /><category term="CS224W" /><category term="图神经网络" /><summary type="html">Datawhale开源学习社区 x 同济子豪兄 Stanford课程中文精讲系列笔记 一、简介与准备 NetworkX用于实现创建，操作和研究复杂网络的结构，动态功能 几个常用链接 NetworkX 主页 NetworkX 文档 NetworkX 文档 PDF 本文接下来使用环境包括 import networkx import networkx as nx import matplotlib.pyplot as plt import matplotlib as mpl import pandas as pd import matplotlib.colors as mcolors # %matplotlib inline #anconda中使用时要添加 # windows系统 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示正负号 二、教程 2.1 下载安装 本人是使用pip安装（使用了清华源） pip install networkx -i https://pypi.tuna.tsinghua.edu.cn/simple 安装好后可在python环境下运行 import networkx as nx print(&quot;nx.__version__: &quot; + nx.__version__) 进行校验输出，结果类似如下 2.2 创建图 本列表中2.2.2至2.2.9暂时视为不常用，因为本人初学使用时基本很少看到，了解即可，可视作资料库，用的时候再查。不过2.2.7中数据集有的时候会用可以多看两眼（笑） 2.2.1 常用图创建（自定义图创建） 1.创建图对象 G = nx.Graph() # 空无向图 （重要） G = nx.DiGraph() # 空有向图 （重要） G = nx.MultiGraph() # 空多重无向图 G = nx.MultiDigraph() # 空多重有向图 G.clear() # 清空图 2.添加图节点 此处先创建一个无节点无连接的空图G和另一个首尾相连成串的Path Graph H G =nx.Graph() H =nx.path_graph(10) G.add_node('刘备') # 添加单个节点 G.add_nodes_from(['诸葛亮','曹操']) # 三、添加多个节点 G.add_nodes_from([ ('关羽',{'武器':'青龙偃月刀','武力值':90,'智力值':80}), ('张飞',{'武器':'八丈蛇矛','武力值':85,'智力值':75}), ('吕布',{'武器':'方天画戟','武力值':100,'智力值':70}) ]) # 添加带属性的节点 G.add_nodes_from(H) # 将H的节点添加到G中 print(&quot;G.nodes&quot;,G.nodes) print(&quot;G.len&quot;,len(G)) G.add_node(H) # 将H本身作为一个节点添加进G中 print(&quot;G.nodes&quot;,G.nodes) print(&quot;G.len&quot;,len(G)) 结果： 注意： add_node和add_nodes_from 对于add_node加一个点来说，字符串是只添加了名字为整个字符串的节点。但是对于add_nodes_from加一组点来说，字符串表示了添加了每一个字符都代表的多个节点，exp： g.add_node(&quot;spam&quot;) #添加了一个名为spam的节点 g.add_nodes_from(&quot;spam&quot;) #添加了4个节点，名为s,p,a,m 小结 节点可以为任意可哈希的对象，比如字符串、图像、XML对象，甚至另一个Graph、自定义的节点对象 通过这种方式可以根据自己的使用灵活的自由构建：以图、文件、函数为节点等灵活的图的形式 3.创建连接 此处先创建无向空图G和有向空图H # 创建无向空图 G = nx.Graph() print(G.is_directed()) # 给整张图添加属性特征 G.graph['Name'] = &quot;HelloWord&quot; print(G.graph) # 创建有向空图 H = nx.DiGraph() print(H.is_directed()) 输出： G.add_node(0,feature=5,label=0,zihao=2) # 创建单个节点，此处为创建0号节点，并添加特征属性 G.add_nodes_from([ (1,{'feature':1,'label':1,'zihao':3}), (2,{'feature':2,'label':2,'zihao':4}) ]) # 创建多个节点 全图节点信息： print(G.number_of_nodes()) print(G.nodes) print(G.nodes(data=True)) # 遍历所有节点，data=True表示输出节点特征属性信息 for node in G.nodes(data=True): print(node) 此时点均为散点，后创立连接 G.add_edge(0,1,weight=0.5,like=3) # 创建单个连接，设置属性特征 G.add_edges_from([ (1,2,{'weight':0.3,'like':5}), (2,0,{'weight':0.1,'like':8}) ]) # 创建多个连接 连接情况 全图连接信息 print(G.number_of_nodes()) print(G.size()) print(G.edges()) print(G.edges(data=True)) # 遍历所有连接，data=True表示输出连接特征属性信息 for edge in G.edges(data=True): print(edge) 查询节点的连接数 指定节点 node_id=1 print(G.degree[node_id]) 指定节点的所有相邻节点 for neighbor in G.neighbors(node_id): print(&quot;Node {} has neighbor {}&quot;.format(node_id,neighbor)) 所有节点 for node_id in G.nodes(): for neighbor in G.neighbors(node_id): print(&quot;Node {} has neighbor {}&quot;.format(node_id,neighbor)) 2.2.2 经典图结构 1.全连接无向图 G = nx.complete_graph(7) nx.draw(G) plt.show() # 全图连接数 print(&quot;全图连接数:&quot;, G.size()) 2.全连接有向图 G = nx.complete_graph(7, nx.DiGraph()) nx.draw(G) plt.show() # 是否是有向图 print(&quot;是否是有向图:&quot;, G.is_directed()) 3.环状图 G = nx.cycle_graph(5) nx.draw(G) plt.show() 4.梯状图 G = nx.ladder_graph(5) nx.draw(G) plt.show() 5.线性串珠图 G = nx.path_graph(15) nx.draw(G) plt.show() 6.星状图 G = nx.star_graph(7) nx.draw(G) plt.show() 7.轮辐图 G = nx.wheel_graph(8) nx.draw(G) plt.show() 8.二项树 G = nx.binomial_tree(5) nx.draw(G) plt.show() 2.2.3 栅格图 1.二维矩形栅格图 G = nx.grid_2d_graph(3, 5) nx.draw(G) plt.show() 2.多维矩形栅格图 G = nx.grid_graph(dim=(2, 3, 4)) nx.draw(G) plt.show() 3.二维三角形栅格图 G = nx.triangular_lattice_graph(2, 5) nx.draw(G) plt.show() 3.二维六边形栅格图 G = nx.hexagonal_lattice_graph(2, 3) nx.draw(G) plt.show() 4.n维超立方体图 G = nx.hypercube_graph(4) nx.draw(G) plt.show() 2.2.4 NetworkX内置图 1.钻石图 G = nx.diamond_graph() nx.draw(G) plt.show() 2.牛角图 G = nx.bull_graph() nx.draw(G) plt.show() 3.荔枝图？（虽然看不出跟荔枝有啥联系） G = nx.frucht_graph() nx.draw(G) plt.show() 4.房子图 G = nx.house_graph() nx.draw(G) plt.show() 5.房子x图 G = nx.house_x_graph() nx.draw(G) plt.show() 6.风筝图 G = nx.krackhardt_kite_graph() nx.draw(G) plt.show() 2.2.5 随机图 G = nx.erdos_renyi_graph(10, 0.5) nx.draw(G) plt.show() 2.2.6 无标量有向图 G = nx.scale_free_graph(100) nx.draw(G) plt.show() 2.2.7 社交网络 1.空手道俱乐部数据集 G = nx.karate_club_graph() nx.draw(G, with_labels=True) plt.show() print(G.nodes[5][&quot;club&quot;]) print(G.nodes[9][&quot;club&quot;]) 2.雨果《悲惨世界》任务关系 G = networkx.les_miserables_graph() plt.figure(figsize=(12, 10)) pos = nx.spring_layout(G, seed=10) nx.draw(G, pos, with_labels=True) plt.show() plt.show() 3.家庭关系图 G = nx.florentine_families_graph() nx.draw(G, with_labels=True) plt.show() 2.2.8 社群聚类图 G = nx.caveman_graph(4, 3) nx.draw(G, with_labels=True) plt.show() 2.2.9 树结构 tree = nx.random_tree(n=10, seed=0) print(nx.forest_str(tree, sources=[0])) 2.3 常用信息获取 nx.info(G) # 图信息的概览 G.number_of_nodes() G.number_of_edges() # 获取和节点idx连接的边的attr属性之和 G.in_degree(idx, weight='attr') # 如果想知道某个结点相连的某个边权之和： DG.degree(nodeIdx, weight='weightName') # 获取结点或者边的属性集合，返回的是元组的列表 G.nodes.data('attrName') G.edges.data('attrName') # 获取n1 n2的边的length权重，那么: G[n1][n2]['length'] # 如果是有重边的图，选择n1,n2第一条边的length权重，则: G[n1][n2][0]['length'] # 获取n1结点的所有邻居 nx.all_neighbors(G, n1) # 判断图中n1到n2是否存在路径 nx.has_path(G, n1, n2) # 根据一个结点的list，获取子图 subG = nx.subgraph(G, nodeList) 2.4 图可视化 2.4.1 初始化 创建4*4网格图（无向图） G = nx.grid_2d_graph(4,4) 2.4.2 原生可视化 pos = nx.spring_layout(G,seed=123) nx.draw(G,pos) plt.show() 2.4.3 不显示节点 nx.draw(G,pos,node_size=0,with_labels=False) plt.show() 2.4.4 设置颜色 print(len(G.edges())) nx.draw( G, pos, node_color = '#66ccff', # 节点颜色 edgecolors='red', # 节点外边缘颜色 edge_color='blue', # edge的颜色 # edge_cmap=plt.cm.coolwarm,# 配色方案 node_size=800, with_labels=False, width=3, ) plt.show() 2.4.5 无向图转有向图后显示 nx.draw( G.to_directed(), # 关键是这一句 pos, node_color = '#66ccff', # 节点颜色 edgecolors='red', # 节点外边缘颜色 edge_color='tab:gray', # edge的颜色 # edge_cmap=plt.cm.coolwarm,# 配色方案 node_size=800, with_labels=False, width=3, arrowsize=10, ) plt.show() 2.4.6 通过设置每个节点的坐标来显示图 # 无向图 # 初始化图 G = nx.Graph() G.add_edge(1,2) G.add_edge(1,3) G.add_edge(1,5) G.add_edge(2,3) G.add_edge(3,4) G.add_edge(4,5) nx.draw(G,with_labels=True) plt.show() # 关键代码 # 设置每个节点可视化的坐标 pos={1:(0,0),2:(-1,0.3),3:(2,0.17),4:(4,0.255),5:(5,0.03)} # 设置其他可视化格式 options = { &quot;font_size&quot;:36, &quot;node_size&quot;:3000, &quot;node_color&quot;:&quot;white&quot;, &quot;edgecolors&quot;:&quot;black&quot;, &quot;linewidths&quot;:5, # 节点线宽 &quot;width&quot;: 5, # edge线宽 } nx.draw_networkx(G,pos,**options) ax=plt.gca() ax.margins(0.20) # 在图的边缘留白，防止节点被截断 plt.axis(&quot;off&quot;) plt.show() # 有向图 G = nx.DiGraph([(0,3),(1,3),(2,4),(3,5),(3,6),(4,6),(5,6)]) nx.draw(G,with_labels=True) plt.show() # 可视化每一列包含的节点 left_nodes=[0,1,2] middle_nodes=[3,4] right_nodes=[5,6] # 可视化时每个节点的坐标 pos = {n:(0,i) for i ,n in enumerate(left_nodes)} pos.update({n:(1,i+0.5)for i,n in enumerate(middle_nodes)}) pos.update({n:(2,i+0.5)for i,n in enumerate(right_nodes)}) print(pos) nx.draw_networkx(G,pos,**options) ax=plt.gca() ax.margins(0.20) # 在图的边缘留白，防止节点被截断 plt.axis(&quot;off&quot;) plt.show() 2.4.7 绘制房子图（例子） # 尝试绘制房子图 G = nx.Graph([(0,1),(0,2),(1,3),(2,3),(2,4),(3,4)]) pos = {0:(0,0),1:(1,0),2:(0,1),3:(1,1),4:(0.5,2.0)} plt.figure(figsize=(10,8)) nx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[0,1,2,3],node_color=&quot;#66ccff&quot;) nx.draw_networkx_nodes(G,pos,node_size=3000,nodelist=[4],node_color=&quot;tab:orange&quot;) nx.draw_networkx_edges(G,pos,alpha=0.5,width=6) plt.axis(&quot;off&quot;) # 关闭坐标轴 plt.show() 2.4.8 可视化模板（重要） # 一、基础可视化 # 创建有向图 seed=114514 G=nx.random_k_out_graph(10,3,0.5,seed=seed) pos=nx.spring_layout(G,seed=seed) # 初步可视化 nx.draw(G,pos=pos,with_labels=True) plt.show() # 二、高级可视化 # 节点大小 node_sizes = [12+10*i for i in range(len(G))] print(node_sizes) # 节点颜色 M = G.number_of_edges() edge_colors = range(2,M+2) print(edge_colors) # 节点透明度 edge_alphas = [(5+i)/(M+4)for i in range(M)] print(edge_alphas) # 配色方案 cmap = plt.get_cmap('plasma') # cmap = plt.cm.Blues plt.figure(figsize=(10,8)) # 绘制节点 nodes = nx.draw_networkx_nodes(G,pos,node_size=node_sizes,node_color=&quot;indigo&quot;) # 绘制链接 edges = nx.draw_networkx_edges( G, pos, node_size=node_sizes, # 节点尺寸 arrowstyle=&quot;-&amp;gt;&quot;, # 箭头样式 arrowsize=20, # 箭头尺寸 edge_color=edge_colors, # 连接颜色 edge_cmap=cmap, # 连接配色方案 width=4 # 连接线宽 ) # 设置每个连接的透明度 for i in range(M): edges[i].set_alpha(edge_alphas[i]) # 调色图例 pc = mpl.collections.PathCollection(edges,cmap=cmap) pc.set_array(edge_colors) plt.colorbar(pc) ax=plt.gca() ax.set_axis_off() plt.show() 2.4.9 自我中心图(ego图) Ego graph指距离中心节点小于特定距离（特定路径长度）的所有结点构成的图，特定距离通常为1，即与中心节点直接有边连接。例如，假设下图左为一个完整的图，图右为以$D$为中心节点的ego-graph。换句话说，所谓的ego network，它的节点是由唯一的一个中心节点(ego)，以及这个节点的邻居(alters)组成的，它的边只包括了ego和alter之间，以及alter与alter之间的边。 有的也称为Ego Network。 其中，图里面的每个alter和它自身的邻居又可以构成一个ego network，而所有节点的ego network合并起来，就可以组成真实的social network了。 Ego graph中的中心被称为ego（$D$），而其它与ego连接的节点被称为alter（$A,B,C,E,F$）。 在ego图中，除了ego与alter之间有边外，例如${DA, DB,DC,DE,DF}$，alter和alter之间也可以存在边（可选的，可能存在也可能不存在），例如${AC,AB,AE,BC,CE}$。 跟ego graph有关联的有一个称之为N-step neighborhood的概念，它指的是与同ego间路径长度为$N$的所有“邻居”。 2.5 图相关数据分析 2.5.1 计算PageRank节点重要度 G =nx.star_graph(7) nx.draw(G,with_labels=True) # 计算PageRank节点重要度 PageRank = nx.pagerank(G,alpha=0.8) print(PageRank) 2.5.2 最大连通域子图 # 一、创建图 # 创建 Erdos-Renyi 随机图，也称作 binomial graph # n-节点数 # p-任意两个节点产生连接的概率 G = nx.gnp_random_graph(100,0.02,seed=10374196) # 初步可视化 pos = nx.spring_layout(G,seed=10) nx.draw(G,pos) plt.show() # 二、最大连通阈子图 Gcc = G.subgraph(sorted(nx.connected_components(G),key=len,reverse=True)[0]) pos=nx.spring_layout(Gcc,seed=1039653) nx.draw_networkx_nodes(Gcc,pos,node_size=20) nx.draw_networkx_edges(Gcc,pos,alpha=0.4) plt.show() 2.5.3 每个节点的连接数（degree） G = nx.gnp_random_graph(100,0.02,seed=10374196) # 排序一下 degree_sequence = sorted((d for n, d in G.degree()), reverse=True) print(degree_sequence) 2.5.4 一些可能用到的图的基础数据 导入图 # 第一个参数指定头部节点数，第二个参数指定尾部节点数 G = nx.lollipop_graph(4, 7) # 可视化 pos = nx.spring_layout(G, seed=3068) nx.draw(G, pos=pos, with_labels=True) plt.show() # 图数据分析 # 半径 print(nx.radius(G)) # 直径 print(nx.diameter(G)) # 偏心度：每个节点到图中其它节点的最远距离 print(nx.eccentricity(G)) # 中心节点，偏心度与半径相等的节点 print(nx.center(G)) # 外围节点，偏心度与直径相等的节点 print(nx.periphery(G)) print(nx.density(G)) # 3号节点到图中其它节点的最短距离 node_id = 3 nx.single_source_shortest_path_length(G, node_id) # 每两个节点之间的最短距离 pathlengths = [] for v in G.nodes(): spl = nx.single_source_shortest_path_length(G, v) for p in spl: print('{} --&amp;gt; {} 最短距离 {}'.format(v, p, spl[p])) pathlengths.append(spl[p]) # 平均最短距离 print(sum(pathlengths) / len(pathlengths)) # 不同距离的节点对个数 dist = {} for p in pathlengths: if p in dist: dist[p] += 1 else: dist[p] = 1 print(dist) 2.5.5 节点特征（重要） # 可视化辅助函数 def draw(G, pos, measures, measure_name): nodes = nx.draw_networkx_nodes(G, pos, node_size=250, cmap=plt.cm.get_cmap('plasma'), node_color=list(measures.values()), nodelist=measures.keys()) nodes.set_norm(mcolors.SymLogNorm(linthresh=0.01, linscale=1)) # labels = nx.draw_networkx_labels(G, pos) edges = nx.draw_networkx_edges(G, pos) # plt.figure(figsize=(10,8)) plt.title(measure_name) plt.colorbar(nodes) plt.axis('off') plt.show() # 导入无向图 G = nx.karate_club_graph() pos = nx.spring_layout(G, seed=675) nx.draw(G, pos, with_labels=True) plt.show() # 导入有向图 DiG = nx.DiGraph() DiG.add_edges_from([(2, 3), (3, 2), (4, 1), (4, 2), (5, 2), (5, 4), (5, 6), (6, 2), (6, 5), (7, 2), (7, 5), (8, 2), (8, 5), (9, 2), (9, 5), (10, 5), (11, 5)]) # dpos = {1: [0.1, 0.9], 2: [0.4, 0.8], 3: [0.8, 0.9], 4: [0.15, 0.55], # 5: [0.5, 0.5], 6: [0.8, 0.5], 7: [0.22, 0.3], 8: [0.30, 0.27], # 9: [0.38, 0.24], 10: [0.7, 0.3], 11: [0.75, 0.35]} nx.draw(DiG, pos, with_labels=True) plt.show() # Node Degree print(list(nx.degree(G))) print(dict(G.degree())) # 字典按值排序 print(sorted(dict(G.degree()).items(), key=lambda x: x[1], reverse=True)) draw(G, pos, dict(G.degree()), 'Node Degree') # 节点重要度特征(节点的度，相当于将节点数归一化后的结果) Centrality # Degree Centrality-无向图 print(nx.degree_centrality(G)) draw(G, pos, nx.degree_centrality(G), 'Degree Centrality') # Degree Centrality-有向图 print(nx.in_degree_centrality(DiG)) print(nx.out_degree_centrality(DiG)) draw(DiG, pos, nx.in_degree_centrality(DiG), 'DiGraph Degree Centrality') draw(DiG, pos, nx.out_degree_centrality(DiG), 'DiGraph Degree Centrality') # Eigenvector Centrality-无向图（特征向量重要度） print(nx.eigenvector_centrality(G)) draw(G, pos, nx.eigenvector_centrality(G), 'Eigenvector Centrality') # Eigenvector Centrality-有向图（特征向量重要度） print(nx.eigenvector_centrality_numpy(DiG)) draw(DiG, pos, nx.eigenvector_centrality_numpy(DiG), 'DiGraph Eigenvector Centrality') # Betweenness Centrality（必经之地） print(nx.betweenness_centrality(G)) draw(G, pos, nx.betweenness_centrality(G), 'Betweenness Centrality') # Closeness Centrality（去哪儿都近） print(nx.closeness_centrality(G)) draw(G, pos, nx.closeness_centrality(G), 'Closeness Centrality') # PageRank print(nx.pagerank(DiG, alpha=0.85)) draw(DiG, pos, nx.pagerank(DiG, alpha=0.85), 'DiGraph PageRank') # Katz Centrality print(nx.katz_centrality(G, alpha=0.1, beta=1.0)) draw(G, pos, nx.katz_centrality(G, alpha=0.1, beta=1.0), 'Katz Centrality') draw(DiG, pos, nx.katz_centrality(DiG, alpha=0.1, beta=1.0), 'DiGraph Katz Centrality') # HITS Hubs and Authorities h, a = nx.hits(DiG) draw(DiG, pos, h, 'DiGraph HITS Hubs') draw(DiG, pos, a, 'DiGraph HITS Authorities') # NetworkX文档：社群属性 Clustering print(nx.draw(G, pos, with_labels=True)) # 三角形个数 print(nx.triangles(G)) print(nx.triangles(G, 0)) draw(G, pos, nx.triangles(G), 'Triangles') # Clustering Coefficient print(nx.clustering(G)) print(nx.clustering(G, 0)) draw(G, pos, nx.clustering(G), 'Clustering Coefficient') # Bridges # 如果某个连接断掉，会使连通域个数增加，则该连接是bridge。 # bridge连接不属于环的一部分。 pos = nx.spring_layout(G, seed=675) nx.draw(G, pos, with_labels=True) plt.show() print(list(nx.bridges(G))) # Common Neighbors 和 Jaccard Coefficient pos = nx.spring_layout(G, seed=675) nx.draw(G, pos, with_labels=True) plt.show() print(sorted(nx.common_neighbors(G, 0, 4))) preds = nx.jaccard_coefficient(G, [(0, 1), (2, 3)]) for u, v, p in preds: print(f&quot;({u}, {v}) -&amp;gt; {p:.8f}&quot;) for u, v, p in nx.adamic_adar_index(G, [(0, 1), (2, 3)]): print(f&quot;({u}, {v}) -&amp;gt; {p:.8f}&quot;) # Katz Index # 节点u到节点v，路径为k的路径个数。 import numpy as np from numpy.linalg import inv G = nx.karate_club_graph() print(len(G.nodes)) # 计算主特征向量 L = nx.normalized_laplacian_matrix(G) e = np.linalg.eigvals(L.A) print('最大特征值', max(e)) # 折减系数 beta = 1 / max(e) # 创建单位矩阵 I = np.identity(len(G.nodes)) # 计算 Katz Index S = inv(I - nx.to_numpy_array(G) * beta) - I print(S.shape) print(S.shape) 2.5.6 计算全图的Graphlet # 导入全图 G = nx.karate_club_graph() plt.figure(figsize=(10,8)) pos = nx.spring_layout(G, seed=123) nx.draw(G, pos, with_labels=True) # 指定Graphlet target = nx.complete_graph(3) nx.draw(target) plt.show() # 匹配Graphlet，统计个数 num = 0 for sub_nodes in itertools.combinations(G.nodes(), len(target.nodes())): # 遍历全图中，符合graphlet节点个数的所有节点组合 subg = G.subgraph(sub_nodes) # 从全图中抽取出子图 if nx.is_connected(subg) and nx.is_isomorphic(subg, target): # 如果子图是完整连通域，并且符合graphlet特征，输出原图节点编号 num += 1 print(subg.edges()) print(num) 2.6.7 拉普拉斯矩阵特征值分解 import numpy.linalg # 线性代数 # 创建图 n = 1000 # 节点个数 m = 5000 # 连接个数 G = nx.gnm_random_graph(n, m, seed=5040) # 邻接矩阵（Adjacency Matrix） A = nx.adjacency_matrix(G) print(A.shape) print(A.todense()) # 拉普拉斯矩阵（Laplacian Matrix） L = nx.laplacian_matrix(G) print(L.shape) # 节点degree对角矩阵 D = L + A print(D.todense()) # 归一化拉普拉斯矩阵（Normalized Laplacian Matrix） L_n = nx.normalized_laplacian_matrix(G) print(L_n.shape) print(L_n.todense()) plt.imshow(L_n.todense()) plt.show() print(type(L_n)) # 特征值分解 e = np.linalg.eigvals(L_n.A) print(e) # 最大特征值 print(max(e)) # 最小特征值 print(min(e)) # 特征值分布直方图 plt.figure(figsize=(12, 8)) plt.hist(e, bins=100) plt.xlim(0, 2) # eigenvalues between 0 and 2 plt.title('Eigenvalue Histogram', fontsize=20) plt.ylabel('Frequency', fontsize=25) plt.xlabel('Eigenvalue', fontsize=25) plt.tick_params(labelsize=20) # 设置坐标文字大小 plt.show() 参考文献 [1] NetworkX 图网络处理工具包 [2] python 工具包 NetworkX 教程翻译 [3] Ego Graph概念介绍 [4] ego network的概念</summary></entry><entry><title type="html">【Datawhalw】【CS224W】图神经网络（二）</title><link href="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%BA%8C)/" rel="alternate" type="text/html" title="【Datawhalw】【CS224W】图神经网络（二）" /><published>2023-02-14T00:00:00+00:00</published><updated>2023-02-14T00:00:00+00:00</updated><id>https://wumorfr.github.io/%5BDatawhale%5D%5BCS224W%5D%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%BA%8C)</id><content type="html" xml:base="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0(%E4%BA%8C)/">&lt;p&gt;Datawhale开源学习社区 x 同济子豪兄 Stanford课程中文精讲系列笔记&lt;/p&gt;

&lt;h2 id=&quot;一概述&quot;&gt;一、概述&lt;/h2&gt;

&lt;p&gt;图是一种常见的数据结构，是节点的集合以及这些节点之间关系的集合。图的强大之处在于关注节点之间的关系以及通用性，比如相同的图结构可以表示社交网络，也可以表示分子内原子的关系。当前语音与图像数据往往呈现一个Euclidean Structure（欧氏结构）的数据相关，而分子结构，社交网络，3D图像等往往呈现非欧氏结构，而研究非欧氏结构的一种方法就是图。机器学习不是分析图数据的唯一方法，但是在随着图数据规模和复杂性的增加，机器学习在图数据上的建模和分析起着越来越重要的作用。&lt;/p&gt;

&lt;h3 id=&quot;11-图的结构&quot;&gt;1.1 图的结构&lt;/h3&gt;

&lt;p&gt;图($Graph$)：$G = (V,\ E)$&lt;/p&gt;

&lt;p&gt;点($Vertices$)：$V= { v_1,v_2,…,v_n},n=6$&lt;/p&gt;

&lt;p&gt;边($Edge$)：$E={e_{1,2},e_{1,5},…,e_{4,6},\ e_{2,1},e_{5,1},…,e_{6,4}}$&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230102111023768.png&quot; alt=&quot;image-20230102111023768&quot; /&gt;&lt;/p&gt;

&lt;p&gt;=&amp;gt;邻接矩阵($Adjacency\ Matrix$)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230102111103938.png&quot; alt=&quot;image-20230102111103938&quot; /&gt;&lt;/p&gt;

&lt;p&gt;=&amp;gt;节点特征向量($Feature\ Vector\ of\ Nodes$)：$x=[x_1,x_2,…,x_6]^T,x_i\in R$&lt;/p&gt;

&lt;h3 id=&quot;12-特征处理&quot;&gt;1.2 特征处理&lt;/h3&gt;

&lt;p&gt;为了利用传统机器学习执行图上的计算任务，需要找到节点的表示形式。实现此目标的方法主要包含两种：特征工程和特征学习。特征工程需要手动设计特征，而特征学习可以自动学习节点的特征。手动的设计特征需要大量人力并且对于下游任务不一定就是最理想的，而特征学习可以由下游任务指导，学到可能适合下游任务的特征，获取更好的性能。&lt;/p&gt;

&lt;p&gt;大多数情况下，谈到的信息指的是节点层面的信息，如节点的属性信息，在极少数形况下，边会带有实值特征，更少数的情况是把实值特征和整张图关联起来得到图的特征信息。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;图特征选择(移除节点上无关和冗余的特征)&lt;/strong&gt;&lt;/p&gt;

    &lt;p&gt;特征选择旨在自动选择一小部分特征，具有最小的冗余度但于学习目标最相关。传统特征选择假定数据实例是独立同分布的，然而，许多应用中的数据样本是嵌入在图上的，本质上不是独立同分布的。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;图表示学习(生成一组新的节点特征)&lt;/strong&gt;&lt;/p&gt;

    &lt;p&gt;图表示学习的目的是生成新的节点特征，已经在谱聚类，基于图的降维，矩阵分解的背景下进行了研究。在谱聚类中，数据点作为图中的节点，然后聚类问题转化为将图划分为节点社区。谱聚类的关键是谱嵌入，旨在将节点嵌入到低维空间中，在该空间中使用传统聚类算法。基于图的降维技术可以直接用于学习节点表示。基于数据样本的原始特征，使用预定义的距离函数构建相似度图，通过保留相似度图得结构信息学习节点表示。矩阵是表示图的最流行的方法，矩阵分解目的是将节点嵌入到低维空间中，在该空间中利用新的节点表示重构邻接矩阵。图嵌入方法一般归为矩阵分解方法。&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;前文提到的方法都是基于浅层模型，随着深度学习的发展图神经网络受到了大家的关注。图神经网络大致分为基于空间的方法和谱方法。空间方法显式利用图结构，通过空间上的邻居节点信息来学习；谱方法利用图的谱视图，通过图的傅里叶变换和逆变换来学习节点表示。&lt;/p&gt;

&lt;h3 id=&quot;13-学习任务&quot;&gt;1.3 学习任务&lt;/h3&gt;

&lt;h4 id=&quot;131-节点分类&quot;&gt;1.3.1 节点分类&lt;/h4&gt;

&lt;p&gt;在现实场景中，节点常与有用的信息相关联，这些信息被视作标签，用于描述节点的特征。但是很难为所有节点获得完整的标签集，只有一部分节点有标签，而那些无标签的节点需要通过预测来得到，这就是节点分类任务。&lt;/p&gt;

&lt;p&gt;用$G=(V,E)$表示一个图，$V$为节点集，$E$为边集。节点集$V$中那些有标签的节点构成的子集记为Vl。节点分类的目标是利用图G(所有节点)和Vl的标签信息学习一个映射来预测无标签节点的标签。&lt;/p&gt;

&lt;p&gt;节点分类任务和标准的监督学习最重要的差别在于图中的节点不满足独立同分布假设。传统的监督学习要求每个样本与其他样本是独立的，否则建模时需要考虑样本之间的依赖关系。并且还需要样本分布相同，否则难以保证模型对新数据点适用。研究者根据节点分类任务的特点将其归为半监督学习，因为在训练过程中，图中的全部节点都被用到了，包括未标记的节点。但是标准的半监督学习也是以独立同分布为前提的，所以，图机器学习任务不是标准的机器学习任务。&lt;/p&gt;

&lt;h4 id=&quot;132-链接预测&quot;&gt;1.3.2 链接预测&lt;/h4&gt;

&lt;p&gt;在许多数据中，图并不是完整的，会缺失一些节点之间的连接，可能是因为未被观察或者图的自然演变。用G=(V,E)表示一个图，V为节点集，E为边集，M是所有可能的节点对。边的补集定义为H=M/E。链接预测的目的为H中每个边赋值，表示这条边出现的可能性。&lt;/p&gt;

&lt;h4 id=&quot;133-图级任务&quot;&gt;1.3.3 图级任务&lt;/h4&gt;

&lt;p&gt;图级别的任务包括图分类，图匹配，图生成，图回归，图聚类，社区发现等等。&lt;/p&gt;

&lt;p&gt;图分类是为每个图预测一个标签，而节点分类是为每个节点预测一个标签。给定一组带标签的图数据集D={(Gi, yi)}，其中yi是图Gi的标签，图分类任务的目的是学到一个映射预测未标记的图的标签。&lt;/p&gt;

&lt;p&gt;图聚类任务的目标是学习一个无监督的方法测量图与图之间的相似性。该任务的挑战是在考虑每张图内部结构关系的前提下定义有效特征。&lt;/p&gt;

&lt;p&gt;社区发现常被类比为图领域的无监督学习中的聚类任务，通过输入一张图，推断潜在的社区结构&lt;/p&gt;

&lt;h2 id=&quot;二传统方法&quot;&gt;二、传统方法&lt;/h2&gt;

&lt;p&gt;图表示学习之前已经有很多优秀的方法被提出。比如，在节点分类或图分类中用到的图的统计特征，核方法等；在关联预测时使用节点邻域重叠测量等方法。&lt;/p&gt;

&lt;p&gt;传统的使用图数据进行分类的方法遵循标准的机器学习范式。首先，基于启发式函数或邻域知识提取一些统计特征，然后，将其作为标准机器学习分类器的输入。&lt;/p&gt;

&lt;h2 id=&quot;三统计特征与核方法&quot;&gt;三、统计特征与核方法&lt;/h2&gt;

&lt;h3 id=&quot;31-节点层面&quot;&gt;3.1 节点层面&lt;/h3&gt;

&lt;p&gt;节点层面的统计特征通常包括节点的度，节点中心性，聚类系数，motifs等。其中节点的度和中心性是从单个节点的连接关系来区分节点的；聚类系数从结构的角度，衡量在一个节点的局部邻域中闭合三角形的比例。它度量了节点的邻居节点聚类的紧密程度(邻居节点之间相互连接的程度)。&lt;/p&gt;

&lt;p&gt;常见计算聚类系数局部变量的方法如下，&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic1.zhimg.com/80/v2-35d843dc15079c3f688f82772038fabc_720w.webp&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;其中，分子表示节点u的邻居节点之间的边的数量，分母表示节点u的所有邻居节点彼此连接产生的边的数目，du是节点u的度。&lt;/p&gt;

&lt;p&gt;整体聚类系数是一个图中所有闭三点组的数量与所有连通三点组(三个点封闭或者不闭)的数量的比值。处了统计三角形之外，还可以统计节点的ego-network中任意的motifs或者Graphlets的数量或者计算各种motifs在节点的ego-network中出现的频率来刻画节点特征。本质上来讲，通过审查节点的ego-network，可以将计算节点层面统计特征的任务转化为图层面的任务。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;节点层面实现任务：&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1.半监督学习任务&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528095957763.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

&lt;p&gt;如图所示案例，任务是预测灰点属于红点还是绿点。区分特征是度数（红点度数是1，绿点度数是2）&lt;/p&gt;

&lt;p&gt;2.特征抽取目标：找到能够描述节点在网络中结构与位置的特征(连接数，节点的重要度，节点的抱团程度，自己定义的子图)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528100158939.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

&lt;p&gt;3.度数$node\ degree$:通过以连接数目为关键，认为连接数目越多的节点越重要。缺点使认为节点所有邻居是同等重要的。&lt;/p&gt;

&lt;p&gt;如下图：如果只考虑数量而不考虑数量，则A和C的特征相同，但是两者的重要程度或者说影响能力则完全不同&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230112205420994.png&quot; alt=&quot;image-20230112205420994&quot; /&gt;&lt;/p&gt;

&lt;p&gt;对node degree的计算，将adjacency Matrix 与column Vector 相乘，相当于计算每一行的大小&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230112205639802.png&quot; alt=&quot;image-20230112205639802&quot; /&gt;&lt;/p&gt;

&lt;p&gt;例如下图，通过对上海地铁的数据绘制的Node degree的图像,我们可以看出上海的几个地铁交通枢纽。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230112205940290.png&quot; alt=&quot;image-20230112205940290&quot; /&gt;&lt;/p&gt;

&lt;p&gt;4.$node\ centrality\ c_v$考虑了节点的重要性&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;eigenvector centrality&lt;/strong&gt;：认为如果节点邻居重要，那么节点本身也重要
   因此节点 $v$ 的centrality是邻居centrality的加总：$c_v=\frac{1}{\lambda}\sum\limits_{u\in N(v)}c_u$ 
   （$\lambda$是某个正的常数，可以看成归一化系数）
   这是个递归式，解法是将其转换为矩阵形式： $\lambda \mathbf{c}=\mathbf{Ac}\ \mathbf{A}$是邻接矩阵，$\mathbf{c}$是$centralty$向量。
   从而发现$centrality$就是特征向量。根据$Perron-Frobenius\  Theorem^2$可知最大的特征值 $ \lambda_{max}$ 总为正且唯一，对应的leading eigenvector $\mathbf{c}_{max}$就是centrality向量。&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;上海地铁站的 &lt;strong&gt;Eigenvector Centrality&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230112210337158.png&quot; alt=&quot;image-20230112210337158&quot; /&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;betweenness centrality&lt;/strong&gt;：认为如果一个节点处在很多节点对的最短路径上，那么这个节点是重要的。（衡量一个节点作为bridge或transit hub的能力。）&lt;/p&gt;

    &lt;p&gt;$c_v=\sum\limits_{s\neq v \neq t}\frac{#(s和t之间包含v的最短路径)}{#(s和t之间的最短路径)}$&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230113164028145.png&quot; alt=&quot;image-20230113164028145&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;上海地铁站的 &lt;strong&gt;betweenness centrality&lt;/strong&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230113164133532.png&quot; alt=&quot;image-20230113164133532&quot; /&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;closeness centrality&lt;/strong&gt;：（去哪都近）认为如果一个节点距其他节点之间距离最短，那么认为这个节点是重要的&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528104341763.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;上海地铁站的 &lt;strong&gt;closeness centrality&lt;/strong&gt;&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230113164250922.png&quot; alt=&quot;image-20230113164250922&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;clustering coefficient&lt;/strong&gt;&lt;a href=&quot;https://blog.csdn.net/PolarisRisingWar/article/details/117336622#fn3&quot;&gt;3&lt;/a&gt;：（集群系数（有多抱团））衡量节点邻居的连接程度，描述节点的局部结构信息&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230113164424071.png&quot; alt=&quot;image-20230113164424071&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;这种
$\bigl(\begin{smallmatrix} k_v\2\end{smallmatrix}\bigr)$是组合数的写法，和国内常用的C写法上下是相反的4
所以这个式子代表 $v$ 邻居所构成的节点对，即潜在的连接数。整个公式衡量节点邻居的连接有多紧密&lt;/p&gt;

    &lt;p&gt;第1个例子：$e_v=6/6$ 
第2个例子：$ e_v=3/6$ 
第3个例子：$e_v=0/6 $&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230113171212040.png&quot; alt=&quot;image-20230113171212040&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;ego-network of a given node is simply a network that is induced by the node itself and its neighbors5. So it’s basically degree 1 neighborhood network around a given node.
这种三角形：How manys triples are connected
在社交网络之中会有很多这种三角形，因为可以想象你的朋友可能会经由你的介绍而认识，从而构建出一个这样的三角形/三元组。&lt;/p&gt;

    &lt;p&gt;上海地铁站的 &lt;strong&gt;clustering coefficient&lt;/strong&gt;&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230113164544554.png&quot; alt=&quot;image-20230113164544554&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;这种三角形可以拓展到某些预定义的子图pre-specified subgraph6上，例如如下所示的graphlet&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;graphlets&lt;/strong&gt;有根连通异构子图&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230113171240920.png&quot; alt=&quot;image-20230113171240920&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;对于某一给定节点数 $k$ ，会有  $n_k$ 个连通的异构子图。
就是说，这些图首先是connected的6，其次这些图有k个节点，第三它们异构。
异构，就是说它们形状不一样，就是怎么翻都不一样……就，高中化学应该讲过这个概念，我也不太会解释，反正就是这么一回事：举例来说，3个节点产生的全连接异构子图只有如图所示的2个，4个点就只有6个。如果你再构建出新的子图形状，那么它一定跟其中某个子图是同构的。
图中标的数字代表根节点可选的位置。例如对于 $G_0$ ，两个节点是等价的（类似同分异构体），所以只有一种graphlet；对于 $G_1$，根节点有在中间和在边上两种选择，上下两个边上的点是等价的，所以只有两种graphlet。其他的类似。节点数为2-5情况下一共能产生如图所示73种graphlet。7
这73个graphlet的核心概念就是不同的形状，不同的位置。
注意这里的graphlet概念和后文图的graphlet kernel的概念不太一样。具体的后文再讲&lt;/p&gt;

    &lt;ol&gt;
      &lt;li&gt;
        &lt;p&gt;Graphlet Degree Vector (GDV): Graphlet-base features for nodes
GDV与其他两种描述节点结构的特征的区别：&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;Degree counts #(edges) that a node touches&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;Clustering coefficient counts #(triangles) that a node touches.&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;GDV counts #(graphlets) that a node touches&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;Graphlet Degree Vector (GDV): A count vector of graphslets rooted at a given node.&lt;/p&gt;

        &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528123912356.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

        &lt;p&gt;如图所示，对四种graphlet，v vv 的每一种graphlet的数量作为向量的一个元素。
注意：graphlet c的情况不存在，是因为像graphlet b那样中间那条线连上了。这是因为graphlet是induced subgraph5，所以那个边也存在，所以c情况不存在。
考虑2-5个节点的graphlets，我们得到一个长度为73个坐标coordinate（就前图所示一共73种graphlet）的向量GDV，描述该点的局部拓扑结构topology of node’s neighborhood，可以捕获距离为4 hops的互联性interconnectivities。
相比节点度数或clustering coefficient，GDV能够描述两个节点之间更详细的节点局部拓扑结构相似性local topological similarity。&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Node Level Feature: Summary&lt;/p&gt;

    &lt;p&gt;这些特征可以分为两类：&lt;/p&gt;

    &lt;ol&gt;
      &lt;li&gt;
        &lt;p&gt;Importance-based features: 捕获节点在图中的重要性&lt;/p&gt;

        &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528124945858.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;Structure-based features: 捕获节点附近的拓扑属性&lt;/p&gt;

        &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528125011276.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ol&gt;

    &lt;p&gt;Discussion&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528125142198.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;大致来说，传统节点特征只能识别出结构上的相似，不能识别出图上空间、距离上的相似，即节点分析只强调了节点的属性（连接数，数据，重要程度等）。&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;32-连接层面&quot;&gt;3.2 连接层面&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;预测任务是基于已知的边，预测新链接的出现。测试模型时，将每一对无链接的点对进行排序，取存在链接概率最高的K个点对，作为预测结果。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;特征在点对上&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;有时你也可以直接将两个点的特征合并concatenate起来作为点对的特征，来训练模型。但这样做的缺点就在于失去了点之间关系的信息。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;链接预测任务的两种类型：随机缺失边；随时间演化边&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528125654243.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;图中的 ’ 念prime
第一种假设可以以蛋白质之间的交互作用举例，缺失的是研究者还没有发现的交互作用。（但这个假设其实有问题，因为研究者不是随机发现新链接的，新链接的发现会受到已发现链接的影响。在网络中有些部分被研究得更彻底，有些部分就几乎没有什么了解，不同部分的发现难度不同）
第二种假设可以以社交网络举例，随着时间流转，人们认识更多朋友。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;基于相似性进行链接预测：计算两点间的相似性得分（如用共同邻居衡量相似性），然后将点对进行排序，得分最高的n组点对就是预测结果，与真实值作比&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528131221987.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;1&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;distance-based feature：两点间最短路径的长度&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/2021052813134058.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;这种方式的问题在于没有考虑两个点邻居的重合度the degree of neighborhood overlap，如B-H有2个共同邻居，B-E和A-B都只有1个共同邻居。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;local neighborhood overlap：捕获节点的共同邻居数&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528131513561.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;common neighbors的问题在于度数高的点对就会有更高的结果，Jaccard’s coefficient是其归一化后的结果。
Adamic-Adar index在实践中表现得好。在社交网络上表现好的原因：有一堆度数低的共同好友比有一堆名人共同好友的得分更高。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;global neighborhood overlap
local neighborhood overlap的限制在于，如果两个点没有共同邻居，值就为0。&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528131745312.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;但是这两个点未来仍有可能被连接起来。所以我们使用考虑全图的global neighborhood overlap来解决这一问题。&lt;/p&gt;

    &lt;ol&gt;
      &lt;li&gt;
        &lt;p&gt;&lt;strong&gt;Katz index&lt;/strong&gt;：计算点对之间所有长度路径的条数&lt;/p&gt;

        &lt;ol&gt;
          &lt;li&gt;
            &lt;p&gt;计算方式：邻接矩阵求幂
邻接矩阵的k次幂结果，每个元素就是对应点对之间长度为k的路径的条数&lt;/p&gt;
          &lt;/li&gt;
          &lt;li&gt;
            &lt;p&gt;证明：&lt;/p&gt;

            &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528132033339.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

            &lt;p&gt;显然$ \mathbf{A}_{uv}$ 代表u和v之间长度为1的路径的数量&lt;/p&gt;

            &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528132048959.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

            &lt;p&gt;计算 $u$和 $v $ 之间长度为2的路径数量，就是计算每个 $u$的邻居  $\mathbf{A}&lt;em&gt;{ui}$（与 $u$ 有1条长度为1的路径）与 $v$ 之间长度为1的路径数量  $\mathbf{P}^{(1)}&lt;/em&gt;{iv}$即 $ \mathbf{A}&lt;em&gt;{iv}$的总和 $\sum_i \mathbf{A}&lt;/em&gt;{ui}*\mathbf{A}&lt;em&gt;{iv}=\mathbf{A}&lt;/em&gt;{uv}^2$&lt;/p&gt;

            &lt;p&gt;同理，更高的幂（更远的距离）就重复过程，继续乘起来&lt;/p&gt;
          &lt;/li&gt;
          &lt;li&gt;
            &lt;p&gt;从而得到Katz index的计算方式：&lt;/p&gt;

            &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528132815215.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

            &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/20210528132827488.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1BvbGFyaXNSaXNpbmdXYXI=,size_16,color_FFFFFF,t_70&quot; alt=&quot;在这里插入图片描述&quot; /&gt;&lt;/p&gt;

            &lt;p&gt;discount factor $\beta$ 会给比较长的距离以比较小的权重,exponentially with their length.
closed-form闭式解，解析解&lt;a href=&quot;https://blog.csdn.net/PolarisRisingWar/article/details/117336622#fn8&quot;&gt;$^8$&lt;/a&gt;
解析解的推导方法我去查了，见尾注&lt;a href=&quot;https://blog.csdn.net/PolarisRisingWar/article/details/117336622#fn9&quot;&gt;$^9$&lt;/a&gt;&lt;/p&gt;
          &lt;/li&gt;
        &lt;/ol&gt;
      &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Summary&lt;/p&gt;

    &lt;ol&gt;
      &lt;li&gt;Distance-based features: Uses the shortest path length between two nodes but does not capture how neighborhood overlaps.&lt;/li&gt;
      &lt;li&gt;Local neighborhood overlap:
        &lt;ol&gt;
          &lt;li&gt;Captures how many neighboring nodes are shared by two nodes.&lt;/li&gt;
          &lt;li&gt;Becomes zero when no neighbor nodes are shared.&lt;/li&gt;
        &lt;/ol&gt;
      &lt;/li&gt;
      &lt;li&gt;Global neighborhood overlap:
        &lt;ol&gt;
          &lt;li&gt;Uses global graph structure to score two nodes.&lt;/li&gt;
          &lt;li&gt;Katz index counts #paths of all lengths between two nodes.&lt;/li&gt;
        &lt;/ol&gt;
      &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;33-图层面&quot;&gt;3.3 图层面&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;目标：提取出的特征（一个D维向量）反应全图结构特点&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;实现：bag-of-words(BOW)：不同特征在图中实现的个数，目的：将一篇文章转换为向量形式，毕竟无法将文章直接输入机器学习模型，但向量可以。&lt;/p&gt;

    &lt;p&gt;​													&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230119185013060.png&quot; alt=&quot;image-20230119185013060&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;​													（e.g：图相当于文章，节点相当于单词）&lt;/p&gt;

    &lt;p&gt;​													问题：只看节点有没有，不看连接结构&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230119185047110.png&quot; alt=&quot;image-20230119185047110&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;改良：bag-of-node-degrees：不看节点，也不看连接结构，看的是graphlets（个人理解：图像结构）&lt;/p&gt;

    &lt;p&gt;关键点：统计不同数量的在图中的图像结构&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230119185347888.png&quot; alt=&quot;image-20230119185347888&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;&lt;strong&gt;graphlets&lt;/strong&gt;&lt;/p&gt;

    &lt;p&gt;基于多个节点之间的通过线段相连的，节点数固定但连接不同的结构&lt;/p&gt;

    &lt;p&gt;$e.g$&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230119203926748.png&quot; alt=&quot;image-20230119203926748&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;对一个数据处理后样本如图&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230117120733379.png&quot; alt=&quot;image-20230117120733379&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;与节点层面的不同点：&lt;/p&gt;

    &lt;ol&gt;
      &lt;li&gt;可以存在孤立节点&lt;/li&gt;
      &lt;li&gt;计数全图$graphlet$个数，而非特定节点邻域的$graphlet$个数&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Graphlet核&lt;/strong&gt;&lt;/p&gt;

    &lt;ol&gt;
      &lt;li&gt;
        &lt;p&gt;定义：通过零个图的Graphlet Count Vector数量积&lt;/p&gt;

\[K(G,G`)\ =\ f_G^T f_{G`}\]
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;如果两个节点的大小不同，则需要进行归一化&lt;/p&gt;

\[h_G= \frac{f_G}{Sum(f_G)} \  K(G,G`)\ =\ h_G^T h_{G`}\]
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;问题：&lt;/p&gt;

        &lt;ol&gt;
          &lt;li&gt;时间复杂度是一个多项式复杂度，因为需要进行子图匹配，复杂度为$O(n^k)$，$k$为图的大小&lt;/li&gt;
          &lt;li&gt;计算时会出现NP问题&lt;/li&gt;
        &lt;/ol&gt;
      &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;$Weisfeiler-Lehman$核&lt;/strong&gt;&lt;/p&gt;

    &lt;p&gt;W-L核是一种迭代邻域聚合的策略，通过提取包含更多信息的节点层面特征来聚合成图层面的表示。W-L算法的基本思想是首先为每个节点分配一个初始标签l0，一般选择节点的度作为标签。&lt;/p&gt;

    &lt;p&gt;然后，通过散列该节点邻域内当前标签构成的多重集，迭代地给每个节点分配新的标签。迭代K次重标记后每个节点的标签聚合了K-hop邻域结构，用这些标签计算直方图或者其他概要统计来作为图的特征表示。WL算法可以有效的判断图是否同构。&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://pic1.zhimg.com/80/v2-03b8f003a489c52001b424c77601312c_720w.webp&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;换一种话说，$Weisfeiler-Lehman$核相当于对不同的节点进行赋予不同的颜色&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230119205846857.png&quot; alt=&quot;image-20230119205846857&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;重复上两个流程&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230119210017360.png&quot; alt=&quot;image-20230119210017360&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230119210138192.png&quot; alt=&quot;image-20230119210138192&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;理论上来说上述过程可进行多次，此处只进行两次，后对颜色进行编码。&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/wumorfr/photo/master/wumorfr.github.io/images/image-20230119210159361.png&quot; alt=&quot;image-20230119210159361&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;34-节点袋&quot;&gt;3.4 节点袋&lt;/h3&gt;

&lt;p&gt;图层面特征最简单的方式是聚合节点层面的特征，作为图层面的表示。但是这种方法完全基于局部节点信息，可能错失图中重要的整体特性。&lt;/p&gt;

&lt;h2 id=&quot;参考文献&quot;&gt;参考文献&lt;/h2&gt;

&lt;p&gt;[1] &lt;a href=&quot;https://blog.csdn.net/PolarisRisingWar/article/details/117336622#fn3&quot;&gt;cs224w（图机器学习）2021冬季课程学习笔记2: Traditional Methods for ML on Graphs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[2] &lt;a href=&quot;https://zhuanlan.zhihu.com/p/549155570&quot;&gt;图机器学习(一)–图数据挖掘传统方法&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[3] [斯坦福CS224W图机器学习、图神经网络、知识图谱&lt;a href=&quot;https://www.bilibili.com/video/BV1pR4y1S7GA?vd_source=872fc2755b4c0ffb1be2bc7240a69fed&quot;&gt;同济子豪兄&lt;/a&gt;&lt;/p&gt;</content><author><name>乌墨_rfr</name></author><category term="Datawhale" /><category term="CS224W" /><category term="图神经网络" /><summary type="html">Datawhale开源学习社区 x 同济子豪兄 Stanford课程中文精讲系列笔记 一、概述 图是一种常见的数据结构，是节点的集合以及这些节点之间关系的集合。图的强大之处在于关注节点之间的关系以及通用性，比如相同的图结构可以表示社交网络，也可以表示分子内原子的关系。当前语音与图像数据往往呈现一个Euclidean Structure（欧氏结构）的数据相关，而分子结构，社交网络，3D图像等往往呈现非欧氏结构，而研究非欧氏结构的一种方法就是图。机器学习不是分析图数据的唯一方法，但是在随着图数据规模和复杂性的增加，机器学习在图数据上的建模和分析起着越来越重要的作用。 1.1 图的结构 图($Graph$)：$G = (V,\ E)$ 点($Vertices$)：$V= { v_1,v_2,…,v_n},n=6$ 边($Edge$)：$E={e_{1,2},e_{1,5},…,e_{4,6},\ e_{2,1},e_{5,1},…,e_{6,4}}$ =&amp;gt;邻接矩阵($Adjacency\ Matrix$) =&amp;gt;节点特征向量($Feature\ Vector\ of\ Nodes$)：$x=[x_1,x_2,…,x_6]^T,x_i\in R$ 1.2 特征处理 为了利用传统机器学习执行图上的计算任务，需要找到节点的表示形式。实现此目标的方法主要包含两种：特征工程和特征学习。特征工程需要手动设计特征，而特征学习可以自动学习节点的特征。手动的设计特征需要大量人力并且对于下游任务不一定就是最理想的，而特征学习可以由下游任务指导，学到可能适合下游任务的特征，获取更好的性能。 大多数情况下，谈到的信息指的是节点层面的信息，如节点的属性信息，在极少数形况下，边会带有实值特征，更少数的情况是把实值特征和整张图关联起来得到图的特征信息。 图特征选择(移除节点上无关和冗余的特征) 特征选择旨在自动选择一小部分特征，具有最小的冗余度但于学习目标最相关。传统特征选择假定数据实例是独立同分布的，然而，许多应用中的数据样本是嵌入在图上的，本质上不是独立同分布的。 图表示学习(生成一组新的节点特征) 图表示学习的目的是生成新的节点特征，已经在谱聚类，基于图的降维，矩阵分解的背景下进行了研究。在谱聚类中，数据点作为图中的节点，然后聚类问题转化为将图划分为节点社区。谱聚类的关键是谱嵌入，旨在将节点嵌入到低维空间中，在该空间中使用传统聚类算法。基于图的降维技术可以直接用于学习节点表示。基于数据样本的原始特征，使用预定义的距离函数构建相似度图，通过保留相似度图得结构信息学习节点表示。矩阵是表示图的最流行的方法，矩阵分解目的是将节点嵌入到低维空间中，在该空间中利用新的节点表示重构邻接矩阵。图嵌入方法一般归为矩阵分解方法。 前文提到的方法都是基于浅层模型，随着深度学习的发展图神经网络受到了大家的关注。图神经网络大致分为基于空间的方法和谱方法。空间方法显式利用图结构，通过空间上的邻居节点信息来学习；谱方法利用图的谱视图，通过图的傅里叶变换和逆变换来学习节点表示。 1.3 学习任务 1.3.1 节点分类 在现实场景中，节点常与有用的信息相关联，这些信息被视作标签，用于描述节点的特征。但是很难为所有节点获得完整的标签集，只有一部分节点有标签，而那些无标签的节点需要通过预测来得到，这就是节点分类任务。 用$G=(V,E)$表示一个图，$V$为节点集，$E$为边集。节点集$V$中那些有标签的节点构成的子集记为Vl。节点分类的目标是利用图G(所有节点)和Vl的标签信息学习一个映射来预测无标签节点的标签。 节点分类任务和标准的监督学习最重要的差别在于图中的节点不满足独立同分布假设。传统的监督学习要求每个样本与其他样本是独立的，否则建模时需要考虑样本之间的依赖关系。并且还需要样本分布相同，否则难以保证模型对新数据点适用。研究者根据节点分类任务的特点将其归为半监督学习，因为在训练过程中，图中的全部节点都被用到了，包括未标记的节点。但是标准的半监督学习也是以独立同分布为前提的，所以，图机器学习任务不是标准的机器学习任务。 1.3.2 链接预测 在许多数据中，图并不是完整的，会缺失一些节点之间的连接，可能是因为未被观察或者图的自然演变。用G=(V,E)表示一个图，V为节点集，E为边集，M是所有可能的节点对。边的补集定义为H=M/E。链接预测的目的为H中每个边赋值，表示这条边出现的可能性。 1.3.3 图级任务 图级别的任务包括图分类，图匹配，图生成，图回归，图聚类，社区发现等等。 图分类是为每个图预测一个标签，而节点分类是为每个节点预测一个标签。给定一组带标签的图数据集D={(Gi, yi)}，其中yi是图Gi的标签，图分类任务的目的是学到一个映射预测未标记的图的标签。 图聚类任务的目标是学习一个无监督的方法测量图与图之间的相似性。该任务的挑战是在考虑每张图内部结构关系的前提下定义有效特征。 社区发现常被类比为图领域的无监督学习中的聚类任务，通过输入一张图，推断潜在的社区结构 二、传统方法 图表示学习之前已经有很多优秀的方法被提出。比如，在节点分类或图分类中用到的图的统计特征，核方法等；在关联预测时使用节点邻域重叠测量等方法。 传统的使用图数据进行分类的方法遵循标准的机器学习范式。首先，基于启发式函数或邻域知识提取一些统计特征，然后，将其作为标准机器学习分类器的输入。 三、统计特征与核方法 3.1 节点层面 节点层面的统计特征通常包括节点的度，节点中心性，聚类系数，motifs等。其中节点的度和中心性是从单个节点的连接关系来区分节点的；聚类系数从结构的角度，衡量在一个节点的局部邻域中闭合三角形的比例。它度量了节点的邻居节点聚类的紧密程度(邻居节点之间相互连接的程度)。 常见计算聚类系数局部变量的方法如下， 其中，分子表示节点u的邻居节点之间的边的数量，分母表示节点u的所有邻居节点彼此连接产生的边的数目，du是节点u的度。 整体聚类系数是一个图中所有闭三点组的数量与所有连通三点组(三个点封闭或者不闭)的数量的比值。处了统计三角形之外，还可以统计节点的ego-network中任意的motifs或者Graphlets的数量或者计算各种motifs在节点的ego-network中出现的频率来刻画节点特征。本质上来讲，通过审查节点的ego-network，可以将计算节点层面统计特征的任务转化为图层面的任务。 节点层面实现任务： 1.半监督学习任务 如图所示案例，任务是预测灰点属于红点还是绿点。区分特征是度数（红点度数是1，绿点度数是2） 2.特征抽取目标：找到能够描述节点在网络中结构与位置的特征(连接数，节点的重要度，节点的抱团程度，自己定义的子图) 3.度数$node\ degree$:通过以连接数目为关键，认为连接数目越多的节点越重要。缺点使认为节点所有邻居是同等重要的。 如下图：如果只考虑数量而不考虑数量，则A和C的特征相同，但是两者的重要程度或者说影响能力则完全不同 对node degree的计算，将adjacency Matrix 与column Vector 相乘，相当于计算每一行的大小 例如下图，通过对上海地铁的数据绘制的Node degree的图像,我们可以看出上海的几个地铁交通枢纽。 4.$node\ centrality\ c_v$考虑了节点的重要性 eigenvector centrality：认为如果节点邻居重要，那么节点本身也重要 因此节点 $v$ 的centrality是邻居centrality的加总：$c_v=\frac{1}{\lambda}\sum\limits_{u\in N(v)}c_u$ （$\lambda$是某个正的常数，可以看成归一化系数） 这是个递归式，解法是将其转换为矩阵形式： $\lambda \mathbf{c}=\mathbf{Ac}\ \mathbf{A}$是邻接矩阵，$\mathbf{c}$是$centralty$向量。 从而发现$centrality$就是特征向量。根据$Perron-Frobenius\ Theorem^2$可知最大的特征值 $ \lambda_{max}$ 总为正且唯一，对应的leading eigenvector $\mathbf{c}_{max}$就是centrality向量。 上海地铁站的 Eigenvector Centrality betweenness centrality：认为如果一个节点处在很多节点对的最短路径上，那么这个节点是重要的。（衡量一个节点作为bridge或transit hub的能力。） $c_v=\sum\limits_{s\neq v \neq t}\frac{#(s和t之间包含v的最短路径)}{#(s和t之间的最短路径)}$ 上海地铁站的 betweenness centrality closeness centrality：（去哪都近）认为如果一个节点距其他节点之间距离最短，那么认为这个节点是重要的 上海地铁站的 closeness centrality clustering coefficient3：（集群系数（有多抱团））衡量节点邻居的连接程度，描述节点的局部结构信息 这种 $\bigl(\begin{smallmatrix} k_v\2\end{smallmatrix}\bigr)$是组合数的写法，和国内常用的C写法上下是相反的4 所以这个式子代表 $v$ 邻居所构成的节点对，即潜在的连接数。整个公式衡量节点邻居的连接有多紧密 第1个例子：$e_v=6/6$ 第2个例子：$ e_v=3/6$ 第3个例子：$e_v=0/6 $ ego-network of a given node is simply a network that is induced by the node itself and its neighbors5. So it’s basically degree 1 neighborhood network around a given node. 这种三角形：How manys triples are connected 在社交网络之中会有很多这种三角形，因为可以想象你的朋友可能会经由你的介绍而认识，从而构建出一个这样的三角形/三元组。 上海地铁站的 clustering coefficient 这种三角形可以拓展到某些预定义的子图pre-specified subgraph6上，例如如下所示的graphlet graphlets有根连通异构子图 对于某一给定节点数 $k$ ，会有 $n_k$ 个连通的异构子图。 就是说，这些图首先是connected的6，其次这些图有k个节点，第三它们异构。 异构，就是说它们形状不一样，就是怎么翻都不一样……就，高中化学应该讲过这个概念，我也不太会解释，反正就是这么一回事：举例来说，3个节点产生的全连接异构子图只有如图所示的2个，4个点就只有6个。如果你再构建出新的子图形状，那么它一定跟其中某个子图是同构的。 图中标的数字代表根节点可选的位置。例如对于 $G_0$ ，两个节点是等价的（类似同分异构体），所以只有一种graphlet；对于 $G_1$，根节点有在中间和在边上两种选择，上下两个边上的点是等价的，所以只有两种graphlet。其他的类似。节点数为2-5情况下一共能产生如图所示73种graphlet。7 这73个graphlet的核心概念就是不同的形状，不同的位置。 注意这里的graphlet概念和后文图的graphlet kernel的概念不太一样。具体的后文再讲 Graphlet Degree Vector (GDV): Graphlet-base features for nodes GDV与其他两种描述节点结构的特征的区别： Degree counts #(edges) that a node touches Clustering coefficient counts #(triangles) that a node touches. GDV counts #(graphlets) that a node touches Graphlet Degree Vector (GDV): A count vector of graphslets rooted at a given node. 如图所示，对四种graphlet，v vv 的每一种graphlet的数量作为向量的一个元素。 注意：graphlet c的情况不存在，是因为像graphlet b那样中间那条线连上了。这是因为graphlet是induced subgraph5，所以那个边也存在，所以c情况不存在。 考虑2-5个节点的graphlets，我们得到一个长度为73个坐标coordinate（就前图所示一共73种graphlet）的向量GDV，描述该点的局部拓扑结构topology of node’s neighborhood，可以捕获距离为4 hops的互联性interconnectivities。 相比节点度数或clustering coefficient，GDV能够描述两个节点之间更详细的节点局部拓扑结构相似性local topological similarity。 Node Level Feature: Summary 这些特征可以分为两类： Importance-based features: 捕获节点在图中的重要性 Structure-based features: 捕获节点附近的拓扑属性 Discussion 大致来说，传统节点特征只能识别出结构上的相似，不能识别出图上空间、距离上的相似，即节点分析只强调了节点的属性（连接数，数据，重要程度等）。 3.2 连接层面 预测任务是基于已知的边，预测新链接的出现。测试模型时，将每一对无链接的点对进行排序，取存在链接概率最高的K个点对，作为预测结果。 特征在点对上 有时你也可以直接将两个点的特征合并concatenate起来作为点对的特征，来训练模型。但这样做的缺点就在于失去了点之间关系的信息。 链接预测任务的两种类型：随机缺失边；随时间演化边 图中的 ’ 念prime 第一种假设可以以蛋白质之间的交互作用举例，缺失的是研究者还没有发现的交互作用。（但这个假设其实有问题，因为研究者不是随机发现新链接的，新链接的发现会受到已发现链接的影响。在网络中有些部分被研究得更彻底，有些部分就几乎没有什么了解，不同部分的发现难度不同） 第二种假设可以以社交网络举例，随着时间流转，人们认识更多朋友。 基于相似性进行链接预测：计算两点间的相似性得分（如用共同邻居衡量相似性），然后将点对进行排序，得分最高的n组点对就是预测结果，与真实值作比 distance-based feature：两点间最短路径的长度 这种方式的问题在于没有考虑两个点邻居的重合度the degree of neighborhood overlap，如B-H有2个共同邻居，B-E和A-B都只有1个共同邻居。 local neighborhood overlap：捕获节点的共同邻居数 common neighbors的问题在于度数高的点对就会有更高的结果，Jaccard’s coefficient是其归一化后的结果。 Adamic-Adar index在实践中表现得好。在社交网络上表现好的原因：有一堆度数低的共同好友比有一堆名人共同好友的得分更高。 global neighborhood overlap local neighborhood overlap的限制在于，如果两个点没有共同邻居，值就为0。 但是这两个点未来仍有可能被连接起来。所以我们使用考虑全图的global neighborhood overlap来解决这一问题。 Katz index：计算点对之间所有长度路径的条数 计算方式：邻接矩阵求幂 邻接矩阵的k次幂结果，每个元素就是对应点对之间长度为k的路径的条数 证明： 显然$ \mathbf{A}_{uv}$ 代表u和v之间长度为1的路径的数量 计算 $u$和 $v $ 之间长度为2的路径数量，就是计算每个 $u$的邻居 $\mathbf{A}{ui}$（与 $u$ 有1条长度为1的路径）与 $v$ 之间长度为1的路径数量 $\mathbf{P}^{(1)}{iv}$即 $ \mathbf{A}{iv}$的总和 $\sum_i \mathbf{A}{ui}*\mathbf{A}{iv}=\mathbf{A}{uv}^2$ 同理，更高的幂（更远的距离）就重复过程，继续乘起来 从而得到Katz index的计算方式： discount factor $\beta$ 会给比较长的距离以比较小的权重,exponentially with their length. closed-form闭式解，解析解$^8$ 解析解的推导方法我去查了，见尾注$^9$ Summary Distance-based features: Uses the shortest path length between two nodes but does not capture how neighborhood overlaps. Local neighborhood overlap: Captures how many neighboring nodes are shared by two nodes. Becomes zero when no neighbor nodes are shared. Global neighborhood overlap: Uses global graph structure to score two nodes. Katz index counts #paths of all lengths between two nodes. 3.3 图层面 目标：提取出的特征（一个D维向量）反应全图结构特点 实现：bag-of-words(BOW)：不同特征在图中实现的个数，目的：将一篇文章转换为向量形式，毕竟无法将文章直接输入机器学习模型，但向量可以。 ​ ​ （e.g：图相当于文章，节点相当于单词） ​ 问题：只看节点有没有，不看连接结构 改良：bag-of-node-degrees：不看节点，也不看连接结构，看的是graphlets（个人理解：图像结构） 关键点：统计不同数量的在图中的图像结构 graphlets 基于多个节点之间的通过线段相连的，节点数固定但连接不同的结构 $e.g$ 对一个数据处理后样本如图 与节点层面的不同点： 可以存在孤立节点 计数全图$graphlet$个数，而非特定节点邻域的$graphlet$个数 Graphlet核 定义：通过零个图的Graphlet Count Vector数量积 \[K(G,G`)\ =\ f_G^T f_{G`}\] 如果两个节点的大小不同，则需要进行归一化 \[h_G= \frac{f_G}{Sum(f_G)} \ K(G,G`)\ =\ h_G^T h_{G`}\] 问题： 时间复杂度是一个多项式复杂度，因为需要进行子图匹配，复杂度为$O(n^k)$，$k$为图的大小 计算时会出现NP问题 $Weisfeiler-Lehman$核 W-L核是一种迭代邻域聚合的策略，通过提取包含更多信息的节点层面特征来聚合成图层面的表示。W-L算法的基本思想是首先为每个节点分配一个初始标签l0，一般选择节点的度作为标签。 然后，通过散列该节点邻域内当前标签构成的多重集，迭代地给每个节点分配新的标签。迭代K次重标记后每个节点的标签聚合了K-hop邻域结构，用这些标签计算直方图或者其他概要统计来作为图的特征表示。WL算法可以有效的判断图是否同构。 换一种话说，$Weisfeiler-Lehman$核相当于对不同的节点进行赋予不同的颜色 重复上两个流程 理论上来说上述过程可进行多次，此处只进行两次，后对颜色进行编码。 3.4 节点袋 图层面特征最简单的方式是聚合节点层面的特征，作为图层面的表示。但是这种方法完全基于局部节点信息，可能错失图中重要的整体特性。 参考文献 [1] cs224w（图机器学习）2021冬季课程学习笔记2: Traditional Methods for ML on Graphs [2] 图机器学习(一)–图数据挖掘传统方法 [3] [斯坦福CS224W图机器学习、图神经网络、知识图谱同济子豪兄</summary></entry><entry><title type="html">【Datawhalw】【CS224W】图神经网络（一）</title><link href="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C-%E4%B8%80/" rel="alternate" type="text/html" title="【Datawhalw】【CS224W】图神经网络（一）" /><published>2023-02-13T00:00:00+00:00</published><updated>2023-02-13T00:00:00+00:00</updated><id>https://wumorfr.github.io/%5BDatawhale%5D%5BCS224W%5D%E5%9B%BE%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C(%E4%B8%80)</id><content type="html" xml:base="https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C-%E4%B8%80/">&lt;p&gt;Datawhale开源学习社区 x 同济子豪兄 Stanford课程中文精讲系列笔记&lt;/p&gt;

&lt;h2 id=&quot;一导读&quot;&gt;一、导读&lt;/h2&gt;

&lt;p&gt;​       传统深度学习技术，如循环神经网络和卷积神经网络已经在图像等欧式数据和信号等序列数据上取得巨大的成功。然而，在丰富的自然科学领域，现实世界的许多重要的对象和问题可以自然的或最优的用复杂的图结构来表达，如·社交网络、推荐系统、药物发现和程序分析中的图或流形结构。一方面，这些图结构的数据可以编码复杂的点对关系，以学习更丰富的信息表征；另一方面原始数据（图像或连续文本）的结构和语义信息中纳入特定领域知识可以捕获数据之间更细粒度的关系。&lt;a href=&quot;#参考文献&quot;&gt;$_{[1]}$&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;​    应用图神经网络架构的一些著名领域：社交网络、生物信息学等。渗透到的其他领域：推荐系统，计算机视觉，自然语言处理，程序分析，药物发现，异常检测，智慧城市等&lt;/p&gt;

&lt;h2 id=&quot;11-当前图神经网络的难点&quot;&gt;1.1 当前图神经网络的难点&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;图的空间局部性和结构不如图像或文本之间那么强&lt;a href=&quot;#参考文献&quot;&gt;$_{[1]}$&lt;/a&gt;，图像与文本往往具有比较明确的时间顺序或空间顺序&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/dac9dfb691634a439bee48108378f0ac.png&quot; alt=&quot;image-20230213190318085&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;图神经网络的输入往往是任意尺寸，任意类型的输入。图的结构决定了图可以提供一种强大的抽象，可以用来编码多种数据。&lt;a href=&quot;#参考文献&quot;&gt;$_{[1]}$&lt;/a&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;图神经网络经常是动态图，而且包含多模态的特征。（如歌曲可以包含歌唱者，歌词等文本特征，也有歌曲专辑图片等图像特征，还有歌曲本身的音频数据）&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;12-图神经网络应用场景及对应的相关模型&quot;&gt;1.2 图神经网络应用场景及对应的相关模型：&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/830c1a366d484fa68c387b1aa900f4fc.png&quot; alt=&quot;image-20230213192105063&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;13-图神经网络的应用方向及应用场景&quot;&gt;1.3 图神经网络的应用方向及应用场景&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/cb1bc7afbc1147f0a69bd09549825de3.png&quot; alt=&quot;image-20230213193245697&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;二图机器学习图神经网络编程工具&quot;&gt;二、图机器学习、图神经网络编程工具&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;PyG（PyTorch Geometric）：官方自己的库，和PyTorch类似&lt;/li&gt;
  &lt;li&gt;GraphGym&lt;/li&gt;
  &lt;li&gt;NetworkX&lt;/li&gt;
  &lt;li&gt;DGL：李沐老师推荐的，适合进行学术研究&lt;/li&gt;
  &lt;li&gt;图数据可视化：AntV、Echarts、GraphXR&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;参考文献&quot;&gt;参考文献&lt;/h2&gt;

&lt;p&gt;[1] 图神经网络——基础、前言与应用&lt;/p&gt;

&lt;p&gt;[2] &lt;a href=&quot;[斯坦福CS224W图机器学习、图神经网络、知识图谱[同济子豪兄]]https://www.bilibili.com/video/BV1pR4y1S7GA?vd_source=872fc2755b4c0ffb1be2bc7240a69fed&quot;&gt;斯坦福CS224W图机器学习、图神经网络、知识图谱【同济子豪兄】&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C-%E4%B8%80/&lt;/p&gt;

&lt;p&gt;https://blog.csdn.net/weixin_45856170/article/details/129015780&lt;/p&gt;</content><author><name>乌墨_rfr</name></author><category term="Datawhale" /><category term="CS224W" /><category term="图神经网络" /><summary type="html">Datawhale开源学习社区 x 同济子豪兄 Stanford课程中文精讲系列笔记 一、导读 ​ 传统深度学习技术，如循环神经网络和卷积神经网络已经在图像等欧式数据和信号等序列数据上取得巨大的成功。然而，在丰富的自然科学领域，现实世界的许多重要的对象和问题可以自然的或最优的用复杂的图结构来表达，如·社交网络、推荐系统、药物发现和程序分析中的图或流形结构。一方面，这些图结构的数据可以编码复杂的点对关系，以学习更丰富的信息表征；另一方面原始数据（图像或连续文本）的结构和语义信息中纳入特定领域知识可以捕获数据之间更细粒度的关系。$_{[1]}$ ​ 应用图神经网络架构的一些著名领域：社交网络、生物信息学等。渗透到的其他领域：推荐系统，计算机视觉，自然语言处理，程序分析，药物发现，异常检测，智慧城市等 1.1 当前图神经网络的难点 图的空间局部性和结构不如图像或文本之间那么强$_{[1]}$，图像与文本往往具有比较明确的时间顺序或空间顺序 图神经网络的输入往往是任意尺寸，任意类型的输入。图的结构决定了图可以提供一种强大的抽象，可以用来编码多种数据。$_{[1]}$ 图神经网络经常是动态图，而且包含多模态的特征。（如歌曲可以包含歌唱者，歌词等文本特征，也有歌曲专辑图片等图像特征，还有歌曲本身的音频数据） 1.2 图神经网络应用场景及对应的相关模型： 1.3 图神经网络的应用方向及应用场景 二、图机器学习、图神经网络编程工具 PyG（PyTorch Geometric）：官方自己的库，和PyTorch类似 GraphGym NetworkX DGL：李沐老师推荐的，适合进行学术研究 图数据可视化：AntV、Echarts、GraphXR 参考文献 [1] 图神经网络——基础、前言与应用 [2] 斯坦福CS224W图机器学习、图神经网络、知识图谱【同济子豪兄】 https://wumorfr.github.io/Datawhale-CS224W-%E5%9B%BE%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C-%E4%B8%80/ https://blog.csdn.net/weixin_45856170/article/details/129015780</summary></entry><entry><title type="html">K-Mean聚类算法</title><link href="https://wumorfr.github.io/K-Mean/" rel="alternate" type="text/html" title="K-Mean聚类算法" /><published>2022-06-19T00:00:00+00:00</published><updated>2022-06-19T00:00:00+00:00</updated><id>https://wumorfr.github.io/K-Mean</id><content type="html" xml:base="https://wumorfr.github.io/K-Mean/">&lt;h1 id=&quot;0前置基础&quot;&gt;0.前置基础&lt;/h1&gt;

&lt;h2 id=&quot;01聚类简介-3-5&quot;&gt;0.1聚类简介 [3] [5]&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Clustering (聚类)&lt;/strong&gt;是常见的unsupervised learning (无监督学习)方法，简单地说就是把相似的对象通过静态分类的方法分成不同的组别或者更多的子集（subset），这样让在同一个子集中的成员对象都有相似的一些属性，常见的包括在坐标系中更加短的空间距离等。聚类的过程，我们并不清楚某一类是什么（通常无标签信息），需要实现的目标只是把相似的样本聚到一起，即只是利用样本数据本身的分布规律。&lt;/p&gt;

&lt;p&gt;聚类算法可以大致分为&lt;strong&gt;传统聚类算法&lt;/strong&gt;以及&lt;strong&gt;深度聚类算法&lt;/strong&gt;：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;传统聚类算法主要是根据原特征+基于划分/密度/层次等方法。&lt;/li&gt;
  &lt;li&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/45b3a44c6a82efe154e8a6028a5660db.png&quot; alt=&quot;[机器学习]全面解析Kmeans聚类算法(Python)&quot; /&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;深度聚类方法主要是根据表征学习后的特征+传统聚类算法。&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/35f20fd8bb5f7ae03d925f61d8e9b6e1.png&quot; alt=&quot;[机器学习]全面解析Kmeans聚类算法(Python)&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;02-聚类与分类的区别4&quot;&gt;0.2 聚类与分类的区别[4]&lt;/h2&gt;

&lt;p&gt;聚类与分类算法的&lt;strong&gt;最大区别&lt;/strong&gt;在于, 分类的目标类别已知, 而聚类的目标类别是未知的.[5]&lt;/p&gt;

&lt;p&gt;分类：类别是已知的，通过对已知分类的数据进行训练和学习，找到这些不同类的特征，再对未分类的数据进行分类。属于监督学习。&lt;/p&gt;

&lt;p&gt;聚类：事先不知道数据会分为几类，通过&lt;a href=&quot;https://so.csdn.net/so/search?q=聚类分析&amp;amp;spm=1001.2101.3001.7020&quot;&gt;聚类分析&lt;/a&gt;将数据聚合成几个群体。聚类不需要对数据进行训练和学习。属于无监督学习。&lt;/p&gt;

&lt;h1 id=&quot;1k-means算法思想&quot;&gt;1.K-Means算法思想&lt;/h1&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-Means&lt;/code&gt;聚类算法是一种迭代求解的划分方法聚类分析算法[1] [3]，其主要是来计算数据聚集的算法，主要通过不断地取离种子点最近均值的算法[2]。&lt;/p&gt;

&lt;p&gt;简述：k-means即是把 n个点划分到k个聚类中，使得每个点都属于离他最近的均值（此即聚类中心）对应的聚类，以之作为聚类的标准。[5]&lt;/p&gt;

&lt;p&gt;算法思想是：&lt;/p&gt;

&lt;p&gt;(版本一)我们需要随机选择K个对象作为初始的聚类中心，然后计算每个对象和各个聚类中心之间的距离，然后将每个对象分配给距离它最近的聚类中心。聚类中心及分配给它们的对象就代表着一个聚类。每分配一个样本，聚类的中心会根据聚类中现有的对象被重新计算。此过程将不断重复，直至满足设置的终止条件。[1]&lt;/p&gt;

&lt;p&gt;（版本二）先随机选取K个对象作为初始的聚类中心。然后计算每个对象与各个种子聚类中心之间的距离，把每个对象分配给距离它最近的聚类中心。聚类中心以及分配给它们的对象就代表一个聚类。一旦全部对象都被分配了，每个聚类的聚类中心会根据聚类中现有的对象被重新计算。这个过程将不断重复直到满足某个终止条件。终止条件可以是以下任何一个：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;没有（或最小数目）对象被重新分配给不同的聚类。&lt;/li&gt;
  &lt;li&gt;没有（或最小数目）聚类中心再发生变化。&lt;/li&gt;
  &lt;li&gt;误差平方和局部最小。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;得到相互分离的球状聚类，在这些聚类中，均值点趋向收敛于聚类中心。 一般会希望得到的聚类大小大致相当，这样把每个观测都分配到离它最近的聚类中心（即均值点）就是比较正确的分配方案。[5]&lt;/p&gt;

&lt;h1 id=&quot;2k-means算法原理及步骤&quot;&gt;2.K-Means算法原理及步骤&lt;/h1&gt;

&lt;h2 id=&quot;21k-means聚类原理3&quot;&gt;2.1k-means聚类原理[3]&lt;/h2&gt;

&lt;p&gt;k-means聚类可以说是聚类算法中最为常见的，它是基于划分方法聚类的，原理是先初始化k个簇类中心，基于计算样本与中心点的距离归纳各簇类下的所属样本，迭代实现样本与其归属的簇类中心的距离为最小的目标。&lt;/p&gt;

&lt;p&gt;已知观测集$(x_1,x_2,…,x_n)$，其中每个观测都是一个 d-维实向量，k-平均聚类要把这 n个观测划分到k个集合中(k≤n),使得组内平方和最小。换句话说，它的目标是找到使得下式满足的聚类$S_i$，&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/336f89c67f0ed34f29ffc8ab983172c3.png&quot; alt=&quot;【机器学习】全面解析Kmeans聚类算法（Python）_人工智能_03&quot; /&gt;&lt;/p&gt;

&lt;p&gt;其中 $μ_i$ 是$S_i$ 中所有点的均值。[5]&lt;/p&gt;

&lt;p&gt;K-means 聚类的迭代算法实际上是 EM 算法，EM 算法解决的是在概率模型中含有无法观测的隐含变量情况下的参数估计问题。&lt;/p&gt;

&lt;p&gt;在 K-means 中的隐变量是每个类别所属类别。K-means 算法迭代步骤中的 每次确认中心点以后重新进行标记 对应 EM 算法中的 E 步 求当前参数条件下的 Expectation 。而 根据标记重新求中心点 对应 EM 算法中的 M 步 求似然函数最大化时（损失函数最小时）对应的参数 。EM 算法的缺点是容易陷入局部极小值，这也是 K-means 有时会得到局部最优解的原因。[3]&lt;/p&gt;

&lt;h2 id=&quot;22-k-means计算步骤1&quot;&gt;2.2 k-means计算步骤[1]&lt;/h2&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-Means&lt;/code&gt;算法的具体步骤如下：&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;首先我们需要&lt;strong&gt;确定一个k值&lt;/strong&gt;（随机），即我们希望数据经过聚类得到k个不同的集合&lt;/li&gt;
  &lt;li&gt;从给定的数据集中&lt;strong&gt;随机选择K个数据点作为质心&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;对数据集中的每个点计算其与每一个质心的距离（比如欧式距离）；&lt;strong&gt;数据点离哪个质心近，就划分到那个质心所属的集合&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;第一轮将所有的数据归号集合后，一共有K个集合，然后&lt;strong&gt;重新计算每个集合的质心&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;如果新计算出来的质心和原来的质心之间的距离小于某一个设置的阈值，则表示重新计算的质心的位置变化不大，数据整体趋于稳定，或者说数据已经收敛。在这样的情况下，我们认为聚类效果已经达到了期望的结果，算法可终止。&lt;/li&gt;
  &lt;li&gt;反之，&lt;strong&gt;如果新质心和原来质心的距离变化很大，需要重复迭代3-5步骤&lt;/strong&gt;，直至位置变化不大，达到收敛状态。&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;23-k-means术语5&quot;&gt;2.3 k-means术语[5]&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;簇: 所有数据的点集合，簇中的对象是相似的。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;质心: 簇中所有点的中心（计算所有点的均值而来）.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;SSE: Sum of Sqared Error（误差平方和）, 它被用来评估模型的好坏，SSE 值越小，表示越接近它们的质心. 聚类效果越 好。由于对误差取了平方，因此更加注重那些远离中心的点（一般为边界点或离群点）。详情见kmeans的评价标准。
有关 簇 和 质心 术语更形象的介绍, 请参考下图:&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://i.imgur.com/lboN0FM.png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;24-k-means开发流程5&quot;&gt;2.4 k-means开发流程[5]&lt;/h2&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;收集数据：使用任意方法
准备数据：需要数值型数据类计算距离, 也可以将标称型数据映射为二值型数据再用于距离计算
分析数据：使用任意方法
训练算法：不适用于无监督学习，即无监督学习不需要训练步骤
测试算法：应用聚类算法、观察结果.可以使用量化的误差指标如误差平方和（后面会介绍）来评价算法的结果.
使用算法：可以用于所希望的任何应用.通常情况下, 簇质心可以代表整个簇的数据来做出决策.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;25-k-means评价标准5&quot;&gt;2.5 k-means评价标准[5]&lt;/h2&gt;

&lt;p&gt;k-means算法因为手动选取k值和初始化随机质心的缘故，每一次的结果不会完全一样，而且由于手动选取k值，我们需要知道我们选取的k值是否合理，聚类效果好不好，那么如何来评价某一次的聚类效果呢？也许将它们画在图上直接观察是最好的办法，但现实是，我们的数据不会仅仅只有两个特征，一般来说都有十几个特征，而观察十几维的空间对我们来说是一个无法完成的任务。&lt;/p&gt;

&lt;p&gt;因此，我们需要一个公式来帮助我们判断聚类的性能，这个公式就是&lt;strong&gt;SSE&lt;/strong&gt; (Sum of Squared Error, 误差平方和 ），它其实就是每一个点到其簇内质心的距离的平方值的总和，这个数值对应k-means函数中clusterAssment矩阵的第一列之和。 SSE值越小表示数据点越接近于它们的质心，聚类效果也越好。 因为对误差取了平方，因此更加重视那些远离中心的点。一种肯定可以降低SSE值的方法是增加簇的个数，但这违背了聚类的目标。聚类的目标是在保持簇数目不变的情况下提高簇的质量。&lt;/p&gt;

&lt;h2 id=&quot;26-k-means应用场景5&quot;&gt;2.6 k-means应用场景[5]&lt;/h2&gt;

&lt;p&gt;k-means，用于数据集内种类属性不明晰，希望能够通过数据挖掘出或自动归类出有相似特点的对象的场景。其商业界的应用场景一般为挖掘出具有相似特点的潜在客户群体以便公司能够重点研究、对症下药。&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;​	例如，在2000年和2004年的美国总统大选中，候选人的得票数比较接近或者说非常接近。任一候选人得到的普选票数的最大百分比为50.7%而最小百分比为47.9% 如果1%的选民将手中的选票投向另外的候选人，那么选举结果就会截然不同。 实际上，如果妥善加以引导与吸引，少部分选民就会转换立场。尽管这类选举者占的比例较低，但当候选人的选票接近时，这些人的立场无疑会对选举结果产生非常大的影响。如何找出这类选民，以及如何在有限的预算下采取措施来吸引他们？ 答案就是聚类（Clustering)。&lt;/p&gt;

  &lt;p&gt;​	那么，具体如何实施呢？首先，收集用户的信息，可以同时收集用户满意或不满意的信息，这是因为任何对用户重要的内容都可能影响用户的投票结果。然后，将这些信息输入到某个聚类算法中。接着，对聚类结果中的每一个簇（最好选择最大簇 ）， 精心构造能够吸引该簇选民的消息。最后， 开展竞选活动并观察上述做法是否有效。&lt;/p&gt;

  &lt;p&gt;​	另一个例子就是产品部门的市场调研了。为了更好的了解自己的用户，产品部门可以采用聚类的方法得到不同特征的用户群体，然后针对不同的用户群体可以对症下药，为他们提供更加精准有效的服务。&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h1 id=&quot;3计算要点&quot;&gt;3.计算要点&lt;/h1&gt;

&lt;h3 id=&quot;31-k值选择1-3&quot;&gt;3.1 k值选择[1] [3]&lt;/h3&gt;

&lt;p&gt;k值决定了我们将数据划分成多少个簇类。k个初始化的质心的位置选择对最后的聚类结果和整个大代码的运行时间都有非常大的影响。因此需要选择合适的k个质心&lt;/p&gt;

&lt;p&gt;一般k值是通过先验知识或交叉验证来选取的。K值的确定常用：先验法、手肘法等方法。&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;先验法
先验比较简单，就是凭借着业务知识确定k的取值。比如对于iris花数据集，我们大概知道有三种类别，可以按照k=3做聚类验证。从下图可看出，对比聚类预测与实际的iris种类是比较一致的。&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/0111fd867be71012cb564aab6aeb6fe2.png&quot; alt=&quot;【机器学习】全面解析Kmeans聚类算法（Python）_算法_08&quot; /&gt;&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/6d14a0ee61c6e9d28ca1e94e8471c4a7.png&quot; alt=&quot;【机器学习】全面解析Kmeans聚类算法（Python）_机器学习_09&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;手肘法
可以知道k值越大，划分的簇群越多，对应的各个点到簇中心的距离的平方的和（类内距离，WSS）越低，我们通过确定WSS随着K的增加而减少的曲线拐点，作为K的取值。&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/dd8dbedc33206070dbb9b51ceaa2b67c.png&quot; alt=&quot;【机器学习】全面解析Kmeans聚类算法（Python）_机器学习_10&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;手肘法的缺点在于需要人为判断不够自动化，还有些其他方法如：&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;使用 Gap statistic 方法，确定k值。&lt;/li&gt;
  &lt;li&gt;验证不同K值的平均轮廓系数，越趋近1聚类效果越好。&lt;/li&gt;
  &lt;li&gt;验证不同K值的类内距离/类间距离，值越小越好。&lt;/li&gt;
  &lt;li&gt;ISODATA算法：它是在k-均值算法的基础上，增加对聚类结果的“合并”和“分裂”两个操作，确定最终的聚类结果。从而不用人为指定k值。&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;32-距离问题&quot;&gt;3.2 距离问题&lt;/h3&gt;

&lt;p&gt;1、两个集合之间的 ${x_i,x_j}$ 的 ${L_p}$ 距离定义为：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/609513bb2ed641d386ebab779756a208.png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;2、当p=1则表示为曼哈顿距离：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/9cbda400edf8410a84abdda8efb54c5e.png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;3、当p=2则表示为我们常用的&lt;strong&gt;欧式距离&lt;/strong&gt;：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/0d6caa3e23160b4fcf1416efa22926af.png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;4、当p趋于无穷时，表示为切比雪夫距离，它是各个坐标距离的最大值：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://img-blog.csdnimg.cn/img_convert/e99b783a0c70e3351faef01b867d4d84.png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;在&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-Means&lt;/code&gt;算法中一般采用的是&lt;strong&gt;欧式距离&lt;/strong&gt;&lt;/p&gt;

&lt;h1 id=&quot;4k-means优缺点&quot;&gt;4.K-Means优缺点&lt;/h1&gt;

&lt;p&gt;&lt;strong&gt;优点&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;原理很简单，实现起来也是非常容易，算法收敛速度也很快&lt;/li&gt;
  &lt;li&gt;聚类效果优，可解释性强。当数据最终收敛之后，我们最终能够很清晰的看到聚类的效果&lt;/li&gt;
  &lt;li&gt;约束条件少。算法中需要控制的参数只有簇数k。通过对k的不断调节才能得到最好的聚类效果&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;缺点&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;k值的选取不好把握，很多情况下K值的估计是非常困难的，有时候通过交叉验证来获取。&lt;/li&gt;
  &lt;li&gt;迭代的方法得到的结果只能是局部最优解，而不能得到全局最优解。&lt;/li&gt;
  &lt;li&gt;对噪音和异常点很敏感。异常点对质心的确定影响很大的。可以用来检测异常值。(K-means++算法改进点)&lt;/li&gt;
  &lt;li&gt;K-Means算法需要用初始随机种子点来搞，这个随机种子点太重要，不同的随机种子点会有得到完全不同的结果。[2]&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;5python实现k-means1&quot;&gt;5.python实现K-means[1]&lt;/h1&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pandas&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 随机模块
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;re&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# 导入数据
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;loadDataSet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loadtext&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;user/skl/cluster/dataset.csv&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 个人文件路径
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 返回数据集
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 绘图函数
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;show_fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loadDataSet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 导入数据
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 确定画布
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;add_subplot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;111&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 一个子图
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;ax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 传入绘图数据
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
  
&lt;span class=&quot;c1&quot;&gt;# 定义欧式距离公式
# 两个向量间的欧式距离公式：[(x_1 - x_2)^2 + (y_1 - y_2)^2 + (x_n - y_n)^2]
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;calcudistance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vec1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vec2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 传入两个向量
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;square&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vec1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 向量相减在平方，最后再求和
&lt;/span&gt;  
&lt;span class=&quot;c1&quot;&gt;# 初始化质心
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initCentroids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# 初始化执行；dataset是传入的数据
&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# k：选择分类簇的个数
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 数据列表化
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 随机选取k的模块
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 计算每个数据点和质心的距离，并归属到距离最小的类别中
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;minDisctance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 传入数据集和选取的质心列表
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 保存簇类结果
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 质心列表的长度：总共多少个质心表示分成多少类
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 原始数据中的每个元素
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;vec1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 数据中的向量
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;flag&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 标志位
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;minDis&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;inf&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 初始化为无穷大值
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;vec2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 取出第i个质心
&lt;/span&gt;      &lt;span class=&quot;n&quot;&gt;distcance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;calcudistance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vec1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 计算欧式距离
&lt;/span&gt;      &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;distance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minDis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;   
        &lt;span class=&quot;n&quot;&gt;minDis&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;distance&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 如果算出来的实际距离小于最小值的初始值，则将真实值distance赋值给最小值（更新最小值）
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;flag&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 循环结束时，flag保存与当前item最近的簇标记
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;flag&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keys&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setdefault&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;flag&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,[])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;flag&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 加入到相应的簇类中
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 不同的类别
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 重新计算质心
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;getcentroids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# 重新计算k个质心
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 质心空列表
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keys&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;centroid&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 现有数据点的平均值
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centroid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 得到新的质心
&lt;/span&gt;    
&lt;span class=&quot;c1&quot;&gt;# 计算均方误差
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;getVar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# 将簇类中各个向量和质心的距离累加求和
&lt;/span&gt;  &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 初始值
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keys&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 簇类中的键
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;vec1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 取出某个质心
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;distance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 距离初始化值
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 簇类的键
&lt;/span&gt;      &lt;span class=&quot;n&quot;&gt;vec2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;distance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;calcudistance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vec1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vec2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 求距离
&lt;/span&gt;    &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;distance&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 累加
&lt;/span&gt;  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 显示簇类
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;showCluster&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# 显示簇类结果
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;color_mark&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;or&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;ob&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;og&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;ok&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;oy&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;ow&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;centroid_mark&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;dr&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;db&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;dg&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;dk&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;dy&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;dw&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
  
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keys&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centroidMark&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;markersize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 质心点
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;colorMark&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
  
&lt;span class=&quot;c1&quot;&gt;# 主函数
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loadDataSet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 导入数据
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initCentroids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 质心列表
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minDistance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 簇类的字典数据
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;newVar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getVar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 质心和簇类中数据得到新的误差
&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;oldVar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 当两次聚类的误差小于某个值时，说明质心基本稳定
&lt;/span&gt;  
  &lt;span class=&quot;n&quot;&gt;times&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newVar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;oldVar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.00001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 当新旧误差的绝对值小于某个很小的值
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getCentroids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 得到质心列表
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;oldVar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;newVar&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 将新的误差赋值给旧误差
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;newVar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;getVar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# 新误差
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;times&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;showCluster&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;centroidList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterDict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 显示聚类结果
&lt;/span&gt;    
    
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__name__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;__main__&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;show_fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;6调用机器学习库sklearn实现k-means-聚类5&quot;&gt;6.调用机器学习库sklearn实现k-means 聚类[5]&lt;/h1&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import numpy as np
import matplotlib.pyplot as plt

from sklearn.cluster import KMeans

# 加载数据集
dataMat = []
fr = open(“./testSet2.txt”) # 注意，这个是相对路径
for line in fr.readlines():
curLine = line.strip().split(‘\t’)
fltLine = list(map(float,curLine)) # 映射所有的元素为 float（浮点数）类型
dataMat.append(fltLine)

# 训练k-means算法模型
km = KMeans(n_clusters=3) # 初始化
km.fit(dataMat) # 拟合
km_pred = km.predict(dataMat) # 预测
centers = km.cluster_centers_ # 质心

# 可视化结果
plt.scatter(np.array(dataMat)[:, 1], np.array(dataMat)[:, 0], c=km_pred)
plt.scatter(centers[:, 1], centers[:, 0], c=&quot;r&quot;)
plt.show()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;7延展学习&quot;&gt;7.延展学习&lt;/h1&gt;

&lt;p&gt;传统的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-Means&lt;/code&gt;算法存在一些缺陷，比如&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K&lt;/code&gt;值的选取不是很好把握、对异常数据敏感等，于是提出了很多在其基础上改进的聚类算法：&lt;/p&gt;

&lt;h2 id=&quot;71k-means初始化优化&quot;&gt;7.1、K-Means++（初始化优化）&lt;/h2&gt;

&lt;p&gt;针对K-Means算法中随机初始化质心的方法进行了优化。&lt;/p&gt;

&lt;p&gt;优化的思路是：各个簇类中心应该互相离得越远越好。基于各点到已有中心点的距离分量，依次随机选取到k个元素作为中心点。离已确定的簇中心点的距离越远，越有可能（可能性正比与距离的平方）被选择作为另一个簇的中心点。&lt;/p&gt;

&lt;p&gt;过程：[6]&lt;/p&gt;

&lt;p&gt;​	a) 从输入的数据点集合中随机选择一个点作为第一个聚类中心μ1μ1
　b) 对于数据集中的每一个点xixi，计算它与已选择的聚类中心中最近聚类中心的距离$D(x_i)=argmin||xi−μr||^2&lt;em&gt;2  r = 1,2,…k&lt;/em&gt;{selected}$&lt;/p&gt;

&lt;p&gt;　c) 选择一个新的数据点作为新的聚类中心，选择的原则是：$D(x)$较大的点，被选取作为聚类中心的概率较大
　d) 重复b和c直到选择出k个聚类质心
　e) 利用这k个质心来作为初始化质心去运行标准的K-Means算法&lt;/p&gt;

&lt;p&gt;如下代码。[3]&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Kmeans ++ 算法基于距离概率选择k个中心点
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# 1.随机选择一个点
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))))&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# 2.根据距离的概率选择其他中心点
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;distance_closest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; 
                         &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;#基于距离设定权重
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;num&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))]&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;72elkan-k-means距离优化&quot;&gt;7.2、elkan K-Means（距离优化）&lt;/h2&gt;

&lt;p&gt;在传统的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-Means&lt;/code&gt;算法中，在每轮迭代中我们都需要计算所有的样本点到质心的距离，这样是非常耗时的。&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;elkan K-Means&lt;/code&gt;算法利用：&lt;strong&gt;两边之和大于等于第三边，以及两边之差小于第三边&lt;/strong&gt;的三角形性质，来减少距离的计算。&lt;/p&gt;

&lt;p&gt;​	第一种规律是对于一个样本点$x$和两个质心$μ_{j1},μ_{j2}$。如果我们预先计算出了这两个质心之间的距离$D(j_1,j_2)$，则如果计算发现$2D(x,j_1)≤D(j_1,j_2)$,我们立即就可以知道$D(x,j_1)≤D(x,j_2)$。此时我们不需要再计算$D(x,j_2)$,也就是说省了一步距离计算。[6]&lt;/p&gt;

&lt;p&gt;　第二种规律是对于一个样本点xx和两个质心$μ_{j1},μ_{j2}$。我们可以得到$D(x,j_2)≥max{0,D(x,j_1)−D(j_1,j_2)}$。这个从三角形的性质也很容易得到。[6]&lt;/p&gt;

&lt;p&gt;　利用上边的两个规律，elkan K-Means比起传统的K-Means迭代速度有很大的提高。但是如果我们的样本的特征是稀疏的，有缺失值的话，这个方法就不使用了，此时某些距离无法计算，则不能使用该算法。[6]&lt;/p&gt;

&lt;h2 id=&quot;73mini-batch-k-means算法大样本优化&quot;&gt;7.3、Mini Batch K-Means算法（大样本优化）&lt;/h2&gt;

&lt;p&gt;在传统的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-Means&lt;/code&gt;算法中，要计算所有的样本点到所有的质心的距离。现在&lt;a href=&quot;https://cloud.tencent.com/solution/bigdata?from=10680&quot;&gt;大数据&lt;/a&gt;时代，如果样本量非常大，传统的算法将会非常耗时。&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Mini Batch K-Means&lt;/code&gt;就是从原始的样本集中随机选择一部分样本做传统的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;K-Means&lt;/code&gt;。这样可以避免样本量太大的计算难题，同时也加速算法的收敛。当然，此时的代价就是我们最终聚类的精度会降低一些。&lt;/p&gt;

&lt;p&gt;为了增加算法的准确性，我们一般会多跑几次&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Mini Batch K-Means&lt;/code&gt;算法，用得到不同的随机样本集来得到聚类簇，选择其中最优的聚类簇。&lt;/p&gt;

&lt;h2 id=&quot;74核k-means-3&quot;&gt;7.4、核K-means [3]&lt;/h2&gt;

&lt;p&gt;基于欧式距离的 K-means 假设了了各个数据簇的数据具有一样的的先验概率并呈现球形分布，但这种分布在实际生活中并不常见。面对非凸的数据分布形状时我们可以引入核函数来优化，这时算法又称为核 K-means 算法，是核聚类方法的一种。核聚类方法的主要思想是通过一个非线性映射，将输入空间中的数据点映射到高位的特征空间中，并在新的特征空间中进行聚类。非线性映射增加了数据点线性可分的概率，从而在经典的聚类算法失效的情况下，通过引入核函数可以达到更为准确的聚类结果。&lt;/p&gt;

&lt;h1 id=&quot;8参考文档&quot;&gt;8.参考文档&lt;/h1&gt;

&lt;p&gt;主要参考：[1] &lt;a href=&quot;https://cloud.tencent.com/developer/article/1762526&quot;&gt;图解K-Means算法&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;补充参考：&lt;/p&gt;

&lt;p&gt;[2] &lt;a href=&quot;https://blog.51cto.com/liangdongchang/3120268&quot;&gt;&lt;strong&gt;机器学习之K均值算法（K-means）聚类&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[3] &lt;a href=&quot;https://blog.51cto.com/u_15671528/5358925&quot;&gt;【机器学习】全面解析Kmeans聚类算法（Python）&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[4] &lt;a href=&quot;https://blog.csdn.net/huangfei711/article/details/78480078&quot;&gt;5 分钟带你弄懂 k-means 聚类&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[5] &lt;a href=&quot;https://bainingchao.github.io/2018/09/19/%E4%B8%80%E6%AD%A5%E6%AD%A5%E6%95%99%E4%BD%A0%E8%BD%BB%E6%9D%BE%E5%AD%A6K-means%E8%81%9A%E7%B1%BB%E7%AE%97%E6%B3%95/&quot;&gt;一步步教你轻松学K-means聚类算法&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;[6] [&lt;a href=&quot;https://www.cnblogs.com/pinard/p/6164214.html&quot;&gt;K-Means聚类算法原理 &lt;/a&gt;]&lt;/p&gt;</content><author><name>乌墨_rfr</name></author><category term="机器学习" /><category term="K-means聚类算法" /><summary type="html">0.前置基础 0.1聚类简介 [3] [5] Clustering (聚类)是常见的unsupervised learning (无监督学习)方法，简单地说就是把相似的对象通过静态分类的方法分成不同的组别或者更多的子集（subset），这样让在同一个子集中的成员对象都有相似的一些属性，常见的包括在坐标系中更加短的空间距离等。聚类的过程，我们并不清楚某一类是什么（通常无标签信息），需要实现的目标只是把相似的样本聚到一起，即只是利用样本数据本身的分布规律。 聚类算法可以大致分为传统聚类算法以及深度聚类算法： 传统聚类算法主要是根据原特征+基于划分/密度/层次等方法。 深度聚类方法主要是根据表征学习后的特征+传统聚类算法。 0.2 聚类与分类的区别[4] 聚类与分类算法的最大区别在于, 分类的目标类别已知, 而聚类的目标类别是未知的.[5] 分类：类别是已知的，通过对已知分类的数据进行训练和学习，找到这些不同类的特征，再对未分类的数据进行分类。属于监督学习。 聚类：事先不知道数据会分为几类，通过聚类分析将数据聚合成几个群体。聚类不需要对数据进行训练和学习。属于无监督学习。 1.K-Means算法思想 K-Means聚类算法是一种迭代求解的划分方法聚类分析算法[1] [3]，其主要是来计算数据聚集的算法，主要通过不断地取离种子点最近均值的算法[2]。 简述：k-means即是把 n个点划分到k个聚类中，使得每个点都属于离他最近的均值（此即聚类中心）对应的聚类，以之作为聚类的标准。[5] 算法思想是： (版本一)我们需要随机选择K个对象作为初始的聚类中心，然后计算每个对象和各个聚类中心之间的距离，然后将每个对象分配给距离它最近的聚类中心。聚类中心及分配给它们的对象就代表着一个聚类。每分配一个样本，聚类的中心会根据聚类中现有的对象被重新计算。此过程将不断重复，直至满足设置的终止条件。[1] （版本二）先随机选取K个对象作为初始的聚类中心。然后计算每个对象与各个种子聚类中心之间的距离，把每个对象分配给距离它最近的聚类中心。聚类中心以及分配给它们的对象就代表一个聚类。一旦全部对象都被分配了，每个聚类的聚类中心会根据聚类中现有的对象被重新计算。这个过程将不断重复直到满足某个终止条件。终止条件可以是以下任何一个： 没有（或最小数目）对象被重新分配给不同的聚类。 没有（或最小数目）聚类中心再发生变化。 误差平方和局部最小。 得到相互分离的球状聚类，在这些聚类中，均值点趋向收敛于聚类中心。 一般会希望得到的聚类大小大致相当，这样把每个观测都分配到离它最近的聚类中心（即均值点）就是比较正确的分配方案。[5] 2.K-Means算法原理及步骤 2.1k-means聚类原理[3] k-means聚类可以说是聚类算法中最为常见的，它是基于划分方法聚类的，原理是先初始化k个簇类中心，基于计算样本与中心点的距离归纳各簇类下的所属样本，迭代实现样本与其归属的簇类中心的距离为最小的目标。 已知观测集$(x_1,x_2,…,x_n)$，其中每个观测都是一个 d-维实向量，k-平均聚类要把这 n个观测划分到k个集合中(k≤n),使得组内平方和最小。换句话说，它的目标是找到使得下式满足的聚类$S_i$， 其中 $μ_i$ 是$S_i$ 中所有点的均值。[5] K-means 聚类的迭代算法实际上是 EM 算法，EM 算法解决的是在概率模型中含有无法观测的隐含变量情况下的参数估计问题。 在 K-means 中的隐变量是每个类别所属类别。K-means 算法迭代步骤中的 每次确认中心点以后重新进行标记 对应 EM 算法中的 E 步 求当前参数条件下的 Expectation 。而 根据标记重新求中心点 对应 EM 算法中的 M 步 求似然函数最大化时（损失函数最小时）对应的参数 。EM 算法的缺点是容易陷入局部极小值，这也是 K-means 有时会得到局部最优解的原因。[3] 2.2 k-means计算步骤[1] K-Means算法的具体步骤如下： 首先我们需要确定一个k值（随机），即我们希望数据经过聚类得到k个不同的集合 从给定的数据集中随机选择K个数据点作为质心 对数据集中的每个点计算其与每一个质心的距离（比如欧式距离）；数据点离哪个质心近，就划分到那个质心所属的集合 第一轮将所有的数据归号集合后，一共有K个集合，然后重新计算每个集合的质心 如果新计算出来的质心和原来的质心之间的距离小于某一个设置的阈值，则表示重新计算的质心的位置变化不大，数据整体趋于稳定，或者说数据已经收敛。在这样的情况下，我们认为聚类效果已经达到了期望的结果，算法可终止。 反之，如果新质心和原来质心的距离变化很大，需要重复迭代3-5步骤，直至位置变化不大，达到收敛状态。 2.3 k-means术语[5] 簇: 所有数据的点集合，簇中的对象是相似的。 质心: 簇中所有点的中心（计算所有点的均值而来）. SSE: Sum of Sqared Error（误差平方和）, 它被用来评估模型的好坏，SSE 值越小，表示越接近它们的质心. 聚类效果越 好。由于对误差取了平方，因此更加注重那些远离中心的点（一般为边界点或离群点）。详情见kmeans的评价标准。 有关 簇 和 质心 术语更形象的介绍, 请参考下图: 2.4 k-means开发流程[5] 收集数据：使用任意方法 准备数据：需要数值型数据类计算距离, 也可以将标称型数据映射为二值型数据再用于距离计算 分析数据：使用任意方法 训练算法：不适用于无监督学习，即无监督学习不需要训练步骤 测试算法：应用聚类算法、观察结果.可以使用量化的误差指标如误差平方和（后面会介绍）来评价算法的结果. 使用算法：可以用于所希望的任何应用.通常情况下, 簇质心可以代表整个簇的数据来做出决策. 2.5 k-means评价标准[5] k-means算法因为手动选取k值和初始化随机质心的缘故，每一次的结果不会完全一样，而且由于手动选取k值，我们需要知道我们选取的k值是否合理，聚类效果好不好，那么如何来评价某一次的聚类效果呢？也许将它们画在图上直接观察是最好的办法，但现实是，我们的数据不会仅仅只有两个特征，一般来说都有十几个特征，而观察十几维的空间对我们来说是一个无法完成的任务。 因此，我们需要一个公式来帮助我们判断聚类的性能，这个公式就是SSE (Sum of Squared Error, 误差平方和 ），它其实就是每一个点到其簇内质心的距离的平方值的总和，这个数值对应k-means函数中clusterAssment矩阵的第一列之和。 SSE值越小表示数据点越接近于它们的质心，聚类效果也越好。 因为对误差取了平方，因此更加重视那些远离中心的点。一种肯定可以降低SSE值的方法是增加簇的个数，但这违背了聚类的目标。聚类的目标是在保持簇数目不变的情况下提高簇的质量。 2.6 k-means应用场景[5] k-means，用于数据集内种类属性不明晰，希望能够通过数据挖掘出或自动归类出有相似特点的对象的场景。其商业界的应用场景一般为挖掘出具有相似特点的潜在客户群体以便公司能够重点研究、对症下药。 ​ 例如，在2000年和2004年的美国总统大选中，候选人的得票数比较接近或者说非常接近。任一候选人得到的普选票数的最大百分比为50.7%而最小百分比为47.9% 如果1%的选民将手中的选票投向另外的候选人，那么选举结果就会截然不同。 实际上，如果妥善加以引导与吸引，少部分选民就会转换立场。尽管这类选举者占的比例较低，但当候选人的选票接近时，这些人的立场无疑会对选举结果产生非常大的影响。如何找出这类选民，以及如何在有限的预算下采取措施来吸引他们？ 答案就是聚类（Clustering)。 ​ 那么，具体如何实施呢？首先，收集用户的信息，可以同时收集用户满意或不满意的信息，这是因为任何对用户重要的内容都可能影响用户的投票结果。然后，将这些信息输入到某个聚类算法中。接着，对聚类结果中的每一个簇（最好选择最大簇 ）， 精心构造能够吸引该簇选民的消息。最后， 开展竞选活动并观察上述做法是否有效。 ​ 另一个例子就是产品部门的市场调研了。为了更好的了解自己的用户，产品部门可以采用聚类的方法得到不同特征的用户群体，然后针对不同的用户群体可以对症下药，为他们提供更加精准有效的服务。 3.计算要点 3.1 k值选择[1] [3] k值决定了我们将数据划分成多少个簇类。k个初始化的质心的位置选择对最后的聚类结果和整个大代码的运行时间都有非常大的影响。因此需要选择合适的k个质心 一般k值是通过先验知识或交叉验证来选取的。K值的确定常用：先验法、手肘法等方法。 先验法 先验比较简单，就是凭借着业务知识确定k的取值。比如对于iris花数据集，我们大概知道有三种类别，可以按照k=3做聚类验证。从下图可看出，对比聚类预测与实际的iris种类是比较一致的。 手肘法 可以知道k值越大，划分的簇群越多，对应的各个点到簇中心的距离的平方的和（类内距离，WSS）越低，我们通过确定WSS随着K的增加而减少的曲线拐点，作为K的取值。 手肘法的缺点在于需要人为判断不够自动化，还有些其他方法如： 使用 Gap statistic 方法，确定k值。 验证不同K值的平均轮廓系数，越趋近1聚类效果越好。 验证不同K值的类内距离/类间距离，值越小越好。 ISODATA算法：它是在k-均值算法的基础上，增加对聚类结果的“合并”和“分裂”两个操作，确定最终的聚类结果。从而不用人为指定k值。 3.2 距离问题 1、两个集合之间的 ${x_i,x_j}$ 的 ${L_p}$ 距离定义为： 2、当p=1则表示为曼哈顿距离： 3、当p=2则表示为我们常用的欧式距离： 4、当p趋于无穷时，表示为切比雪夫距离，它是各个坐标距离的最大值： 在K-Means算法中一般采用的是欧式距离 4.K-Means优缺点 优点 原理很简单，实现起来也是非常容易，算法收敛速度也很快 聚类效果优，可解释性强。当数据最终收敛之后，我们最终能够很清晰的看到聚类的效果 约束条件少。算法中需要控制的参数只有簇数k。通过对k的不断调节才能得到最好的聚类效果 缺点 k值的选取不好把握，很多情况下K值的估计是非常困难的，有时候通过交叉验证来获取。 迭代的方法得到的结果只能是局部最优解，而不能得到全局最优解。 对噪音和异常点很敏感。异常点对质心的确定影响很大的。可以用来检测异常值。(K-means++算法改进点) K-Means算法需要用初始随机种子点来搞，这个随机种子点太重要，不同的随机种子点会有得到完全不同的结果。[2] 5.python实现K-means[1] import numpy as np import pandas as pd import random # 随机模块 import re import matplotlib.pyplot as plt # 导入数据 def loadDataSet(): dataset = np.loadtext(&quot;user/skl/cluster/dataset.csv&quot;) # 个人文件路径 return dataset # 返回数据集 # 绘图函数 def show_fig(): dataset = loadDataSet() # 导入数据 fig = plt.figure() # 确定画布 ax = fig.add_subplot(111) # 一个子图 ax.scatter(dataset[:,0], dataset[:,1]) # 传入绘图数据 plt.show() # 定义欧式距离公式 # 两个向量间的欧式距离公式：[(x_1 - x_2)^2 + (y_1 - y_2)^2 + (x_n - y_n)^2] def calcudistance(vec1,vec2): # 传入两个向量 return np.sqrt(np.sum(np.square(vec1 - vec2))) # 向量相减在平方，最后再求和 # 初始化质心 def initCentroids(dataset, k): # 初始化执行；dataset是传入的数据 # k：选择分类簇的个数 dataset = list(dataset) # 数据列表化 return random.sample(dataset,k) # 随机选取k的模块 # 计算每个数据点和质心的距离，并归属到距离最小的类别中 def minDisctance(dataset, centroidList): # 传入数据集和选取的质心列表 clusterDict = dict() # 保存簇类结果 k = len(centroidList) # 质心列表的长度：总共多少个质心表示分成多少类 for item in dataset: # 原始数据中的每个元素 vec1 = item # 数据中的向量 flag = -1 # 标志位 minDis = float(&quot;inf&quot;) # 初始化为无穷大值 for i in range(k): vec2 = centroidList[i] # 取出第i个质心 distcance = calcudistance(vec1, vec2) # 计算欧式距离 if distance &amp;lt; minDis: minDis = distance # 如果算出来的实际距离小于最小值的初始值，则将真实值distance赋值给最小值（更新最小值） flag = i # 循环结束时，flag保存与当前item最近的簇标记 if flag not in clusterDict.keys(): clusterDict.setdefault(flag,[]) clusterDict[flag].append(item) # 加入到相应的簇类中 return clusterDict # 不同的类别 # 重新计算质心 def getcentroids(clusterDict): # 重新计算k个质心 centroidList = [] # 质心空列表 for key in clusterDict.keys(): # centroid = np.mean(clusterDict[key], axis=0) # 现有数据点的平均值 centroidList.append(centroid) return centroidList # 得到新的质心 # 计算均方误差 def getVar(centroidList, clusterDict): # 将簇类中各个向量和质心的距离累加求和 sum = 0.0 # 初始值 for key in clusterDict.keys(): # 簇类中的键 vec1 = centroidList[key] # 取出某个质心 distance = 0.0 # 距离初始化值 for item in clusterDict[key]: # 簇类的键 vec2 = item distance += calcudistance(vec1, vec2) # 求距离 sum += distance # 累加 return sum # 显示簇类 def showCluster(centroidList, clusterDict): # 显示簇类结果 color_mark = [&quot;or&quot;,&quot;ob&quot;,&quot;og&quot;,&quot;ok&quot;,&quot;oy&quot;,&quot;ow&quot;] centroid_mark = [&quot;dr&quot;,&quot;db&quot;,&quot;dg&quot;,&quot;dk&quot;,&quot;dy&quot;,&quot;dw&quot;] for key in clusterDict.keys(): plt.plot(centroidList[key][0], centroidList[key][1], centroidMark[key],markersize=12) # 质心点 for item in clusterDict[key]: plt.plot(item[0],item[1],colorMark[key]) plt.show() # 主函数 def main(): dataset = loadDataSet() # 导入数据 centroidList = initCentroids(dataset,4) # 质心列表 clusterDict = minDistance(dataset, centroidList) # 簇类的字典数据 newVar = getVar(centroidList, clusterDict) # 质心和簇类中数据得到新的误差 oldVar = 1 # 当两次聚类的误差小于某个值时，说明质心基本稳定 times = 2 while abs(newVar - oldVar) &amp;gt;= 0.00001: # 当新旧误差的绝对值小于某个很小的值 centroidList = getCentroids(clusterDict) # 得到质心列表 oldVar = newVar # 将新的误差赋值给旧误差 newVar = getVar(centroidList, clusterDict) # 新误差 times += 1 showCluster(centroidList, clusterDict) # 显示聚类结果 if __name__ == &quot;__main__&quot;: show_fig() main() 6.调用机器学习库sklearn实现k-means 聚类[5] import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans # 加载数据集 dataMat = [] fr = open(“./testSet2.txt”) # 注意，这个是相对路径 for line in fr.readlines(): curLine = line.strip().split(‘\t’) fltLine = list(map(float,curLine)) # 映射所有的元素为 float（浮点数）类型 dataMat.append(fltLine) # 训练k-means算法模型 km = KMeans(n_clusters=3) # 初始化 km.fit(dataMat) # 拟合 km_pred = km.predict(dataMat) # 预测 centers = km.cluster_centers_ # 质心 # 可视化结果 plt.scatter(np.array(dataMat)[:, 1], np.array(dataMat)[:, 0], c=km_pred) plt.scatter(centers[:, 1], centers[:, 0], c=&quot;r&quot;) plt.show() 7.延展学习 传统的K-Means算法存在一些缺陷，比如K值的选取不是很好把握、对异常数据敏感等，于是提出了很多在其基础上改进的聚类算法： 7.1、K-Means++（初始化优化） 针对K-Means算法中随机初始化质心的方法进行了优化。 优化的思路是：各个簇类中心应该互相离得越远越好。基于各点到已有中心点的距离分量，依次随机选取到k个元素作为中心点。离已确定的簇中心点的距离越远，越有可能（可能性正比与距离的平方）被选择作为另一个簇的中心点。 过程：[6] ​ a) 从输入的数据点集合中随机选择一个点作为第一个聚类中心μ1μ1 　b) 对于数据集中的每一个点xixi，计算它与已选择的聚类中心中最近聚类中心的距离$D(x_i)=argmin||xi−μr||^22 r = 1,2,…k{selected}$ 　c) 选择一个新的数据点作为新的聚类中心，选择的原则是：$D(x)$较大的点，被选取作为聚类中心的概率较大 　d) 重复b和c直到选择出k个聚类质心 　e) 利用这k个质心来作为初始化质心去运行标准的K-Means算法 如下代码。[3] # Kmeans ++ 算法基于距离概率选择k个中心点 # 1.随机选择一个点 center = [] center.append(random.choice(range(len(self.data[0])))) # 2.根据距离的概率选择其他中心点 for i in range(self.k - 1): weights = [self.distance_closest(self.data[0][x], center) for x in range(len(self.data[0])) if x not in center] dp = [x for x in range(len(self.data[0])) if x not in center] total = sum(weights) #基于距离设定权重 weights = [weight/total for weight in weights] num = random.random() x = -1 i = 0 while i &amp;lt; num : x += 1 i += weights[x] center.append(dp[x]) center = [self.data_dict[self.data[0][center[k]]] for k in range(len(center))] 7.2、elkan K-Means（距离优化） 在传统的K-Means算法中，在每轮迭代中我们都需要计算所有的样本点到质心的距离，这样是非常耗时的。 elkan K-Means算法利用：两边之和大于等于第三边，以及两边之差小于第三边的三角形性质，来减少距离的计算。 ​ 第一种规律是对于一个样本点$x$和两个质心$μ_{j1},μ_{j2}$。如果我们预先计算出了这两个质心之间的距离$D(j_1,j_2)$，则如果计算发现$2D(x,j_1)≤D(j_1,j_2)$,我们立即就可以知道$D(x,j_1)≤D(x,j_2)$。此时我们不需要再计算$D(x,j_2)$,也就是说省了一步距离计算。[6] 　第二种规律是对于一个样本点xx和两个质心$μ_{j1},μ_{j2}$。我们可以得到$D(x,j_2)≥max{0,D(x,j_1)−D(j_1,j_2)}$。这个从三角形的性质也很容易得到。[6] 　利用上边的两个规律，elkan K-Means比起传统的K-Means迭代速度有很大的提高。但是如果我们的样本的特征是稀疏的，有缺失值的话，这个方法就不使用了，此时某些距离无法计算，则不能使用该算法。[6] 7.3、Mini Batch K-Means算法（大样本优化） 在传统的K-Means算法中，要计算所有的样本点到所有的质心的距离。现在大数据时代，如果样本量非常大，传统的算法将会非常耗时。 Mini Batch K-Means就是从原始的样本集中随机选择一部分样本做传统的K-Means。这样可以避免样本量太大的计算难题，同时也加速算法的收敛。当然，此时的代价就是我们最终聚类的精度会降低一些。 为了增加算法的准确性，我们一般会多跑几次Mini Batch K-Means算法，用得到不同的随机样本集来得到聚类簇，选择其中最优的聚类簇。 7.4、核K-means [3] 基于欧式距离的 K-means 假设了了各个数据簇的数据具有一样的的先验概率并呈现球形分布，但这种分布在实际生活中并不常见。面对非凸的数据分布形状时我们可以引入核函数来优化，这时算法又称为核 K-means 算法，是核聚类方法的一种。核聚类方法的主要思想是通过一个非线性映射，将输入空间中的数据点映射到高位的特征空间中，并在新的特征空间中进行聚类。非线性映射增加了数据点线性可分的概率，从而在经典的聚类算法失效的情况下，通过引入核函数可以达到更为准确的聚类结果。 8.参考文档 主要参考：[1] 图解K-Means算法 补充参考： [2] 机器学习之K均值算法（K-means）聚类 [3] 【机器学习】全面解析Kmeans聚类算法（Python） [4] 5 分钟带你弄懂 k-means 聚类 [5] 一步步教你轻松学K-means聚类算法 [6] [K-Means聚类算法原理 ]</summary></entry><entry><title type="html">K近邻算法</title><link href="https://wumorfr.github.io/Feature_Space/" rel="alternate" type="text/html" title="K近邻算法" /><published>2022-05-20T00:00:00+00:00</published><updated>2022-05-20T00:00:00+00:00</updated><id>https://wumorfr.github.io/Feature_Space</id><content type="html" xml:base="https://wumorfr.github.io/Feature_Space/">&lt;h1 id=&quot;第一部分k近邻算法原理&quot;&gt;第一部分：K近邻算法原理&lt;/h1&gt;

&lt;h2 id=&quot;11k近邻算法的基本概念原理以及应用&quot;&gt;&lt;strong&gt;1.1、k近邻算法的基本概念，原理以及应用&lt;/strong&gt;&lt;/h2&gt;

&lt;p&gt;K近邻算法，即是给定一个训练数据集，对新的输入实例，在训练数据集中找到与该实例&lt;strong&gt;最邻近&lt;/strong&gt;的K个实例，&lt;strong&gt;这K个实例的多数属于某个类&lt;/strong&gt;，就把该输入实例分类到这个类中。（&lt;strong&gt;这就类似于现实生活中少数服从多数的思想&lt;/strong&gt;）&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/KnnClassification.svg/330px-KnnClassification.svg.png&quot; alt=&quot;*k*近邻算法例子。测试样本（绿色圆形）应归入要么是第一类的蓝色方形或是第二类的红色三角形。如果k=3（实线圆圈）它被分配给第二类，因为有2个三角形和只有1个正方形在内侧圆圈之内。如果k=5（虚线圆圈）它被分配到第一类（3个正方形与2个三角形在外侧圆圈之内）&quot; /&gt;&lt;/p&gt;

&lt;p&gt;如上图所示，有&lt;strong&gt;两类&lt;/strong&gt;不同的样本数据，分别用蓝色的小正方形和红色的小三角形表示，而图正中间的那个绿色的圆所标示的数据则是&lt;strong&gt;待分类的数据&lt;/strong&gt;。这也就是我们的目的，来了一个新的数据点，我要得到它的类别是什么？好的，下面我们根据k近邻的思想来给绿色圆点进行分类。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;如果K=3，绿色圆点的最邻近的3个点是2个红色小三角形和1个蓝色小正方形，&lt;strong&gt;少数从属于多数，&lt;/strong&gt;基于统计的方法，判定绿色的这个待分类点属于红色的三角形一类。&lt;/li&gt;
  &lt;li&gt;如果K=5，绿色圆点的最邻近的5个邻居是2个红色三角形和3个蓝色的正方形，&lt;strong&gt;还是少数从属于多数，&lt;/strong&gt;基于统计的方法，判定绿色的这个待分类点属于蓝色的正方形一类。&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;从上面例子我们可以看出，k近邻的算法思想非常的简单，也非常的容易理解，那么我们是不是就到此结束了，&lt;strong&gt;该算法的原理我们也已经懂了，也知道怎么给新来的点如何进行归类，只要找到离它最近的k个实例，哪个类别最多即可。&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;12k近邻算法中k的选取以及特征归一化的重要性&quot;&gt;&lt;strong&gt;1.2、k近邻算法中k的选取以及特征归一化的重要性&lt;/strong&gt;&lt;/h2&gt;

&lt;h3 id=&quot;1选取k值以及它的影响&quot;&gt;&lt;strong&gt;1.选取k值以及它的影响&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;k近邻的k值我们应该怎么选取呢？&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;如果我们选取较小的k值，那么就会意味着我们的整体模型会变得复杂，容易发生过拟合！&lt;/strong&gt;恩~结论说完了，太抽象了吧你，不上图讲解号称通俗讲解的都是流氓&lt;strong&gt;~好吧，那我就上图来讲解&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;假设我们选取k=1这个极端情况，怎么就使得模型变得复杂，又容易过拟合了呢？&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;假设我们有训练数据和待分类点如下图：&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic2.zhimg.com/80/v2-6911dd1ce577c9fd6842cbd2ee68a309_720w.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;图中有俩类，一个是&lt;strong&gt;黑色的圆点&lt;/strong&gt;，一个是&lt;strong&gt;蓝色的长方形&lt;/strong&gt;，现在我们的待分类点是&lt;strong&gt;红色的五边形。&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;好，根据我们的k近邻算法步骤来决定待分类点应该归为哪一类。我们由图中可以得到，&lt;strong&gt;很容易我们能够看出来五边形离黑色的圆点最近，k又等于1，那太好了&lt;/strong&gt;，我们最终判定待分类点是黑色的圆点。&lt;/p&gt;

&lt;p&gt;由这个处理过程我们很容易能够感觉出问题了，如果k太小了，比如等于1，那么模型就太复杂了，&lt;strong&gt;我们很容易学习到噪声&lt;/strong&gt;，也就非常容易判定为噪声类别，而在上图，如果，k大一点，k等于8，&lt;strong&gt;把长方形都包括进来&lt;/strong&gt;，我们很容易得到我们正确的分类应该是蓝色的长方形！如下图：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic3.zhimg.com/80/v2-18df63acb37f29bd026e01770ef5c966_720w.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;所谓的过拟合就是在训练集上准确率非常高，而在测试集上准确率低，经过上例，我们可以得到k太小会导致&lt;strong&gt;过拟合&lt;/strong&gt;，&lt;strong&gt;很容易将一些噪声（如上图离五边形很近的黑色圆点）学习到模型中，而忽略了数据真实的分布！&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;如果我们选取较大的k值，就相当于用较大邻域中的训练数据进行预测，这时与输入实例较远的（不相似）训练实例也会对预测起作用，使预测发生错误，k值的增大意味着整体模型变得简单。&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;k值增大怎么就意味着模型变得简单了，不要急，我会解释的！哈哈。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;我们想，如果k=N（N为训练样本的个数）,那么无论输入实例是什么，都将简单地预测它属于在训练实例中最多的类。这时，模型是不是非常简单，这相当于你压根就没有训练模型呀！&lt;/strong&gt;直接拿训练数据统计了一下各个数据的类别，找最大的而已！这好像下图所示：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic1.zhimg.com/80/v2-e79d46a56c426061a9494091f8fac068_720w.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;我们统计了黑色圆形是8个，长方形个数是7个，那么哈哈，如果k=N，我就得出结论了，红色五边形是属于黑色圆形的（&lt;strong&gt;明显是错误的好不，捂脸！&lt;/strong&gt;）&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;这个时候，模型过于简单，完全忽略训练数据实例中的大量有用信息，是不可取的。&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;恩，k值既不能过大，也不能过小，在我举的这个例子中，我们k值的选择，在下图红色圆边界之间这个范围是最好的，如下图：&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic3.zhimg.com/80/v2-b7dc18ee84e5c099c21fbaa175a7b9c6_720w.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;（注：这里只是为了更好让大家理解，真实例子中不可能只有俩维特征，但是原理是一样的1，我们就是想找到较好的k值大小）&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;那么我们一般怎么选取呢？李航博士书上讲到，我们一般选取一个较小的数值，通常采取 交叉验证法来选取最优的k值。（&lt;strong&gt;也就是说，选取k值很重要的关键是实验调参，类似于神经网络选取多少层这种，通过调整超参数来得到一个较好的结果&lt;/strong&gt;）&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;小节&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;如李航博士的一书「统计学习方法」上所说：&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;如果选择较小的K值，就相当于用较小的领域中的训练实例进行预测，“学习”近似误差会减小，只有与输入实例较近或相似的训练实例才会对预测结果起作用，与此同时带来的问题是“学习”的估计误差会增大，换句话说，K值的减小就意味着整体模型变得复杂，容易发生过拟合；&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;如果选择较大的K值，就相当于用较大领域中的训练实例进行预测，其优点是可以减少学习的估计误差，但缺点是学习的近似误差会增大。这时候，与输入实例较远（不相似的）训练实例也会对预测器作用，使预测发生错误，且K值的增大就意味着整体的模型变得简单。&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;K=N，则完全不足取，因为此时无论输入实例是什么，都只是简单的预测它属于在训练实例中最多的累，模型过于简单，忽略了训练实例中大量有用信息。&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;​        在实际应用中，K值一般取一个比较小的数值，例如采用 &lt;a href=&quot;http://zh.wikipedia.org/zh/交叉驗證&quot;&gt;交叉验证&lt;/a&gt;法（简单来说，就是一部分样本做训练集，一部分做测试集）来选择最优的K值。&lt;/p&gt;

&lt;h3 id=&quot;2距离的度量&quot;&gt;&lt;strong&gt;2.距离的度量&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;在上文中说到，k近邻算法是在训练数据集中找到与该实例&lt;strong&gt;最邻近&lt;/strong&gt;的K个实例，这K个实例的多数属于某个类，我们就说预测点属于哪个类。&lt;/p&gt;

&lt;p&gt;定义中所说的最邻近是如何度量呢？我们怎么知道谁跟测试点最邻近。这里就会引出我们几种度量俩个点之间距离的标准。&lt;/p&gt;

&lt;p&gt;我们可以有以下几种度量方式：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic1.zhimg.com/80/v2-60bb382b0d22ec0ce296ed0e024f31bc_720w.png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;其中当p=2的时候，就是我们最常见的欧式距离，我们也一般都用欧式距离来衡量我们高维空间中俩点的距离。在实际应用中，距离函数的选择应该根据数据的特性和分析的需要而定，一般选取p=2欧式距离表示。&lt;/p&gt;

&lt;p&gt;其中具体包含的内容详细见&lt;a href=&quot;https://blog.csdn.net/v_july_v/article/details/8203674&quot;&gt;从K近邻算法、距离度量谈到KD树、SIFT+BBF算法&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;恩，距离度量我们也了解了，下面我要说一下各个维度归一化的必要性！&lt;/strong&gt;&lt;/p&gt;

&lt;h3 id=&quot;3特征归一化的必要性&quot;&gt;&lt;strong&gt;3.特征归一化的必要性&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;首先举例如下，我用一个人身高(cm)与脚码（尺码）大小来作为特征值，类别为男性或者女性。我们现在如果有5个训练样本，分布如下：&lt;/p&gt;

&lt;p&gt;A [(179,42),男] B [(178,43),男] C [(165,36)女] D [(177,42),男] E [(160,35),女]&lt;/p&gt;

&lt;p&gt;通过上述训练样本，我们看出问题了吗？&lt;/p&gt;

&lt;p&gt;很容易看到第一维身高特征是第二维脚码特征的4倍左右，那么在进行距离度量的时候，&lt;strong&gt;我们就会偏向于第一维特征。&lt;/strong&gt;这样造成俩个特征并不是等价重要的，最终可能会导致距离计算错误，从而导致预测错误。口说无凭，举例如下：&lt;/p&gt;

&lt;p&gt;现在我来了一个测试样本 F(167,43)，让我们来预测他是男性还是女性，我们采取k=3来预测。&lt;/p&gt;

&lt;p&gt;下面我们用欧式距离分别算出F离训练样本的欧式距离，然后选取最近的3个，多数类别就是我们最终的结果，计算如下：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic4.zhimg.com/80/v2-07d94c435dc95d66091768d56499f363_720w.png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;由计算可以得到，最近的前三个分别是C,D,E三个样本，那么由C,E为女性，D为男性，女性多于男性得到我们要预测的结果为&lt;strong&gt;女性&lt;/strong&gt;。&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;这样问题就来了，一个女性的脚43码的可能性，远远小于男性脚43码的可能性，那么为什么算法还是会预测F为女性呢？那是因为由于各个特征量纲的不同，在这里导致了身高的重要性已经远远大于脚码了，这是不客观的。&lt;/strong&gt;所以我们应该让每个特征都是同等重要的！这也是我们要归一化的原因！归一化公式如下：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://pic4.zhimg.com/80/v2-be30691d37ac93b2237217cadca2e967_720w.png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;讲到这里，k近邻算法基本内容我们已经讲完了。除去之后为了提高查找效率提出的kd树外，算法的原理，应用等方面已经讲解完毕，由于每篇文章内容不宜太多，kd树等知识下篇讲解，这里总结一下本文讲的内容。&lt;/p&gt;

&lt;h2 id=&quot;13第一部分小结&quot;&gt;&lt;strong&gt;1.3、第一部分小结&lt;/strong&gt;&lt;/h2&gt;

&lt;p&gt;1.我们提出了k近邻算法，算法的核心思想是，即是给定一个训练数据集，对新的输入实例，在训练数据集中找到与该实例最邻近的K个实例，这K个实例的多数属于某个类，就把该输入实例分类到这个类中。&lt;strong&gt;更通俗说一遍算法的过程，来了一个新的输入实例，我们算出该实例与每一个训练点的距离（这里的复杂度为0(n)比较大，所以引出了下文的kd树等结构），然后找到前k个，这k个哪个类别数最多，我们就判断新的输入实例就是哪类！&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;2.与该实例最近邻的k个实例，这个最近邻的定义是通过不同&lt;strong&gt;距离函数&lt;/strong&gt;来定义，我们最常用的是欧式距离。&lt;/p&gt;

&lt;p&gt;3.为了保证每个特征同等重要性，我们这里对每个特征进行&lt;strong&gt;归一化&lt;/strong&gt;。&lt;/p&gt;

&lt;p&gt;4.k值的选取，既不能太大，也不能太小，何值为最好，需要实验调整参数确定！&lt;/p&gt;

&lt;h1 id=&quot;第二部分k近邻算法的实现kd树&quot;&gt;第二部分：K近邻算法的实现：KD树&lt;/h1&gt;

&lt;h2 id=&quot;21什么是kd树&quot;&gt;2.1、什么是KD树&lt;/h2&gt;

&lt;p&gt;Kd-树是K-dimension tree的缩写，是对数据点在k维空间（如二维(x，y)，三维(x，y，z)，k维(x1，y，z..)）中划分的一种数据结构，主要应用于多维空间关键数据的搜索（如：范围搜索和最近邻搜索）。本质上说，Kd-树就是一种平衡二叉树。&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;首先必须搞清楚的是，k-d树是一种空间划分树，说白了，就是把整个空间划分为特定的几个部分，然后在特定空间的部分内进行相关搜索操作。&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;22kd树基本原理&quot;&gt;2.2、KD树基本原理&lt;/h2&gt;

&lt;p&gt;kd树构建的伪代码如下图所示（伪代码来自《图像局部不变特性特征与描述》王永明 王贵锦 编著）：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWctbXkuY3Nkbi5uZXQvdXBsb2Fkcy8yMDEyMTEvMjQvMTM1MzczMjA5MV80MjI1LmpwZw?x-oss-process=image/format,png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;再举一个简单直观的实例来介绍k-d树构建算法。假设有6个二维数据点{(2,3)，(5,4)，(9,6)，(4,7)，(8,1)，(7,2)}，数据点位于二维空间内，如下图所示。为了能有效的找到最近邻，k-d树采用分而治之的思想，即将整个空间划分为几个小部分，首先，粗黑线将空间一分为二，然后在两个子空间中，细黑直线又将整个空间划分为四部分，最后虚黑直线将这四部分进一步划分。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWctbXkuY3Nkbi5uZXQvdXBsb2Fkcy8yMDEyMTEvMjAvMTM1MzQwNTkyMV8zMDY2LmpwZw?x-oss-process=image/format,png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;6个二维数据点{(2,3)，(5,4)，(9,6)，(4,7)，(8,1)，(7,2)}构建kd树的具体步骤为：&lt;/p&gt;

&lt;p&gt;确定：split域=x。具体是：6个数据点在x，y维度上的数据方差分别为39，28.63，所以在x轴上方差更大，故split域值为x；
确定：Node-data = （7,2）。具体是：根据x维上的值将数据排序，6个数据的中值(所谓中值，即中间大小的值)为7，所以Node-data域位数据点（7,2）。这样，该节点的分割超平面就是通过（7,2）并垂直于：split=x轴的直线x=7；
确定：左子空间和右子空间。具体是：分割超平面x=7将整个空间分为两部分：x&amp;lt;=7的部分为左子空间，包含3个节点={(2,3),(5,4),(4,7)}；另一部分为右子空间，包含2个节点={(9,6)，(8,1)}；&lt;/p&gt;

&lt;p&gt;如上算法所述，kd树的构建是一个递归过程，我们对左子空间和右子空间内的数据重复根节点的过程就可以得到一级子节点（5,4）和（9,6），同时将空间和数据集进一步细分，如此往复直到空间中只包含一个数据点。&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWctbXkuY3Nkbi5uZXQvdXBsb2Fkcy8yMDEyMTEvMjQvMTM1MzczNTQ2Ml80NTIyLmpwZw?x-oss-process=image/format,png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;与此同时，经过对上面所示的空间划分之后，我们可以看出，点(7,2)可以为根结点，从根结点出发的两条红粗斜线指向的(5,4)和(9,6)则为根结点的左右子结点，而(2,3)，(4,7)则为(5,4)的左右孩子(通过两条细红斜线相连)，最后，(8,1)为(9,6)的左孩子(通过细红斜线相连)。如此，便形成了下面这样一棵k-d树：&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWctbXkuY3Nkbi5uZXQvdXBsb2Fkcy8yMDEyMTEvMjAvMTM1MzQwNjI3Nl80MDk1LmpwZw?x-oss-process=image/format,png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;k-d树的数据结构&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWctbXkuY3Nkbi5uZXQvdXBsb2Fkcy8yMDEyMTEvMjAvMTM1MzQwNDY0OF8yMDg2LmpwZw?x-oss-process=image/format,png&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;针对上表给出的kd树的数据结构，转化成具体代码如下所示(注，本文以下代码分析基于Rob Hess维护的sift库)：&lt;/p&gt;

&lt;div class=&quot;language-c++ highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;cm&quot;&gt;/** a node in a k-d tree */&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;kd_node&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
	&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ki&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;                      &lt;span class=&quot;cm&quot;&gt;/**&amp;lt; partition key index */&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//关键点直方图方差最大向量系列位置&lt;/span&gt;
	&lt;span class=&quot;kt&quot;&gt;double&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;                   &lt;span class=&quot;cm&quot;&gt;/**&amp;lt; partition key value */&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;//直方图方差最大向量系列中最中间模值&lt;/span&gt;
	&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;leaf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;                    &lt;span class=&quot;cm&quot;&gt;/**&amp;lt; 1 if node is a leaf, 0 otherwise */&lt;/span&gt;
	&lt;span class=&quot;k&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;feature&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;    &lt;span class=&quot;cm&quot;&gt;/**&amp;lt; features at this node */&lt;/span&gt;
	&lt;span class=&quot;kt&quot;&gt;int&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;                       &lt;span class=&quot;cm&quot;&gt;/**&amp;lt; number of features */&lt;/span&gt;
	&lt;span class=&quot;k&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;kd_node&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kd_left&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;     &lt;span class=&quot;cm&quot;&gt;/**&amp;lt; left child */&lt;/span&gt;
	&lt;span class=&quot;k&quot;&gt;struct&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;kd_node&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kd_right&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;    &lt;span class=&quot;cm&quot;&gt;/**&amp;lt; right child */&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;也就是说，如之前所述，kd树中，kd代表k-dimension，每个节点即为一个k维的点。每个非叶节点可以想象为一个分割超平面，用垂直于坐标轴的超平面将空间分为两个部分，这样递归的从根节点不停的划分，直到没有实例为止。经典的构造k-d tree的规则如下：&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;随着树的深度增加，循环的选取坐标轴，作为分割超平面的法向量。对于3-d tree来说，根节点选取x轴，根节点的孩子选取y轴，根节点的孙子选取z轴，根节点的曾孙子选取x轴，这样循环下去。&lt;/li&gt;
  &lt;li&gt;每次均为所有对应实例的中位数的实例作为切分点，切分点作为父节点，左右两侧为划分的作为左右两子树。&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWctbXkuY3Nkbi5uZXQvdXBsb2Fkcy8yMDEyMTEvMjQvMTM1MzczMDY5NF84OTQxLmdpZg&quot; alt=&quot;img&quot; /&gt;&lt;/p&gt;

&lt;p&gt;对于n个实例的k维数据来说，建立kd-tree的时间复杂度为O(k&lt;em&gt;n&lt;/em&gt;logn)。&lt;/p&gt;

&lt;h2 id=&quot;23k树的构建及插入删除改进&quot;&gt;2.3、K树的构建及插入删除，改进&lt;/h2&gt;

&lt;p&gt;详细查看：&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://blog.csdn.net/v_july_v/article/details/8203674&quot;&gt;从K近邻算法、距离度量谈到KD树、SIFT+BBF算法&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;参考：&lt;/p&gt;

&lt;p&gt;李航博士《统计学习方法》&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://zhuanlan.zhihu.com/p/25994179&quot;&gt;一文搞懂k近邻（k-NN）算法（一）&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://link.zhihu.com/?target=https%3A//www.joinquant.com/post/2227%3Ff%3Dzh%26%3Bm%3D23028465&quot;&gt;【量化课堂】一只兔子帮你理解 kNN&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://link.zhihu.com/?target=http%3A//blog.csdn.net/v_july_v/article/details/8203674&quot;&gt;从K近邻算法、距离度量谈到KD树、SIFT+BBF算法 - 结构之法 算法之道 - 博客频道 - CSDN.NET&lt;/a&gt;&lt;/p&gt;</content><author><name>乌墨_rfr</name></author><category term="机器学习" /><category term="K-近邻算法" /><summary type="html">第一部分：K近邻算法原理 1.1、k近邻算法的基本概念，原理以及应用 K近邻算法，即是给定一个训练数据集，对新的输入实例，在训练数据集中找到与该实例最邻近的K个实例，这K个实例的多数属于某个类，就把该输入实例分类到这个类中。（这就类似于现实生活中少数服从多数的思想） 如上图所示，有两类不同的样本数据，分别用蓝色的小正方形和红色的小三角形表示，而图正中间的那个绿色的圆所标示的数据则是待分类的数据。这也就是我们的目的，来了一个新的数据点，我要得到它的类别是什么？好的，下面我们根据k近邻的思想来给绿色圆点进行分类。 如果K=3，绿色圆点的最邻近的3个点是2个红色小三角形和1个蓝色小正方形，少数从属于多数，基于统计的方法，判定绿色的这个待分类点属于红色的三角形一类。 如果K=5，绿色圆点的最邻近的5个邻居是2个红色三角形和3个蓝色的正方形，还是少数从属于多数，基于统计的方法，判定绿色的这个待分类点属于蓝色的正方形一类。 从上面例子我们可以看出，k近邻的算法思想非常的简单，也非常的容易理解，那么我们是不是就到此结束了，该算法的原理我们也已经懂了，也知道怎么给新来的点如何进行归类，只要找到离它最近的k个实例，哪个类别最多即可。 1.2、k近邻算法中k的选取以及特征归一化的重要性 1.选取k值以及它的影响 k近邻的k值我们应该怎么选取呢？ 如果我们选取较小的k值，那么就会意味着我们的整体模型会变得复杂，容易发生过拟合！恩~结论说完了，太抽象了吧你，不上图讲解号称通俗讲解的都是流氓~好吧，那我就上图来讲解 假设我们选取k=1这个极端情况，怎么就使得模型变得复杂，又容易过拟合了呢？ 假设我们有训练数据和待分类点如下图： 图中有俩类，一个是黑色的圆点，一个是蓝色的长方形，现在我们的待分类点是红色的五边形。 好，根据我们的k近邻算法步骤来决定待分类点应该归为哪一类。我们由图中可以得到，很容易我们能够看出来五边形离黑色的圆点最近，k又等于1，那太好了，我们最终判定待分类点是黑色的圆点。 由这个处理过程我们很容易能够感觉出问题了，如果k太小了，比如等于1，那么模型就太复杂了，我们很容易学习到噪声，也就非常容易判定为噪声类别，而在上图，如果，k大一点，k等于8，把长方形都包括进来，我们很容易得到我们正确的分类应该是蓝色的长方形！如下图： 所谓的过拟合就是在训练集上准确率非常高，而在测试集上准确率低，经过上例，我们可以得到k太小会导致过拟合，很容易将一些噪声（如上图离五边形很近的黑色圆点）学习到模型中，而忽略了数据真实的分布！ 如果我们选取较大的k值，就相当于用较大邻域中的训练数据进行预测，这时与输入实例较远的（不相似）训练实例也会对预测起作用，使预测发生错误，k值的增大意味着整体模型变得简单。 k值增大怎么就意味着模型变得简单了，不要急，我会解释的！哈哈。 我们想，如果k=N（N为训练样本的个数）,那么无论输入实例是什么，都将简单地预测它属于在训练实例中最多的类。这时，模型是不是非常简单，这相当于你压根就没有训练模型呀！直接拿训练数据统计了一下各个数据的类别，找最大的而已！这好像下图所示： 我们统计了黑色圆形是8个，长方形个数是7个，那么哈哈，如果k=N，我就得出结论了，红色五边形是属于黑色圆形的（明显是错误的好不，捂脸！） 这个时候，模型过于简单，完全忽略训练数据实例中的大量有用信息，是不可取的。 恩，k值既不能过大，也不能过小，在我举的这个例子中，我们k值的选择，在下图红色圆边界之间这个范围是最好的，如下图： （注：这里只是为了更好让大家理解，真实例子中不可能只有俩维特征，但是原理是一样的1，我们就是想找到较好的k值大小） 那么我们一般怎么选取呢？李航博士书上讲到，我们一般选取一个较小的数值，通常采取 交叉验证法来选取最优的k值。（也就是说，选取k值很重要的关键是实验调参，类似于神经网络选取多少层这种，通过调整超参数来得到一个较好的结果） 小节 如李航博士的一书「统计学习方法」上所说： 如果选择较小的K值，就相当于用较小的领域中的训练实例进行预测，“学习”近似误差会减小，只有与输入实例较近或相似的训练实例才会对预测结果起作用，与此同时带来的问题是“学习”的估计误差会增大，换句话说，K值的减小就意味着整体模型变得复杂，容易发生过拟合； 如果选择较大的K值，就相当于用较大领域中的训练实例进行预测，其优点是可以减少学习的估计误差，但缺点是学习的近似误差会增大。这时候，与输入实例较远（不相似的）训练实例也会对预测器作用，使预测发生错误，且K值的增大就意味着整体的模型变得简单。 K=N，则完全不足取，因为此时无论输入实例是什么，都只是简单的预测它属于在训练实例中最多的累，模型过于简单，忽略了训练实例中大量有用信息。 ​ 在实际应用中，K值一般取一个比较小的数值，例如采用 交叉验证法（简单来说，就是一部分样本做训练集，一部分做测试集）来选择最优的K值。 2.距离的度量 在上文中说到，k近邻算法是在训练数据集中找到与该实例最邻近的K个实例，这K个实例的多数属于某个类，我们就说预测点属于哪个类。 定义中所说的最邻近是如何度量呢？我们怎么知道谁跟测试点最邻近。这里就会引出我们几种度量俩个点之间距离的标准。 我们可以有以下几种度量方式： 其中当p=2的时候，就是我们最常见的欧式距离，我们也一般都用欧式距离来衡量我们高维空间中俩点的距离。在实际应用中，距离函数的选择应该根据数据的特性和分析的需要而定，一般选取p=2欧式距离表示。 其中具体包含的内容详细见从K近邻算法、距离度量谈到KD树、SIFT+BBF算法 恩，距离度量我们也了解了，下面我要说一下各个维度归一化的必要性！ 3.特征归一化的必要性 首先举例如下，我用一个人身高(cm)与脚码（尺码）大小来作为特征值，类别为男性或者女性。我们现在如果有5个训练样本，分布如下： A [(179,42),男] B [(178,43),男] C [(165,36)女] D [(177,42),男] E [(160,35),女] 通过上述训练样本，我们看出问题了吗？ 很容易看到第一维身高特征是第二维脚码特征的4倍左右，那么在进行距离度量的时候，我们就会偏向于第一维特征。这样造成俩个特征并不是等价重要的，最终可能会导致距离计算错误，从而导致预测错误。口说无凭，举例如下： 现在我来了一个测试样本 F(167,43)，让我们来预测他是男性还是女性，我们采取k=3来预测。 下面我们用欧式距离分别算出F离训练样本的欧式距离，然后选取最近的3个，多数类别就是我们最终的结果，计算如下： 由计算可以得到，最近的前三个分别是C,D,E三个样本，那么由C,E为女性，D为男性，女性多于男性得到我们要预测的结果为女性。 这样问题就来了，一个女性的脚43码的可能性，远远小于男性脚43码的可能性，那么为什么算法还是会预测F为女性呢？那是因为由于各个特征量纲的不同，在这里导致了身高的重要性已经远远大于脚码了，这是不客观的。所以我们应该让每个特征都是同等重要的！这也是我们要归一化的原因！归一化公式如下： 讲到这里，k近邻算法基本内容我们已经讲完了。除去之后为了提高查找效率提出的kd树外，算法的原理，应用等方面已经讲解完毕，由于每篇文章内容不宜太多，kd树等知识下篇讲解，这里总结一下本文讲的内容。 1.3、第一部分小结 1.我们提出了k近邻算法，算法的核心思想是，即是给定一个训练数据集，对新的输入实例，在训练数据集中找到与该实例最邻近的K个实例，这K个实例的多数属于某个类，就把该输入实例分类到这个类中。更通俗说一遍算法的过程，来了一个新的输入实例，我们算出该实例与每一个训练点的距离（这里的复杂度为0(n)比较大，所以引出了下文的kd树等结构），然后找到前k个，这k个哪个类别数最多，我们就判断新的输入实例就是哪类！ 2.与该实例最近邻的k个实例，这个最近邻的定义是通过不同距离函数来定义，我们最常用的是欧式距离。 3.为了保证每个特征同等重要性，我们这里对每个特征进行归一化。 4.k值的选取，既不能太大，也不能太小，何值为最好，需要实验调整参数确定！ 第二部分：K近邻算法的实现：KD树 2.1、什么是KD树 Kd-树是K-dimension tree的缩写，是对数据点在k维空间（如二维(x，y)，三维(x，y，z)，k维(x1，y，z..)）中划分的一种数据结构，主要应用于多维空间关键数据的搜索（如：范围搜索和最近邻搜索）。本质上说，Kd-树就是一种平衡二叉树。 首先必须搞清楚的是，k-d树是一种空间划分树，说白了，就是把整个空间划分为特定的几个部分，然后在特定空间的部分内进行相关搜索操作。 2.2、KD树基本原理 kd树构建的伪代码如下图所示（伪代码来自《图像局部不变特性特征与描述》王永明 王贵锦 编著）： 再举一个简单直观的实例来介绍k-d树构建算法。假设有6个二维数据点{(2,3)，(5,4)，(9,6)，(4,7)，(8,1)，(7,2)}，数据点位于二维空间内，如下图所示。为了能有效的找到最近邻，k-d树采用分而治之的思想，即将整个空间划分为几个小部分，首先，粗黑线将空间一分为二，然后在两个子空间中，细黑直线又将整个空间划分为四部分，最后虚黑直线将这四部分进一步划分。 6个二维数据点{(2,3)，(5,4)，(9,6)，(4,7)，(8,1)，(7,2)}构建kd树的具体步骤为： 确定：split域=x。具体是：6个数据点在x，y维度上的数据方差分别为39，28.63，所以在x轴上方差更大，故split域值为x； 确定：Node-data = （7,2）。具体是：根据x维上的值将数据排序，6个数据的中值(所谓中值，即中间大小的值)为7，所以Node-data域位数据点（7,2）。这样，该节点的分割超平面就是通过（7,2）并垂直于：split=x轴的直线x=7； 确定：左子空间和右子空间。具体是：分割超平面x=7将整个空间分为两部分：x&amp;lt;=7的部分为左子空间，包含3个节点={(2,3),(5,4),(4,7)}；另一部分为右子空间，包含2个节点={(9,6)，(8,1)}； 如上算法所述，kd树的构建是一个递归过程，我们对左子空间和右子空间内的数据重复根节点的过程就可以得到一级子节点（5,4）和（9,6），同时将空间和数据集进一步细分，如此往复直到空间中只包含一个数据点。 与此同时，经过对上面所示的空间划分之后，我们可以看出，点(7,2)可以为根结点，从根结点出发的两条红粗斜线指向的(5,4)和(9,6)则为根结点的左右子结点，而(2,3)，(4,7)则为(5,4)的左右孩子(通过两条细红斜线相连)，最后，(8,1)为(9,6)的左孩子(通过细红斜线相连)。如此，便形成了下面这样一棵k-d树： k-d树的数据结构 针对上表给出的kd树的数据结构，转化成具体代码如下所示(注，本文以下代码分析基于Rob Hess维护的sift库)： /** a node in a k-d tree */ struct kd_node { int ki; /**&amp;lt; partition key index *///关键点直方图方差最大向量系列位置 double kv; /**&amp;lt; partition key value *///直方图方差最大向量系列中最中间模值 int leaf; /**&amp;lt; 1 if node is a leaf, 0 otherwise */ struct feature* features; /**&amp;lt; features at this node */ int n; /**&amp;lt; number of features */ struct kd_node* kd_left; /**&amp;lt; left child */ struct kd_node* kd_right; /**&amp;lt; right child */ }; 也就是说，如之前所述，kd树中，kd代表k-dimension，每个节点即为一个k维的点。每个非叶节点可以想象为一个分割超平面，用垂直于坐标轴的超平面将空间分为两个部分，这样递归的从根节点不停的划分，直到没有实例为止。经典的构造k-d tree的规则如下： 随着树的深度增加，循环的选取坐标轴，作为分割超平面的法向量。对于3-d tree来说，根节点选取x轴，根节点的孩子选取y轴，根节点的孙子选取z轴，根节点的曾孙子选取x轴，这样循环下去。 每次均为所有对应实例的中位数的实例作为切分点，切分点作为父节点，左右两侧为划分的作为左右两子树。 对于n个实例的k维数据来说，建立kd-tree的时间复杂度为O(knlogn)。 2.3、K树的构建及插入删除，改进 详细查看： 从K近邻算法、距离度量谈到KD树、SIFT+BBF算法 参考： 李航博士《统计学习方法》 一文搞懂k近邻（k-NN）算法（一） 【量化课堂】一只兔子帮你理解 kNN 从K近邻算法、距离度量谈到KD树、SIFT+BBF算法 - 结构之法 算法之道 - 博客频道 - CSDN.NET</summary></entry></feed>