当前位置:网站首页>Introduction of some functions or methods in DGL Library
Introduction of some functions or methods in DGL Library
2022-07-24 08:01:00 【Icy Hunter】
List of articles
Preface
DGL There are many built-in functions and methods in the Library , It still needs to be recorded , In order to better grasp DGL.
AddReverse()
For isomorphic graphs and heterogeneous graphs, we can create the opposite edge of the graph ( Take the heterogeneous graph as an example ).
dgl.transforms.AddReverse(copy_edata=False, sym_new_etype=False)
copy_edata=True Then copy the characteristics of the edge
sym_new_etype=True For heterogeneous graphs , Nodes of the same type also create reverse edges
import dgl
import torch as th
g = dgl.heterograph({
('user', 'follows', 'user') : ([0, 1], [1, 2]),
('user', 'plays', 'game') : ([0], [1]),
('store', 'sells', 'game') :([0], [2])})
g.edges["follows"].data["w"] = th.ones(2, 2)
g.edges["plays"].data["w"] = th.ones(1, 2) + 1
g.edges["sells"].data["w"] = th.ones(1, 2) + 2
print(g)
print(g.edges["sells"].data["w"])
gg = dgl.AddReverse(copy_edata=True, sym_new_etype=True)(g)
print("="*10)
print(gg)
print(gg.edges["rev_sells"].data["w"])
Output is as follows :
so user Nodes between have also appeared rev_follows Relationship ,sym_new_etype=False There won't be
update_all()
For updating messages .
For isomorphic graphs :
import dgl
import dgl.function as fn
import torch
g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
g.ndata['x'] = torch.ones(5, 2)
g.update_all(fn.copy_u('x', 'm'), fn.mean('m', 'h'))
print(g.ndata['h'])
g.update_all(fn.u_add_v('x', 'x', 'm'), fn.sum('m', 'h'))
print(g.ndata['h'])
Output :
g.update_all(fn.copy_u('x', 'm'), fn.mean('m', 'h'))
This is copy Node x Feature to m Then on m Take the average value to get the node characteristics h, Because this picture is 0->1->2->3->4, therefore 0 There is no message from the node
g.update_all(fn.u_add_v('x', 'x', 'm'), fn.sum('m', 'h'))
This u_add_v It is to connect the source node and the target node x Add the features to get m Then for all m Sum to get h, Again 0 There is no message from the node .
For heterogeneous graphs :
When you want to update some specific relationships :
import dgl
import torch as th
g = dgl.heterograph({
('user', 'follows', 'user') : ([0, 1], [1, 2]),
('user', 'plays', 'game') : ([0], [1]),
('store', 'sells', 'game') :([0], [2])})
g.nodes["user"].data["w"] = th.ones(3, 2)
g.nodes["game"].data["w"] = th.ones(3, 2) + 1
g.nodes["store"].data["w"] = th.ones(1, 2) + 2
print(g.nodes["user"].data["w"])
print(g["follows"]) # follows Subgraph of relation
g['follows'].update_all(fn.copy_src('w', 'm'), fn.sum('m', 'h'), etype="follows")
print(g.nodes["user"].data["h"])
print(g.nodes["user"].data["w"])
# print(g.nodes["store"].data["h"]) # Only updated follows The node of the relationship
Output :
because user yes 0->1->2, therefore 0 No message came
Heterogeneous graph transmits messages to all relationships :
import dgl
import torch as th
g = dgl.heterograph({
('user', 'follows', 'user'): ([0, 1], [1, 1]),
('game', 'attracts', 'user'): ([0], [1])
})
g.nodes['user'].data['h'] = torch.tensor([[1.], [2.]])
g.nodes['game'].data['h'] = torch.tensor([[1.]])
g.update_all(fn.copy_src('h', 'm'), fn.sum('m', 'h'))
print(g.nodes['user'].data['h'])
Output :
because user0 -> user1, user1->user1, game0 ->user1, It means that user1 Will converge user0、1 and game0 Of h features
1+2+1 = 4 obtain user1 Of h Characterized by 4 In line with expectations , because user1 No message came , So it is 0
apply_edges()
Used to update the features of edges
For isomorphic graphs :
g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
g.ndata['h'] = torch.ones(5, 2)
g.apply_edges(lambda edges: {
'x' : edges.src['h'] + edges.dst['h']})
print(g.edata['x'])
The operation here is to merge the source node and target node of each edge h Add to get the characteristics of the edge x
Output :
import dgl.function as fn
g.apply_edges(fn.u_add_v('h', 'h', 'x'))
g.edata['x']
This way of writing has the same meaning as the above
For heterogeneous graphs :
import dgl
import torch as th
g = dgl.heterograph({
('user', 'follows', 'user'): ([0, 1], [1, 1]),
('game', 'attracts', 'user'): ([0], [1])
})
g.nodes['user'].data['h'] = torch.tensor([[1.], [2.]])
g.nodes['game'].data['h'] = torch.tensor([[1.]])
g.update_all(fn.copy_src('h', 'm'), fn.sum('m', 'h'))
g.apply_edges(lambda edges: {
'h': edges.src['h'] * 2}, etype="follows")
print(g.edges["follows"].data['h'])
When there is more than one side , You need to specify the etype
Output :
follows In relationship ,user0->user1, user1->user1, because user0 Characteristics of h by 0,user1 Characteristics of h by 4 So the result is 0,8 In line with expectations .
apply_nodes()
Only used to transform the characteristics of nodes
For isomorphic graphs :
import dgl
import dgl.function as fn
import torch
g = dgl.graph(([0, 1, 2, 3], [1, 2, 3, 4]))
g.ndata['h'] = torch.ones(5, 2)
g.apply_nodes(lambda nodes: {
'x' : nodes.data['h'] * 2})
print(g.ndata['x'])
Assign x Characterized by nodes h The eigenvalue *2
Output :
For heterogeneous graphs :
import dgl
import torch as th
g = dgl.heterograph({
('user', 'follows', 'user'): ([0, 1], [1, 1]),
('game', 'attracts', 'user'): ([0], [1])
})
g.nodes['user'].data['h'] = torch.tensor([[1.], [2.]])
g.nodes['game'].data['h'] = torch.tensor([[1.]])
g.update_all(fn.copy_src('h', 'm'), fn.sum('m', 'h'))
g.apply_nodes(lambda nodes: {
'h': nodes.data['h'] * 1.5}, ntype='user')
print(g.nodes['user'].data['h'])
Yes user Node characteristics h*1.5
Output :
apply_each()
It can transform the corresponding features of some special format data, such as dictionary type data
import dgl
import torch as th
import torch
from dgl import apply_each
h = {
k: torch.randn(3) for k in ['A', 'B', 'C']}
print(h)
h = apply_each(h, torch.nn.functional.relu)
assert all((v >= 0).all() for v in h.values())
print(h)
Here will be the dictionary h Corresponding to the features in relu Activate
Get the results :
Positive retention , A negative number is 0, In line with expectations .
HeteroLinear
Heterogeneous linear layer , Suitable for heterogeneous graph processing
import dgl
import torch
from dgl.nn import HeteroLinear
layer = HeteroLinear({
'user': 1, ('user', 'follows', 'user'): 2}, 3)
in_feats = {
'user': torch.randn(2, 1), ('user', 'follows', 'user'): torch.randn(3, 2)}
out_feats = layer(in_feats)
print(out_feats['user'].shape)
print(out_feats[('user', 'follows', 'user')].shape)
Definition requires a dictionary ({ features 1: Input dimension , features 2: Input dimension }, Dimension of output )
You can complete the alignment output of dimensions .
Code output :
Reference resources
https://docs.dgl.ai/en/0.9.x/generated/dgl.transforms.AddReverse.html?highlight=dgl%20addreverse#dgl.transforms.AddReverse
https://docs.dgl.ai/en/0.9.x/generated/dgl.DGLGraph.update_all.html?highlight=update_all
https://docs.dgl.ai/en/0.9.x/generated/dgl.DGLGraph.apply_edges.html?highlight=apply_edges
https://docs.dgl.ai/en/0.9.x/generated/dgl.nn.pytorch.HeteroLinear.html?highlight=heterolinear
边栏推荐
- The vision group of Hegong University Sky team trained day3 - machine learning, strengthened the use of Yolo models, and learned pumpkin books and watermelon books
- Anaconda install pytorch
- Binary search common questions
- Basic operation of queue
- Natural language processing Jieba
- 1005. Maximized array sum after K negations
- 加密熊市:有人大举扩张 有人裁员收缩
- Debug NO2 check for errors according to the process
- Why is knowledge base important? This is the best answer I've ever heard
- how to add square on screenshot
猜你喜欢

