mirror of
https://github.com/Estom/notes.git
synced 2026-11-28 06:11:42 +08:00
netowkx和pyg的教程
This commit is contained in:
283
Python/networkx/0 基础使用.md
Normal file
283
Python/networkx/0 基础使用.md
Normal file
@@ -0,0 +1,283 @@
|
||||
# 教程
|
||||
|
||||
> 参考文献
|
||||
> * [官方文档](https://www.osgeo.cn/networkx/tutorial.html)
|
||||
|
||||
## 0 简单介绍
|
||||
|
||||
### 图的类型
|
||||
|
||||
* Graph类是无向图的基类,无向图能有自己的属性或参数,不包含重边,允许有回路,节点可以是任何hash的python对象,节点和边可以保存key/value属性对。该类的构造函数为Graph(data=None,**attr),其中data可以是边列表,或任意一个Networkx的图对象,默认为none;attr是关键字参数,例如key=value对形式的属性。
|
||||
* MultiGraph是可以有重边的无向图,其它和Graph类似。其构造函数MultiGraph(data=None, *attr)。
|
||||
* DiGraph是有向图的基类,有向图可以有数自己的属性或参数,不包含重边,允许有回路;节点可以是任何hash的python对象,边和节点可含key/value属性对。该类的构造函数DiGraph(data=None,**attr),其中data可以是边列表,或任意一个Networkx的图对象,默认为none;attr是关键字参数,例如key=value对形式的属性。
|
||||
* MultiDiGraph是可以有重边的有向图,其它和DiGraph类似。其构造函数MultiDiGraph(data=None, *attr)
|
||||
|
||||
|
||||
### 有向图
|
||||
|
||||
|
||||
这个 DiGraph 提供了附加的属性,DiGraph.out_edges , DiGraph.in_degree , DiGraph.predecessors() , DiGraph.successors() 等。为了使算法能够轻松地与两个类一起工作,有向版本的 neighbors() 等于 successors() 虽然 degree 报告 in_degree 和 out_degree 尽管有时会觉得不一致。
|
||||
|
||||
```py
|
||||
DG = nx.DiGraph()
|
||||
DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
|
||||
DG.out_degree(1, weight='weight')
|
||||
0.5
|
||||
DG.degree(1, weight='weight')
|
||||
1.25
|
||||
list(DG.successors(1))
|
||||
[2]
|
||||
list(DG.neighbors(1))
|
||||
[2]
|
||||
```
|
||||
|
||||
有向图和无向图的转换
|
||||
|
||||
```py
|
||||
Graph.to_undirected()
|
||||
H = nx.Graph(G) # create an undirected graph H from a directed graph G
|
||||
```
|
||||
|
||||
|
||||
### 多重图
|
||||
|
||||
多重图
|
||||
NetworkX为允许任意节点对之间存在多个边的图形提供类。这个 MultiGraph 和 MultiDiGraph 类允许您两次添加相同的边缘,可能使用不同的边缘数据。这对某些应用程序来说可能很强大,但许多算法在此类图上没有很好的定义。如果结果定义明确,例如: MultiGraph.degree() 我们提供功能。否则,您应该以一种使测量定义良好的方式转换为标准图。
|
||||
|
||||
```py
|
||||
MG = nx.MultiGraph()
|
||||
MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
|
||||
dict(MG.degree(weight='weight'))
|
||||
{1: 1.25, 2: 1.75, 3: 0.5}
|
||||
GG = nx.Graph()
|
||||
for n, nbrs in MG.adjacency():
|
||||
for nbr, edict in nbrs.items():
|
||||
minvalue = min([d['weight'] for d in edict.values()])
|
||||
GG.add_edge(n, nbr, weight = minvalue)
|
||||
|
||||
nx.shortest_path(GG, 1, 3)
|
||||
[1, 2, 3]
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 1 增加
|
||||
|
||||
### 创建图形
|
||||
创建一个没有节点和边的空图形。
|
||||
|
||||
```py
|
||||
>>>
|
||||
import networkx as nx
|
||||
G = nx.Graph()
|
||||
```
|
||||
根据定义,a Graph 是一组节点(顶点)和已识别的节点对(称为边、链接等)的集合。在NetworkX中,节点可以是任何 hashable 对象,例如文本字符串、图像、XML对象、另一个图形、自定义节点对象等
|
||||
|
||||
|
||||
### 添加节点
|
||||
|
||||
图 G 可以通过多种方式生长。NetworkX包括许多图形生成器功能和以多种格式读取和写入图形的工具。我们先来看看简单的操作。
|
||||
|
||||
* 一次添加一个节点,
|
||||
|
||||
```py
|
||||
G.add_node(1)
|
||||
```
|
||||
|
||||
* 从任何 iterable 容器,如列表
|
||||
|
||||
```py
|
||||
G.add_nodes_from([2, 3])
|
||||
```
|
||||
|
||||
* 如果容器产生2个元组形式,还可以添加节点和节点属性 (node, node_attribute_dict) ::
|
||||
|
||||
```py
|
||||
G.add_nodes_from([
|
||||
(4, {"color": "red"}),
|
||||
(5, {"color": "green"}),
|
||||
])
|
||||
```
|
||||
|
||||
* 一个图中的节点可以合并到另一个图中
|
||||
|
||||
```py
|
||||
H = nx.path_graph(10)
|
||||
G.add_nodes_from(H)
|
||||
```
|
||||
|
||||
* G 现在包含的节点 H 作为节点 G . 相反,您可以使用图表 H 作为一个节点 G .
|
||||
```
|
||||
G.add_node(H)
|
||||
```
|
||||
|
||||
|
||||
### 添加边缘
|
||||
|
||||
* G 也可以通过一次添加一个边来生长,
|
||||
|
||||
```
|
||||
G.add_edge(1, 2)
|
||||
e = (2, 3)
|
||||
G.add_edge(*e) # unpack edge tuple*
|
||||
```
|
||||
|
||||
* 通过添加边列表,
|
||||
|
||||
```
|
||||
G.add_edges_from([(1, 2), (1, 3)])
|
||||
```
|
||||
|
||||
* 我们添加新的节点/边缘,忽略已经存在的节点和边
|
||||
```
|
||||
>>>
|
||||
G.add_edges_from([(1, 2), (1, 3)])
|
||||
G.add_node(1) # 已经存在1节点,不再重复添加
|
||||
G.add_edge(1, 2) # 已经存在1,2边,不再重复添加
|
||||
G.add_node("spam") # adds node "spam"
|
||||
G.add_nodes_from("spam") # adds 4 nodes: 's', 'p', 'a', 'm'
|
||||
G.add_edge(3, 'm')
|
||||
```
|
||||
|
||||
* 在这个阶段,图表 G 由8个节点和3个边组成,如下所示:
|
||||
|
||||
```py
|
||||
>>>
|
||||
G.number_of_nodes()
|
||||
8
|
||||
G.number_of_edges()
|
||||
3
|
||||
```
|
||||
|
||||
## 2 删除
|
||||
### 删除元素
|
||||
可以用与添加类似的方式从图形中删除节点和边。
|
||||
* Graph.remove_node()
|
||||
* Graph.remove_nodes_from()
|
||||
* Graph.remove_edge()
|
||||
* Graph.remove_edges_from()
|
||||
|
||||
```
|
||||
>>>
|
||||
G.remove_node(2)
|
||||
G.remove_nodes_from("spam")
|
||||
list(G.nodes)
|
||||
[1, 3, 'spam']
|
||||
G.remove_edge(1, 3)
|
||||
```
|
||||
|
||||
|
||||
### 构造函数
|
||||
图形对象不必以增量方式构建——指定图形结构的数据可以直接传递给各种图形类的构造函数。当通过实例化一个图形类来创建一个图结构时,可以用几种格式指定数据。
|
||||
|
||||
```
|
||||
G.add_edge(1, 2)
|
||||
H = nx.DiGraph(G) # create a DiGraph using the connections from G
|
||||
list(H.edges())
|
||||
[(1, 2), (2, 1)]
|
||||
edgelist = [(0, 1), (1, 2), (2, 3)]
|
||||
H = nx.Graph(edgelist)
|
||||
```
|
||||
|
||||
## 3 查找
|
||||
### 访问边缘和邻居
|
||||
* 除了视图 Graph.edges 和 Graph.adj ,可以使用下标表示法访问边和邻居。
|
||||
|
||||
```py
|
||||
G = nx.Graph([(1, 2, {"color": "yellow"})])
|
||||
G[1] # same as G.adj[1]
|
||||
AtlasView({2: {'color': 'yellow'}})
|
||||
G[1][2]
|
||||
{'color': 'yellow'}
|
||||
G.edges[1, 2]
|
||||
{'color': 'yellow'}
|
||||
```
|
||||
|
||||
* 如果边已经存在,可以使用下标表示法获取/设置边的属性。
|
||||
|
||||
```py
|
||||
G.add_edge(1, 3)
|
||||
G[1][3]['color'] = "blue"
|
||||
G.edges[1, 2]['color'] = "red"
|
||||
G.edges[1, 2]
|
||||
{'color': 'red'}
|
||||
```
|
||||
|
||||
* 使用 G.adjacency() 或 G.adj.items() . 注意,对于无向图,邻接迭代可以看到每个边两次。
|
||||
|
||||
```py
|
||||
FG = nx.Graph()
|
||||
FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])
|
||||
for n, nbrs in FG.adj.items():
|
||||
for nbr, eattr in nbrs.items():
|
||||
wt = eattr['weight']
|
||||
if wt < 0.5: print(f"({n}, {nbr}, {wt:.3})")
|
||||
(1, 2, 0.125)
|
||||
(2, 1, 0.125)
|
||||
(3, 4, 0.375)
|
||||
(4, 3, 0.375)
|
||||
```
|
||||
|
||||
* 使用边缘属性可以方便地访问所有边缘。
|
||||
|
||||
```py
|
||||
for (u, v, wt) in FG.edges.data('weight'):
|
||||
if wt < 0.5:
|
||||
print(f"({u}, {v}, {wt:.3})")
|
||||
(1, 2, 0.125)
|
||||
(3, 4, 0.375)
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 4 修改
|
||||
向图形、节点和边添加属性
|
||||
|
||||
诸如权重、标签、颜色或任何您喜欢的python对象等属性都可以附加到图形、节点或边上。
|
||||
|
||||
每个图、节点和边都可以在关联的属性字典中保存键/值属性对(键必须是可哈希的)。默认情况下,这些属性为空,但可以使用 add_edge , add_node 或直接操作命名的属性字典 G.graph , G.nodes 和 G.edges 对于图 G .
|
||||
|
||||
### 图形属性
|
||||
|
||||
创建新图形时分配图形属性
|
||||
|
||||
```
|
||||
G = nx.Graph(day="Friday")
|
||||
G.graph
|
||||
{'day': 'Friday'}
|
||||
```
|
||||
或者您可以稍后修改属性
|
||||
|
||||
```
|
||||
G.graph['day'] = "Monday"
|
||||
G.graph
|
||||
{'day': 'Monday'}
|
||||
```
|
||||
### 节点属性
|
||||
使用添加节点属性 add_node() , add_nodes_from() 或 G.nodes
|
||||
|
||||
```py
|
||||
G.add_node(1, time='5pm')
|
||||
G.add_nodes_from([3], time='2pm')
|
||||
G.nodes[1]
|
||||
{'time': '5pm'}
|
||||
G.nodes[1]['room'] = 714
|
||||
G.nodes.data()
|
||||
NodeDataView({1: {'time': '5pm', 'room': 714}, 3: {'time': '2pm'}})
|
||||
```
|
||||
|
||||
|
||||
请注意,将节点添加到 G.nodes 不将其添加到图表中,使用 G.add_node() 添加新节点。同样适用于边缘。
|
||||
|
||||
### 边缘属性
|
||||
使用添加/更改边缘属性 add_edge() , add_edges_from() 或下标符号。
|
||||
|
||||
```py
|
||||
G.add_edge(1, 2, weight=4.7 )
|
||||
G.add_edges_from([(3, 4), (4, 5)], color='red')
|
||||
G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})])
|
||||
G[1][2]['weight'] = 4.7
|
||||
G.edges[3, 4]['weight'] = 4.2
|
||||
```
|
||||
|
||||
特殊属性 weight 应该是数字,因为它被需要加权边缘的算法使用。
|
||||
53
Python/networkx/1 图的视图.md
Normal file
53
Python/networkx/1 图的视图.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# 图的视图
|
||||
|
||||
## 视图
|
||||
### 概述
|
||||
* 各种视图提供了图上节点、边、邻接矩阵和度本身的各种基础方法。这些视图提供对属性的迭代,以及成员查询和数据属性查找。
|
||||
* 视图引用图形数据结构,因此对图形的更改反映在视图中。这类似于Python3中的字典视图。是一种图表示的数据结构效率非常高,全是字典。
|
||||
* 如果要在迭代时更改图形,则需要使用例如 for e in list(G.edges): .
|
||||
* 视图提供了类似集合的操作,例如联合和交集,
|
||||
* 视图提供了类似dict的数据属性查找和迭代,使用 G.edges[u, v]['color'] 和 for e, datadict in G.edges.items(): . 方法 G.edges.items() 和 G.edges.values()
|
||||
|
||||
|
||||
## 2 常见的视图
|
||||
|
||||
```py
|
||||
__all__ = [
|
||||
"NodeView", #只包含节点的视图
|
||||
"NodeDataView", # 包含节点和属性的视图
|
||||
|
||||
"EdgeView", # 只保函边的视图
|
||||
"OutEdgeView",
|
||||
"InEdgeView",
|
||||
"EdgeDataView", # 包含边和属性的视图
|
||||
"OutEdgeDataView",
|
||||
"InEdgeDataView",
|
||||
|
||||
|
||||
"DegreeView", # 度的视图
|
||||
"DiDegreeView",
|
||||
"InDegreeView",
|
||||
"OutDegreeView",
|
||||
"MultiDegreeView",
|
||||
"DiMultiDegreeView",
|
||||
"InMultiDegreeView",
|
||||
"OutMultiDegreeView",
|
||||
|
||||
"adjacentView", # 邻接视图
|
||||
"AtlasView", # 邻接属性视图
|
||||
]
|
||||
```
|
||||
|
||||
### 节点视图
|
||||
|
||||
|
||||
### 边视图
|
||||
|
||||
### 邻接视图
|
||||
|
||||
### 度视图
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
225
Python/networkx/1.ipynb
Normal file
225
Python/networkx/1.ipynb
Normal file
@@ -0,0 +1,225 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 16,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import networkx as nx\n",
|
||||
"G = nx.Graph()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 17,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"G.add_nodes_from([1,2,3])\n",
|
||||
"G.add_edge(3,4)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 18,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[1, 2, 3, 4]\n",
|
||||
"[(3, 4)]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(G.nodes())\n",
|
||||
"print(G.edges())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 20,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"<ipython-input-20-2623cf771fd5>:3: UserWarning: Matplotlib is currently using ps, which is a non-GUI backend, so cannot show the figure.\n",
|
||||
" plt.show()\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"nx.draw(G)\n",
|
||||
"plt.show()\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 22,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"(1, 2, 0.125)\n",
|
||||
"(2, 1, 0.125)\n",
|
||||
"(3, 4, 0.375)\n",
|
||||
"(4, 3, 0.375)\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"FG = nx.Graph()\n",
|
||||
"FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])\n",
|
||||
"for n, nbrs in FG.adj.items():\n",
|
||||
" for nbr, eattr in nbrs.items():\n",
|
||||
" wt = eattr['weight']\n",
|
||||
" if wt < 0.5: print(f\"({n}, {nbr}, {wt:.3})\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 24,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"(1, 2, 0.125)\n",
|
||||
"(3, 4, 0.375)\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"for (u, v, wt) in FG.edges.data('weight'):\n",
|
||||
" if wt < 0.5:\n",
|
||||
" print(f\"({u}, {v}, {wt:.3})\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 33,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"ItemsView(AdjacencyView({1: {2: {'weight': 0.5}}, 2: {}, 3: {1: {'weight': 0.75}}}))\n",
|
||||
"[3]\n",
|
||||
"[2]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"DG = nx.DiGraph()\n",
|
||||
"DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])\n",
|
||||
"DG.out_degree(1, weight='weight')\n",
|
||||
"print(DG.adj.items())\n",
|
||||
"print(list(DG.predecessors(1)))\n",
|
||||
"print(list(DG.successors(1)))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 35,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"[[0 1 0 1 0 0 1 1 0 0]\n",
|
||||
" [1 0 1 1 1 1 0 1 0 1]\n",
|
||||
" [0 1 0 0 1 1 1 1 0 1]\n",
|
||||
" [0 0 1 0 0 0 0 1 1 1]\n",
|
||||
" [1 0 0 1 1 1 0 1 1 1]\n",
|
||||
" [0 0 0 0 0 0 0 0 1 1]\n",
|
||||
" [0 0 1 0 0 0 1 1 1 1]\n",
|
||||
" [1 0 1 0 0 1 1 0 0 0]\n",
|
||||
" [1 1 1 1 1 0 1 0 0 0]\n",
|
||||
" [1 1 1 0 0 0 0 0 0 1]]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"import numpy as np\n",
|
||||
"a = np.random.randint(0, 2, size=(10, 10))\n",
|
||||
"print(a)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 36,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"D = nx.DiGraph(a)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 40,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"array([[0., 1., 0., 1., 0., 0., 1., 1., 0., 0.],\n",
|
||||
" [1., 0., 1., 1., 1., 1., 0., 1., 0., 1.],\n",
|
||||
" [0., 1., 0., 0., 1., 1., 1., 1., 0., 1.],\n",
|
||||
" [0., 0., 1., 0., 0., 0., 0., 1., 1., 1.],\n",
|
||||
" [1., 0., 0., 1., 1., 1., 0., 1., 1., 1.],\n",
|
||||
" [0., 0., 0., 0., 0., 0., 0., 0., 1., 1.],\n",
|
||||
" [0., 0., 1., 0., 0., 0., 1., 1., 1., 1.],\n",
|
||||
" [1., 0., 1., 0., 0., 1., 1., 0., 0., 0.],\n",
|
||||
" [1., 1., 1., 1., 1., 0., 1., 0., 0., 0.],\n",
|
||||
" [1., 1., 1., 0., 0., 0., 0., 0., 0., 1.]])"
|
||||
]
|
||||
},
|
||||
"execution_count": 40,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"D.nodes()\n",
|
||||
"D.edges()\n",
|
||||
"nx.to_numpy_array(D)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"interpreter": {
|
||||
"hash": "5ef0042cb263260037aa2928643ae94e240dd3afaec7872ebebe4f07619ddd0c"
|
||||
},
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3.8.8 ('ml')",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.8.8"
|
||||
},
|
||||
"orig_nbformat": 4
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
69
Python/networkx/2 图生成器.md
Normal file
69
Python/networkx/2 图生成器.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# 图形生成器和图形操作
|
||||
|
||||
## 1 应用经典图形操作
|
||||
|
||||
|
||||
| subgraph \(G ,N启动) | 返回在nbunch中的节点上诱导的子图。 |
|
||||
|---|---|
|
||||
| union (g,h) [, rename, name] ) | 返回图g和h的并集。 |
|
||||
| disjoint_union (g,h) | 返回图G和图H的不相交的并集。 |
|
||||
| cartesian_product (g,h) | 返回g和h的笛卡尔积。 |
|
||||
| compose (g,h) | 返回由h组成的g的新图。 |
|
||||
| complement (g) | 返回g的图补。 |
|
||||
| create_empty_copy (g) [, with_data] ) | 返回图形G的副本,并删除所有边。 |
|
||||
| to_undirected [(图)] | 返回图表的无向视图 graph . |
|
||||
| to_directed [(图)] | 返回图形的定向视图 graph . |
|
||||
|
||||
|
||||
## 2 经典生成小图
|
||||
|
||||
|
||||
| petersen_graph \ [create_using] ) | 返回彼得森图。 |
|
||||
|---|---|
|
||||
| tutte_graph \ [create_using] ) | 返回图特图。 |
|
||||
| sedgewick_maze_graph \ [create_using] ) | 返回一个带有循环的小迷宫。 |
|
||||
| tetrahedral_graph \ [create_using] ) | 返回3-正则柏拉图四面体图。 |
|
||||
|
||||
|
||||
## 3 对经典图形使用生成器
|
||||
|
||||
|
||||
| complete_graph n(n) [, create_using] ) | 返回完整图形 K_n 具有n个节点。 |
|
||||
|---|---|
|
||||
| complete_bipartite_graph (N1,N2) [, create_using] ) | 返回完整的二部图 K_{{n_1,n_2}} . |
|
||||
| barbell_graph (M1,M2) [, create_using] ) | 返回杠铃图:由路径连接的两个完整图。 |
|
||||
| lollipop_graph (m,n) [, create_using] ) | 返回棒棒糖图; K_m 连接到 P_n . |
|
||||
|
||||
|
||||
```py
|
||||
K_5 = nx.complete_graph(5)
|
||||
K_3_5 = nx.complete_bipartite_graph(3, 5)
|
||||
barbell = nx.barbell_graph(10, 10)
|
||||
lollipop = nx.lollipop_graph(10, 20)
|
||||
```
|
||||
|
||||
|
||||
## 4 使用随机图形生成器
|
||||
|
||||
|
||||
| erdos_renyi_graph (n,p) [, seed, directed] ) | 返回一个$G{n,p}$随机图,也称为Erdős-Rényi图或二项式图。 |
|
||||
|---|---|
|
||||
| watts_strogatz_graph (n,k,p) [, seed] ) | 返回Watts–Strogaz小世界图。 |
|
||||
| barabasi_albert_graph (n,m) [, seed] ) | 根据barab_si–albert优先连接模型返回随机图。 |
|
||||
| random_lobster \(N、P1、P2)[, seed] ) | 返回随机龙虾图。 |
|
||||
|
||||
|
||||
```py
|
||||
er = nx.erdos_renyi_graph(100, 0.15)
|
||||
ws = nx.watts_strogatz_graph(30, 3, 0.1)
|
||||
ba = nx.barabasi_albert_graph(100, 5)
|
||||
red = nx.random_lobster(100, 0.9, 0.9)
|
||||
```
|
||||
|
||||
使用常用的图形格式读取存储在文件中的图形,如边列表、邻接列表、gml、graphml、pickle、leda等。
|
||||
|
||||
```
|
||||
nx.write_gml(red, "path.to.file")
|
||||
mygraph = nx.read_gml("path.to.file")
|
||||
```
|
||||
有关图形格式的详细信息,请参见 读写图表 关于图形生成器函数,请参见 图形生成器
|
||||
30
Python/networkx/3 分析图形.md
Normal file
30
Python/networkx/3 分析图形.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# 分析图形
|
||||
|
||||
|
||||
|
||||
## 基础处理
|
||||
|
||||
分析图形的结构 G 可以使用各种图论函数进行分析,例如:
|
||||
|
||||
```py
|
||||
G = nx.Graph()
|
||||
G.add_edges_from([(1, 2), (1, 3)])
|
||||
G.add_node("spam") # adds node "spam"
|
||||
list(nx.connected_components(G))
|
||||
[{1, 2, 3}, {'spam'}]
|
||||
sorted(d for n, d in G.degree())
|
||||
[0, 1, 1, 2]
|
||||
nx.clustering(G)
|
||||
{1: 0, 2: 0, 3: 0, 'spam': 0}
|
||||
```
|
||||
|
||||
一些具有大输出的函数迭代(节点、值)2元组。这些很容易存储在 dict 结构,如果你愿意的话。
|
||||
|
||||
```py
|
||||
sp = dict(nx.all_pairs_shortest_path(G))
|
||||
sp[3]
|
||||
{3: [3], 1: [3, 1], 2: [3, 1, 2]}
|
||||
```
|
||||
|
||||
## 图算法
|
||||
|
||||
22
Python/networkx/4 绘制图形.md
Normal file
22
Python/networkx/4 绘制图形.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# 图形绘制
|
||||
|
||||
|
||||
networkx主要不是一个图形绘制包,而是一个带有matplotlib的基本绘图,以及一个使用开源graphviz软件包的接口。这些是 networkx.drawing 模块,如果可能,将导入。
|
||||
|
||||
首先导入Matplotlib的绘图接口(Pylab也可以工作)
|
||||
|
||||
```py
|
||||
import matplotlib.pyplot as plt
|
||||
```
|
||||
|
||||
测试是否导入 networkx.drawing 抽签成功 G 使用其中之一
|
||||
|
||||
```
|
||||
G = nx.petersen_graph()
|
||||
plt.subplot(121)
|
||||
<matplotlib.axes._subplots.AxesSubplot object at ...>
|
||||
nx.draw(G, with_labels=True, font_weight='bold')
|
||||
plt.subplot(122)
|
||||
<matplotlib.axes._subplots.AxesSubplot object at ...>
|
||||
nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')
|
||||
```
|
||||
77
Python/networkx/5 导入导出.md
Normal file
77
Python/networkx/5 导入导出.md
Normal file
@@ -0,0 +1,77 @@
|
||||
读写图表
|
||||
邻接表
|
||||
邻接表
|
||||
networkx.readwrite.adjlist.read_adjlist
|
||||
networkx.readwrite.adjlist.write_adjlist
|
||||
networkx.readwrite.adjlist.parse_adjlist
|
||||
networkx.readwrite.adjlist.generate_adjlist
|
||||
多行邻接列表
|
||||
多行相邻列表
|
||||
networkx.readwrite.multiline_adjlist.read_multiline_adjlist
|
||||
networkx.readwrite.multiline_adjlist.write_multiline_adjlist
|
||||
networkx.readwrite.multiline_adjlist.parse_multiline_adjlist
|
||||
networkx.readwrite.multiline_adjlist.generate_multiline_adjlist
|
||||
边缘列表
|
||||
边缘列表
|
||||
networkx.readwrite.edgelist.read_edgelist
|
||||
networkx.readwrite.edgelist.write_edgelist
|
||||
networkx.readwrite.edgelist.read_weighted_edgelist
|
||||
networkx.readwrite.edgelist.write_weighted_edgelist
|
||||
networkx.readwrite.edgelist.generate_edgelist
|
||||
networkx.readwrite.edgelist.parse_edgelist
|
||||
GEXF
|
||||
格式
|
||||
networkx.readwrite.gexf.read_gexf
|
||||
networkx.readwrite.gexf.write_gexf
|
||||
networkx.readwrite.gexf.generate_gexf
|
||||
networkx.readwrite.gexf.relabel_gexf_graph
|
||||
GML
|
||||
networkx.readwrite.gml.read_gml
|
||||
networkx.readwrite.gml.write_gml
|
||||
networkx.readwrite.gml.parse_gml
|
||||
networkx.readwrite.gml.generate_gml
|
||||
networkx.readwrite.gml.literal_destringizer
|
||||
networkx.readwrite.gml.literal_stringizer
|
||||
泡菜
|
||||
腌渍图
|
||||
networkx.readwrite.gpickle.read_gpickle
|
||||
networkx.readwrite.gpickle.write_gpickle
|
||||
图形ML
|
||||
图形ML
|
||||
networkx.readwrite.graphml.read_graphml
|
||||
networkx.readwrite.graphml.write_graphml
|
||||
networkx.readwrite.graphml.generate_graphml
|
||||
networkx.readwrite.graphml.parse_graphml
|
||||
JSON
|
||||
JSON数据
|
||||
networkx.readwrite.json_graph.node_link_data
|
||||
networkx.readwrite.json_graph.node_link_graph
|
||||
networkx.readwrite.json_graph.adjacency_data
|
||||
networkx.readwrite.json_graph.adjacency_graph
|
||||
networkx.readwrite.json_graph.cytoscape_data
|
||||
networkx.readwrite.json_graph.cytoscape_graph
|
||||
networkx.readwrite.json_graph.tree_data
|
||||
networkx.readwrite.json_graph.tree_graph
|
||||
networkx.readwrite.json_graph.jit_data
|
||||
networkx.readwrite.json_graph.jit_graph
|
||||
LEDA
|
||||
格式
|
||||
networkx.readwrite.leda.read_leda
|
||||
networkx.readwrite.leda.parse_leda
|
||||
YAML
|
||||
YAML
|
||||
networkx.readwrite.nx_yaml.read_yaml
|
||||
networkx.readwrite.nx_yaml.write_yaml
|
||||
闪光灯6
|
||||
图形6
|
||||
SARSE6
|
||||
帕吉克
|
||||
帕吉克
|
||||
networkx.readwrite.pajek.read_pajek
|
||||
networkx.readwrite.pajek.write_pajek
|
||||
networkx.readwrite.pajek.parse_pajek
|
||||
networkx.readwrite.pajek.generate_pajek
|
||||
地理信息系统
|
||||
整形器
|
||||
networkx.readwrite.nx_shp.read_shp
|
||||
networkx.readwrite.nx_shp.write_shp
|
||||
217
pytorch/PyG/1 数据.md
Normal file
217
pytorch/PyG/1 数据.md
Normal file
@@ -0,0 +1,217 @@
|
||||
|
||||
## 1 图数据结构
|
||||
|
||||
图说起来也很简单,就是两个核心点,一个是图节点(nodes/vertics),一个是边(edges/links)表示节点之间的连接关系
|
||||
|
||||
总体而言,图可以是不规整的(irregular),对比而言,平时我们看到的图片都是规整的(regular),可以表示成矩阵或者向量。问题在于设计数据结构如何储存图,一般有两种方案
|
||||
|
||||
### 矩阵表示
|
||||
|
||||
又细分成两种
|
||||
|
||||
1. 用邻接矩阵(adjacency matrix),度矩阵(degree matrix), 拉普拉斯矩阵(Laplacian matrix)去表示, 衍生出各种对拉普拉斯矩阵的操作,比如图傅里叶变换(graph fourier transform), 也有稀疏邻接矩阵
|
||||
|
||||
2. 用关联矩阵(incidence matrix)表示,行表示节点,列表示边, 和这个相关的例如:超图(hypergraph)
|
||||
|
||||
这(两)种方式的缺点在于使用内存大, 矩阵维度和节点数目N挂钩。但是图的连接常常是稀疏的(sparse),也就是邻接矩阵中很多元素都是0(两个node没有连接关系),这些0元素会占据大量存储空间,使效率很低下。尤其是大型网络图,都不会把图完整的表示成一个矩阵。
|
||||
|
||||
|
||||
|
||||
### 邻接表
|
||||
邻接表(Adjacency list),也是数据领域常用的存储图方式,比如将边表示成节点对,成为一个2*N_edges的matrix,第一行表示source node, 第二行表示target node。这样的好处在于可以只储存有边存在的,对稀疏结构友好。总体而言,如果图是dense的,可以考虑矩阵表示,如果是稀疏的,最好使用稀疏邻接矩阵或邻接表
|
||||
|
||||
|
||||
|
||||
## 2 数据Data
|
||||
|
||||
|
||||
### Data的内容
|
||||
pytorch Geometric Data使用邻接表去表示图,同时也表示了node特征x, 边属性edge_attr等, 需要注意的是, Data只表示一张图(single graph)
|
||||
|
||||
|
||||
```py
|
||||
Data(x=None, edge_index=None, edge_attr=None, y=None)
|
||||
```
|
||||
|
||||
一个Graph本质是torch_geometric.data.Data的实例,它包括以下几个常见对象(属性,attributes):
|
||||
|
||||
* data.x:节点的特征矩阵,形状为[num_nodes,num_node_features]
|
||||
* data.edge_index:图的边索引,用COO稀疏矩阵格式保存,形状为[2,num_edgs],数据类型为torch.long;
|
||||
* data.edge_attr:边的特征矩阵,形状为[num_edges,num_edge_features];
|
||||
* data.y:计算损失所需的目标数据,target,针对训练的目标可能有不同的形状,比如节点级别的形状为[num_nodes,*],或者图级别的形状为[1,*];
|
||||
|
||||
```py
|
||||
import torch
|
||||
from torch_geometric.data import Data
|
||||
|
||||
edge_index = torch.tensor([[0, 1, 1, 2],
|
||||
[1, 0, 2, 1]], dtype=torch.long)
|
||||
x = torch.tensor([[-1], [0], [1]], dtype=torch.float)
|
||||
|
||||
data = Data(x=x, edge_index=edge_index)
|
||||
print(data)
|
||||
|
||||
# 将数据集迁移到GPU上
|
||||
device=torch.device("cuda")
|
||||
data=data.to(device)
|
||||
```
|
||||
|
||||
|
||||
* Data的其他属性
|
||||
```
|
||||
data.num_nodes
|
||||
data.num_edges
|
||||
data.num_node_features
|
||||
data.has_isolated_nodes()
|
||||
data.has_self_loops()
|
||||
data.is_directed()
|
||||
```
|
||||
|
||||
## 3 数据集Dataset
|
||||
|
||||
### Dataset实例
|
||||
|
||||
我们可以看到数据集中的第一个图包含 37 个节点,每个节点有 3 个特征。 有 168/2 = 84 条无向边,并且该图恰好分配给一个类。 此外,数据对象正好持有一个图级别目标。
|
||||
```py
|
||||
from torch_geometric.datasets import TUDataset
|
||||
|
||||
dataset = TUDataset(root='/home/ykl/ENZYMES', name='ENZYMES')
|
||||
|
||||
print(len(dataset))
|
||||
print(dataset.num_classes)
|
||||
|
||||
|
||||
print(dataset.num_node_labels)
|
||||
print(dataset.num_node_features)
|
||||
print(dataset.num_node_attributes)
|
||||
|
||||
print(dataset.num_edge_labels)
|
||||
print(dataset.num_edge_features)
|
||||
print(dataset.num_edge_attributes)
|
||||
|
||||
|
||||
print(dataset.num_features)
|
||||
|
||||
```
|
||||
|
||||
* 打乱并划分数据集
|
||||
|
||||
```py
|
||||
# 使用切片、长或布尔张量来分割数据集。
|
||||
划分测试集和训练集
|
||||
|
||||
torch.manual_seed(12345)
|
||||
dataset = dataset.shuffle()
|
||||
|
||||
train_dataset = dataset[:150]
|
||||
test_dataset = dataset[150:]
|
||||
```
|
||||
### Dataset中的Data对象
|
||||
Data对象为每个节点保存了一个标签,以及附加的节点级属性:train_mask,val_mask,test_mask,其中:
|
||||
|
||||
* train_mask:表示针对哪些节点进行训练(140个节点);
|
||||
* val_mask:表示针对哪些节点进行验证(500个节点);
|
||||
* test_mask:表示针对哪些节点进行测试(1000个节点)
|
||||
|
||||
```
|
||||
data=dataset[0]
|
||||
|
||||
print(data.is_undirected()) # True
|
||||
print(data.num_nodes) # 2708
|
||||
print(data.train_mask.sum().item()) # 140
|
||||
print(data.val_mask.sum().item()) # 500
|
||||
print(data.test_mask.sum().item()) # 1000
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 4 数据加载Dataloader
|
||||
神经网络通常以批量方式进行训练。PyG 通过创建稀疏块对角邻接矩阵(由 定义edge_index)并在节点维度中连接特征和目标矩阵来实现小批量的并行化。这种组合允许在一批示例中使用不同数量的节点和边
|
||||
|
||||
$$
|
||||
\begin{split}\mathbf{A} = \begin{bmatrix} \mathbf{A}_1 & & \\ & \ddots & \\ & & \mathbf{A}_n \end{bmatrix}, \qquad \mathbf {X} = \begin{bmatrix} \mathbf{X}_1 \\ \vdots \\ \mathbf{X}_n \end{bmatrix}, \qquad \mathbf{Y} = \begin{bmatrix} \mathbf{Y }_1 \\ \vdots \\ \mathbf{Y}_n \end{bmatrix}\end{split}
|
||||
$$
|
||||
|
||||
```py
|
||||
from torch_geometric.datasets import TUDataset
|
||||
from torch_geometric.data import DataLoader
|
||||
|
||||
dataset=TUDataset(root='/home/ykl/ENZYMES',name='ENZYMES')
|
||||
loader=DataLoader(dataset,batch_size=32,shuffle=True)
|
||||
|
||||
|
||||
for batch in loader:
|
||||
print(batch.num_graphs) # 32
|
||||
```
|
||||
|
||||
|
||||
## 5 数据转换
|
||||
|
||||
|
||||
|
||||
|
||||
### 自定义Dataset
|
||||
InMemoryDataset 中有下列四个函数需要我们实现:
|
||||
|
||||
|
||||
* raw_file_names()
|
||||
返回一个包含所有未处理过的数据文件的文件名的列表。起始也可以返回一个空列表,然后在后面要说的 process() 函数里再定义。
|
||||
|
||||
* processed_file_names()
|
||||
返回一个包含所有处理过的数据文件的文件名的列表。
|
||||
|
||||
* download()
|
||||
如果在数据加载前需要先下载,则在这里定义下载过程,下载到 self.raw_dir 中定义的文件夹位置。如果不需要下载,返回 pass 即可。
|
||||
|
||||
* process()
|
||||
这是最重要的一个函数,我们需要在这个函数里把数据处理成一个 Data 对象。
|
||||
|
||||
```py
|
||||
import torch
|
||||
from torch_geometric.data import InMemoryDataset
|
||||
from tqdm import tqdm
|
||||
|
||||
class YooChooseBinaryDataset(InMemoryDataset):
|
||||
def __init__(self, root, transform=None, pre_transform=None):
|
||||
super(YooChooseBinaryDataset, self).__init__(root, transform, pre_transform)
|
||||
self.data, self.slices = torch.load(self.processed_paths[0])
|
||||
|
||||
@property
|
||||
def raw_file_names(self):
|
||||
return []
|
||||
@property
|
||||
def processed_file_names(self):
|
||||
return ['../input/yoochoose_click_binary_1M_sess.dataset']
|
||||
|
||||
def download(self):
|
||||
pass
|
||||
|
||||
def process(self):
|
||||
|
||||
data_list = []
|
||||
|
||||
# process by session_id
|
||||
grouped = df.groupby('session_id')
|
||||
for session_id, group in tqdm(grouped):
|
||||
sess_item_id = LabelEncoder().fit_transform(group.item_id)
|
||||
group = group.reset_index(drop=True)
|
||||
group['sess_item_id'] = sess_item_id
|
||||
node_features = group.loc[group.session_id==session_id,['sess_item_id','item_id']].sort_values('sess_item_id').item_id.drop_duplicates().values
|
||||
|
||||
node_features = torch.LongTensor(node_features).unsqueeze(1)
|
||||
target_nodes = group.sess_item_id.values[1:]
|
||||
source_nodes = group.sess_item_id.values[:-1]
|
||||
|
||||
edge_index = torch.tensor([source_nodes, target_nodes], dtype=torch.long)
|
||||
x = node_features
|
||||
|
||||
y = torch.FloatTensor([group.label.values[0]])
|
||||
|
||||
data = Data(x=x, edge_index=edge_index, y=y)
|
||||
data_list.append(data)
|
||||
|
||||
data, slices = self.collate(data_list)
|
||||
torch.save((data, slices), self.processed_paths[0])
|
||||
```
|
||||
|
||||
95
pytorch/PyG/2 模型.md
Normal file
95
pytorch/PyG/2 模型.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# 消息传递网络
|
||||
|
||||
|
||||
## 1 原理
|
||||
|
||||
Message Passing 是图网络中学习 node embedding 的重要方法。
|
||||
|
||||
### 公式
|
||||
$$
|
||||
\mathbf{x}_i^{(k)} = \gamma^{(k)} \left( \mathbf{x}_i^{(k-1)}, \square_{j \in \mathcal{N} (i)} \, \phi^{(k)}\left(\mathbf{x}_i^{(k-1)}, \mathbf{x}_j^{(k-1)},\mathbf{ e}_{j,i}\right) \right),
|
||||
$$
|
||||
|
||||
x 表示表格节点的 embedding,e 表示边的特征,ϕ 表示 message 函数,□ 表示聚合 aggregation 函数,γ 表示 update 函数。上标表示层的 index,比如说,当 k = 1 时,x 则表示所有输入网络的图结构的数据。
|
||||
|
||||
|
||||
### 函数
|
||||
|
||||
* propagate(edge_index, size=None, **kwargs)
|
||||
这个函数最终会调用 message 和 update 函数。
|
||||
* message(**kwargs)
|
||||
这个函数定义了对于每个节点对 (xi,xj),怎样生成信息(message)。
|
||||
|
||||
* update(aggr_out, **kwargs)
|
||||
这个函数利用聚合好的信息(message)更新每个节点的 embedding。
|
||||
|
||||
### 传播消息
|
||||
```
|
||||
torch_geometric.nn.MessagePassing.propagate(edge_index, size=None, **kwargs)
|
||||
```
|
||||
* 初始化时调用这个函数开始传播消息。输入边的索引和所有其他的用于构造消息和更新节点嵌入的数据。值得注意的是,这个propagate()方法不仅可以在形状为 [N, N] 的对称邻接矩阵中交换消息,还可以在一般的稀疏分配矩阵中交换消息,例如二分图,形状为[N, M]的话只需要 size=(N, M) 作为一个额外的参数就可以。如果设置为None,那么分配的矩阵会被假设为对称的。对于具有两组独立节点和索引的二分图,并且每组保存自己的信息,这种拆分可以通过在传递过程中将信息作为一个元组来标记。例如 x=(x_row, x_col),以此表明不同集合中的节点关系。
|
||||
|
||||
### 创建消息
|
||||
|
||||
```
|
||||
torch_geometric.nn.MessagePassing.message()
|
||||
```
|
||||
* 以函数的方式构造消息,如果 flow="source_to_target",那么对每条边做此操作,即将消息从节点传播到节点;如果 flow="target_to_source",那么对每条边做此操作,即将消息从节点传播到节点。任何用于构造消息的输入都可以作为参数传递给 propagate() 函数。另外,通过将_i或者_j加在变量名后面可以将特征映射到相应的节点和,例如 x_i 和 x_j。
|
||||
|
||||
|
||||
|
||||
### 更新表示
|
||||
```
|
||||
torch_geometric.nn.MessagePassing.update()
|
||||
```
|
||||
|
||||
* 以函数 的方式对每一个节点 进行更新节点嵌入的操作。将聚合操作后的输出结果作为第一个参数,任何需要在初始化时传递给 propagate() 函数的参数作为输入。
|
||||
|
||||
MessagePassing 类是实现各种图神经网络模型的基础。从一个图神经层到另一个图神经进行的消息传递操作可以分为三个计算层次:
|
||||
|
||||
* 第一层计算函数操作,这属于创建消息的过程。输入为上一层的节点特征和边关系,可以指定消息的流向。(边关系以索引的形式进行查找)利用了图结构数据的边关系。
|
||||
|
||||
* 第二层计算函数操作,这属于邻域聚合的过程。经过第一层的操作,已经按边关系建立了节点间的消息,表示节点的(一阶)邻居节点,即限定了消息只在指定节点的邻域范围内传递。的 add,mean 和 max 都不会因为邻居节点的顺序排列问题而产生不同的结果。利用了图结构数据中的结构信息。
|
||||
|
||||
* 第三层计算函数操作,这属于更新特征的过程。经过邻域上的消息传递之后,将邻域上的信息聚合到目标节点,然后更新节点的特征,作为这一层的输出。
|
||||
### SAGE示例
|
||||
|
||||
```py
|
||||
class SAGEConv(MessagePassing):
|
||||
def __init__(self, in_channels, out_channels):
|
||||
super(SAGEConv, self).__init__(aggr='max')
|
||||
self.lin = torch.nn.Linear(in_channels, out_channels)
|
||||
self.act = torch.nn.ReLU()
|
||||
|
||||
def forward(self, x, edge_index):
|
||||
# x has shape [N, in_channels]
|
||||
# edge_index has shape [2, E]
|
||||
|
||||
|
||||
edge_index, _ = remove_self_loops(edge_index)
|
||||
edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))
|
||||
|
||||
|
||||
return self.propagate(edge_index, size=(x.size(0), x.size(0)), x=x)
|
||||
|
||||
def message(self, x_j):
|
||||
# x_j has shape [E, in_channels]
|
||||
|
||||
x_j = self.lin(x_j)
|
||||
x_j = self.act(x_j)
|
||||
|
||||
return x_j
|
||||
|
||||
def update(self, aggr_out, x):
|
||||
# aggr_out has shape [N, out_channels]
|
||||
|
||||
|
||||
new_embedding = torch.cat([aggr_out, x], dim=1)
|
||||
|
||||
new_embedding = self.update_lin(new_embedding)
|
||||
new_embedding = self.update_act(new_embedding)
|
||||
|
||||
return new_embedding
|
||||
```
|
||||
|
||||
|
||||
429
pytorch/PyG/3 训练.md
Normal file
429
pytorch/PyG/3 训练.md
Normal file
@@ -0,0 +1,429 @@
|
||||
## 1 图分类示例
|
||||
|
||||
### 创建数据集
|
||||
```
|
||||
|
||||
import torch
|
||||
from torch_geometric.datasets import TUDataset
|
||||
|
||||
dataset = TUDataset('/home/ykl/TUDataset', name = 'MUTAG')
|
||||
|
||||
print()
|
||||
print(f'Dataset: {dataset}:')
|
||||
print('====================')
|
||||
print(f'Number of graphs: {len(dataset)}')
|
||||
print(f'Number of features: {dataset.num_features}')
|
||||
print(f'Number of classes: {dataset.num_classes}')
|
||||
|
||||
data = dataset[0] # Get the first graph object.
|
||||
|
||||
print()
|
||||
print(data)
|
||||
print('=============================================================')
|
||||
|
||||
# Gather some statistics about the first graph.
|
||||
print(f'Number of nodes: {data.num_nodes}')
|
||||
print(f'Number of edges: {data.num_edges}')
|
||||
print(f'Average node degree: {data.num_edges / data.num_nodes:.2f}')
|
||||
print(f'Has isolated nodes: {data.has_isolated_nodes()}')
|
||||
print(f'Has self-loops: {data.has_self_loops()}')
|
||||
print(f'Is undirected: {data.is_undirected()}')
|
||||
```
|
||||
|
||||
### 划分测试集和训练集
|
||||
```py
|
||||
torch.manual_seed(12345)
|
||||
dataset = dataset.shuffle()
|
||||
|
||||
train_dataset = dataset[:150]
|
||||
test_dataset = dataset[150:]
|
||||
|
||||
print(f'Number of training graphs: {len(train_dataset)}')
|
||||
print(f'Number of test graphs: {len(test_dataset)}')
|
||||
```
|
||||
|
||||
### 加载数据集
|
||||
```py
|
||||
from torch_geometric.loader import DataLoader
|
||||
|
||||
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
|
||||
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
|
||||
|
||||
for step, data in enumerate(train_loader):
|
||||
print(f'Step {step + 1}:')
|
||||
print('=======')
|
||||
print(f'Number of graphs in the current batch: {data.num_graphs}')
|
||||
print(data)
|
||||
print()
|
||||
```
|
||||
|
||||
### 创建模型
|
||||
```py
|
||||
from torch.nn import Linear
|
||||
import torch.nn.functional as F
|
||||
from torch_geometric.nn import GCNConv
|
||||
from torch_geometric.nn import global_mean_pool
|
||||
|
||||
class GCN(torch.nn.Module):
|
||||
def __init__(self, hidden_channels):
|
||||
super(GCN, self).__init__()
|
||||
torch.manual_seed(12345)
|
||||
self.conv1 = GCNConv(dataset.num_node_features, hidden_channels)
|
||||
self.conv2 = GCNConv(hidden_channels, hidden_channels)
|
||||
self.conv3 = GCNConv(hidden_channels, hidden_channels)
|
||||
self.lin = Linear(hidden_channels, dataset.num_classes)
|
||||
|
||||
def forward(self, x, edge_index, batch):
|
||||
# 1. 获得节点嵌入
|
||||
x = self.conv1(x, edge_index)
|
||||
x = x.relu()
|
||||
x = self.conv2(x, edge_index)
|
||||
x = x.relu()
|
||||
x = self.conv3(x, edge_index)
|
||||
|
||||
# 2. Readout layer
|
||||
x = global_mean_pool(x, batch) # [batch_size, hidden_channels]
|
||||
|
||||
# 3. 分类器
|
||||
x = F.dropout(x, p=0.5, training=self.training)
|
||||
x = self.lin(x)
|
||||
|
||||
return x
|
||||
|
||||
model = GCN(hidden_channels=64)
|
||||
print(model)
|
||||
```
|
||||
### 开始训练
|
||||
```py
|
||||
model = GCN(hidden_channels=64)
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
|
||||
criterion = torch.nn.CrossEntropyLoss()
|
||||
|
||||
def train():
|
||||
model.train()
|
||||
|
||||
for data in train_loader:
|
||||
optimizer.zero_grad()
|
||||
|
||||
out = model(data.x, data.edge_index, data.batch)
|
||||
loss = criterion(out, data.y)
|
||||
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
def test(loader):
|
||||
model.eval()
|
||||
|
||||
correct = 0
|
||||
for data in loader: # 批遍历测试集数据集。
|
||||
out = model(data.x, data.edge_index, data.batch) # 一次前向传播
|
||||
pred = out.argmax(dim=1) # 使用概率最高的类别
|
||||
correct += int((pred == data.y).sum()) # 检查真实标签
|
||||
return correct / len(loader.dataset)
|
||||
|
||||
for epoch in range(1, 121):
|
||||
train()
|
||||
train_acc = test(train_loader)
|
||||
test_acc = test(test_loader)
|
||||
print(f'Epoch: {epoch:03d}, Train Acc: {train_acc:.4f}, Test Acc: {test_acc:.4f}')
|
||||
```
|
||||
|
||||
|
||||
## 2 图节点分类实例
|
||||
|
||||
|
||||
|
||||
1. 增加自连接到邻接矩阵,即邻接矩阵的对角线元素为1,得到[公式];
|
||||
2. 对节点的特征矩阵进行线性变换,将特征变换到维度D;
|
||||
3. 使用函数 [公式] 对节点特征进行规范化, 也就是乘以参数矩阵 [公式] 再乘以归一化的拉普拉斯矩阵;
|
||||
4. 对邻居节点特征进行聚合操作,这里是求和;
|
||||
5. 返回新的节点embedding
|
||||
|
||||
|
||||
将卷积操作推广到不规则数据通常表示为邻域聚合(neighborhood aggregation)或消息传递(message passing)。在 PyTorch Geometric 中将各种图神经网络中的邻域聚合方法统一到一种消息传递网络的架构中。
|
||||
|
||||
```py
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch_geometric.nn import GCNConv
|
||||
|
||||
#数据集加载
|
||||
from torch_geometric.datasets import Planetoid
|
||||
dataset = Planetoid(root='/home/ykl/Cora', name='Cora')
|
||||
|
||||
#网络定义
|
||||
class Net(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(Net, self).__init__()
|
||||
self.conv1 = GCNConv(dataset.num_node_features, 16)
|
||||
self.conv2 = GCNConv(16, dataset.num_classes)
|
||||
|
||||
def forward(self, data):
|
||||
x, edge_index = data.x, data.edge_index
|
||||
|
||||
x = self.conv1(x, edge_index)
|
||||
x = F.relu(x)
|
||||
x = F.dropout(x, training=self.training)
|
||||
x = self.conv2(x, edge_index)
|
||||
|
||||
return F.log_softmax(x, dim=1)
|
||||
|
||||
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
||||
model = Net().to(device)
|
||||
data = dataset[0].to(device)
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
|
||||
|
||||
#网络训练
|
||||
model.train()
|
||||
for epoch in range(200):
|
||||
optimizer.zero_grad()
|
||||
out = model(data)
|
||||
loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
#测试
|
||||
model.eval()
|
||||
_, pred = model(data).max(dim=1)
|
||||
correct = float(pred[data.test_mask].eq(data.y[data.test_mask]).sum().item())
|
||||
acc = correct / data.test_mask.sum().item()
|
||||
print('Accuracy: {:.4f}'.format(acc))
|
||||
```
|
||||
|
||||
|
||||
|
||||
## 3 自己创建数据集分类的实例
|
||||
|
||||
### 获取数据集
|
||||
RecSys Challenge 2015 是一个挑战赛,主要目的是创建一个 session-based recommender system。主要任务有两个:
|
||||
|
||||
* 预测经过一系列的点击后,是否会产生购买行为。
|
||||
* 预测购买的商品。
|
||||
|
||||
|
||||

|
||||
|
||||
|
||||
### 数据预处理
|
||||
|
||||
|
||||
下载好数据后,我们先进行一些预处理:
|
||||
```py
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
|
||||
df = pd.read_csv('../input/yoochoose-click.dat', header=None)
|
||||
df.columns=['session_id','timestamp','item_id','category']
|
||||
|
||||
buy_df = pd.read_csv('../input/yoochoose-buys.dat', header=None)
|
||||
buy_df.columns=['session_id','timestamp','item_id','price','quantity']
|
||||
|
||||
item_encoder = LabelEncoder()
|
||||
df['item_id'] = item_encoder.fit_transform(df.item_id)
|
||||
df.head()
|
||||
```
|
||||
|
||||
因为数据太多,我们随机进行取样以方便讲解:
|
||||
|
||||
```
|
||||
#randomly sample a couple of them
|
||||
sampled_session_id = np.random.choice(df.session_id.unique(), 1000000, replace=False)
|
||||
df = df.loc[df.session_id.isin(sampled_session_id)]
|
||||
df.nunique()
|
||||
```
|
||||
|
||||
获取标签,即对于某个特定的 session,是否产生了购买行为,我们只需要检查文件 yoochoose-clicks.dat 中的 session_id 是否在文件 yoochoose-buys.dat 中出现即可:
|
||||
```py
|
||||
df['label'] = df.session_id.isin(buy_df.session_id)
|
||||
df.head()
|
||||
```
|
||||
|
||||
|
||||
### 创建 Dataset
|
||||
|
||||
|
||||
这里我们将预处理过的数据创建成为 Dataset 对象。对于每个 session,里面的每个商品(item)看作一个节点,因此每个 session 里所有的商品组成一个图。
|
||||
|
||||
我们将数据集按照 session_id 进行分组,分组过程中 item_id 也要被重新编码,因为对于每个图,每个节点的 index 应该从 0 开始
|
||||
|
||||
```py
|
||||
import torch
|
||||
from torch_geometric.data import InMemoryDataset
|
||||
from tqdm import tqdm
|
||||
|
||||
class YooChooseBinaryDataset(InMemoryDataset):
|
||||
def __init__(self, root, transform=None, pre_transform=None):
|
||||
super(YooChooseBinaryDataset, self).__init__(root, transform, pre_transform)
|
||||
self.data, self.slices = torch.load(self.processed_paths[0])
|
||||
|
||||
@property
|
||||
def raw_file_names(self):
|
||||
return []
|
||||
@property
|
||||
def processed_file_names(self):
|
||||
return ['../input/yoochoose_click_binary_1M_sess.dataset']
|
||||
|
||||
def download(self):
|
||||
pass
|
||||
|
||||
def process(self):
|
||||
|
||||
data_list = []
|
||||
|
||||
# process by session_id
|
||||
grouped = df.groupby('session_id')
|
||||
for session_id, group in tqdm(grouped):
|
||||
sess_item_id = LabelEncoder().fit_transform(group.item_id)
|
||||
group = group.reset_index(drop=True)
|
||||
group['sess_item_id'] = sess_item_id
|
||||
node_features = group.loc[group.session_id==session_id,['sess_item_id','item_id']].sort_values('sess_item_id').item_id.drop_duplicates().values
|
||||
|
||||
node_features = torch.LongTensor(node_features).unsqueeze(1)
|
||||
target_nodes = group.sess_item_id.values[1:]
|
||||
source_nodes = group.sess_item_id.values[:-1]
|
||||
|
||||
edge_index = torch.tensor([source_nodes, target_nodes], dtype=torch.long)
|
||||
x = node_features
|
||||
|
||||
y = torch.FloatTensor([group.label.values[0]])
|
||||
|
||||
data = Data(x=x, edge_index=edge_index, y=y)
|
||||
data_list.append(data)
|
||||
|
||||
data, slices = self.collate(data_list)
|
||||
torch.save((data, slices), self.processed_paths[0])
|
||||
```
|
||||
|
||||
然后我们对数据集进行随机排序,分成 training, validation 和 testing 三个子数据集:
|
||||
```py
|
||||
dataset = dataset.shuffle()
|
||||
train_dataset = dataset[:800000]
|
||||
val_dataset = dataset[800000:900000]
|
||||
test_dataset = dataset[900000:]
|
||||
len(train_dataset), len(val_dataset), len(test_dataset)
|
||||
```
|
||||
|
||||
### 定义模型
|
||||
|
||||
```py
|
||||
embed_dim = 128
|
||||
from torch_geometric.nn import TopKPooling
|
||||
from torch_geometric.nn import global_mean_pool as gap, global_max_pool as gmp
|
||||
import torch.nn.functional as F
|
||||
class Net(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(Net, self).__init__()
|
||||
|
||||
self.conv1 = SAGEConv(embed_dim, 128)
|
||||
self.pool1 = TopKPooling(128, ratio=0.8)
|
||||
self.conv2 = SAGEConv(128, 128)
|
||||
self.pool2 = TopKPooling(128, ratio=0.8)
|
||||
self.conv3 = SAGEConv(128, 128)
|
||||
self.pool3 = TopKPooling(128, ratio=0.8)
|
||||
self.item_embedding = torch.nn.Embedding(num_embeddings=df.item_id.max() +1, embedding_dim=embed_dim)
|
||||
self.lin1 = torch.nn.Linear(256, 128)
|
||||
self.lin2 = torch.nn.Linear(128, 64)
|
||||
self.lin3 = torch.nn.Linear(64, 1)
|
||||
self.bn1 = torch.nn.BatchNorm1d(128)
|
||||
self.bn2 = torch.nn.BatchNorm1d(64)
|
||||
self.act1 = torch.nn.ReLU()
|
||||
self.act2 = torch.nn.ReLU()
|
||||
|
||||
def forward(self, data):
|
||||
x, edge_index, batch = data.x, data.edge_index, data.batch
|
||||
x = self.item_embedding(x)
|
||||
x = x.squeeze(1)
|
||||
|
||||
x = F.relu(self.conv1(x, edge_index))
|
||||
|
||||
x, edge_index, _, batch, _ = self.pool1(x, edge_index, None, batch)
|
||||
x1 = torch.cat([gmp(x, batch), gap(x, batch)], dim=1)
|
||||
|
||||
x = F.relu(self.conv2(x, edge_index))
|
||||
|
||||
x, edge_index, _, batch, _ = self.pool2(x, edge_index, None, batch)
|
||||
x2 = torch.cat([gmp(x, batch), gap(x, batch)], dim=1)
|
||||
|
||||
x = F.relu(self.conv3(x, edge_index))
|
||||
|
||||
x, edge_index, _, batch, _ = self.pool3(x, edge_index, None, batch)
|
||||
x3 = torch.cat([gmp(x, batch), gap(x, batch)], dim=1)
|
||||
|
||||
x = x1 + x2 + x3
|
||||
|
||||
x = self.lin1(x)
|
||||
x = self.act1(x)
|
||||
x = self.lin2(x)
|
||||
x = self.act2(x)
|
||||
x = F.dropout(x, p=0.5, training=self.training)
|
||||
|
||||
x = torch.sigmoid(self.lin3(x)).squeeze(1)
|
||||
|
||||
return x
|
||||
```
|
||||
|
||||
|
||||
### 训练模型
|
||||
|
||||
训练
|
||||
训练过程中,我们使用 Adam 优化器,学习率 0.005,损失函数是 BCE:
|
||||
```py
|
||||
def train():
|
||||
model.train()
|
||||
|
||||
loss_all = 0
|
||||
for data in train_loader:
|
||||
data = data.to(device)
|
||||
optimizer.zero_grad()
|
||||
output = model(data)
|
||||
label = data.y.to(device)
|
||||
loss = crit(output, label)
|
||||
loss.backward()
|
||||
loss_all += data.num_graphs * loss.item()
|
||||
optimizer.step()
|
||||
return loss_all / len(train_dataset)
|
||||
|
||||
device = torch.device('cuda')
|
||||
model = Net().to(device)
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=0.005)
|
||||
crit = torch.nn.BCELoss()
|
||||
train_loader = DataLoader(train_dataset, batch_size=batch_size)
|
||||
for epoch in range(num_epochs):
|
||||
train()
|
||||
```
|
||||
|
||||
|
||||
### 验证模型
|
||||
|
||||
Validation
|
||||
这个数据集非常的不平衡,因为大多数的 session 里没有购买行为。也就是说,如果一个模型将所有的结果都预测为 false,也能达到 90% 的准确率。因此,这里我们不使用 accuracy 作为评测标准,而是使用 Area Under Curve (AUC):
|
||||
```py
|
||||
def evaluate(loader):
|
||||
model.eval()
|
||||
|
||||
predictions = []
|
||||
labels = []
|
||||
|
||||
with torch.no_grad():
|
||||
for data in loader:
|
||||
|
||||
data = data.to(device)
|
||||
pred = model(data).detach().cpu().numpy()
|
||||
|
||||
label = data.y.detach().cpu().numpy()
|
||||
predictions.append(pred)
|
||||
labels.append(label)
|
||||
```
|
||||
|
||||
|
||||
|
||||
### 训练结果
|
||||
|
||||
```
|
||||
for epoch in range(1):
|
||||
loss = train()
|
||||
train_acc = evaluate(train_loader)
|
||||
val_acc = evaluate(val_loader)
|
||||
test_acc = evaluate(test_loader)
|
||||
print('Epoch: {:03d}, Loss: {:.5f}, Train Auc: {:.5f}, Val Auc: {:.5f}, Test Auc: {:.5f}'.
|
||||
format(epoch, loss, train_acc, val_acc, test_acc))
|
||||
```
|
||||
BIN
pytorch/PyG/image/2022-02-22-15-04-25.png
Normal file
BIN
pytorch/PyG/image/2022-02-22-15-04-25.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
@@ -10,16 +10,16 @@
|
||||
|
||||
1. 获取数据集
|
||||
2. 数据预处理
|
||||
3. 训练模型
|
||||
1. 创建模型:torch.nn.Model.__init__定义具有一些可学习参数(或权重)的神经网络
|
||||
2. 训练算法:
|
||||
1. 正向传播:torch.nn.Model.forward通过网络处理输入,进行正向传播
|
||||
2. 计算损失:torch.nn.loss输出正确的距离有多远
|
||||
3. 反向传播:torch.tensor.backward将梯度传播回网络参数
|
||||
4. 更新权重:troch.optim通常使用简单的更新规则来更新网络的权重:weight = weight - learning_rate * gradient
|
||||
5. 迭代循环:重复以上步骤直到(精确度满足要求 或者 迭代次数到达上限)
|
||||
4. 验证模型
|
||||
5. 使用模型
|
||||
3. 创建模型
|
||||
1. 定义模型:torch.nn.Model.__init__定义具有一些可学习参数(或权重)的神经网络
|
||||
2. 定义损失函数、训练算法、验证方法
|
||||
4. 训练模型
|
||||
1. 正向传播:torch.nn.Model.forward通过网络处理输入,进行正向传播
|
||||
2. 计算损失:torch.nn.loss输出正确的距离有多远
|
||||
3. 反向传播:torch.tensor.backward将梯度传播回网络参数
|
||||
4. 更新权重:troch.optim通常使用简单的更新规则来更新网络的权重:weight = weight - learning_rate * gradient
|
||||
5. 迭代循环:重复以上步骤直到(精确度满足要求 或者 迭代次数到达上限)
|
||||
5. 验证模型
|
||||
|
||||
|
||||
## 术语
|
||||
|
||||
10
工作日志/2022年2月16日-今日计划.md
Normal file
10
工作日志/2022年2月16日-今日计划.md
Normal file
@@ -0,0 +1,10 @@
|
||||
## 任务
|
||||
|
||||
1. 完成神经网络的二次设计。加入嵌入层。
|
||||
2. 完成图特征的提取和简化工作
|
||||
|
||||
|
||||
## 收获
|
||||
> 距离上次离开,正好二十天,浪费了大量时间吧。本来可以初七就返回学校的。本来可以晚点回家的。站在事后人的角度来说应该有很多时间。我现在很紧张很焦虑。需要通过一些手段,来让自己快速恢复到之前的状态。在完成这个月的计划之前,尽量不要休息。开始吧。工作的流程和事件安排,还是主要在毕业设计内部进行,这里只是用来复述一下之前的工作安排。记录其中的工作安排。进行双向完成的方案。tmd这个月只有28天,到月末都不到两周了,我是服了。所以这一周必须完成实验,下一周必须完成系统。
|
||||
>
|
||||
>
|
||||
Reference in New Issue
Block a user