QT | string generation QR code function

Database system - Basic Concepts

Postman extracts the token parameter value in the response header and sets it as an environment variable, with code attached

Project practice - document scanning OCR recognition

Summary of study notes (I)

【MATLAB】(四)MATLAB在线性代数中的应用

Installation and use of Zen path & defect report & defect operation

Digital twin demonstration project -- Talking about simple pendulum (3) solid model exploration
![[matlab] (IV) application of MATLAB in linear algebra](/img/c8/97fddb4105008990173247b1b4a155.png)
[matlab] (IV) application of MATLAB in linear algebra

jmeter中JSON提取器使用
随机推荐
P1739表达式括号匹配题解
RBM contrast divergence
Why is knowledge base important? This is the best answer I've ever heard
MySQL --- 子查询 - 标量子查询
55. Jumping game
Hegong sky team vision training Day2 - traditional vision, opencv basic operation
Have you seen the interview questions of VR major? Trust me, it's absolutely useful
Case practice - panoramic image mosaic: feature matching method
MySQL -- subquery scalar subquery
Image feature Harris corner detection
Intelligent robots and intelligent systems (Professor Zheng Zheng of Dalian University of Technology) -- 2. Mobile Robot Perception
[matlab] (III) application of MATLAB in Higher Mathematics
Telecom Customer Churn Prediction challenge baseline [AI competition]
OpenGL camera and periodic review
基于VSCode聊聊编译器那些事儿
Super simple countdown code writing
Arduino's super power-saving sleep mode has worked with one 18650 battery for 17 years
Detailed notes on pytoch building neural network
*Yolo5 learning * data experiment based on yolo5 face combined with attention model se
[matlab] (IV) application of MATLAB in linear algebra