├── src ├── fraudd_backend │ ├── __init__.py │ ├── requirements.txt │ ├── wsgi.py │ ├── README.md │ └── fraudd │ │ ├── __init__.py │ │ └── gnn │ │ └── __init__.py ├── fraudd_frontend │ ├── babel.config.js │ ├── public │ │ ├── favicon.ico │ │ └── index.html │ ├── src │ │ ├── main.js │ │ ├── App.vue │ │ └── components │ │ │ └── Table.vue │ ├── .gitignore │ ├── README.md │ └── package.json ├── docker-compose.yaml └── nginx.conf ├── .gitignore ├── notebooks ├── README.md ├── Inference_API.ipynb └── Train_GraphSAGE.ipynb ├── LICENSE └── README.md /src/fraudd_backend/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/fraudd_frontend/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | '@vue/cli-plugin-babel/preset' 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /src/fraudd_frontend/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/HEAD/src/fraudd_frontend/public/favicon.ico -------------------------------------------------------------------------------- /src/fraudd_frontend/src/main.js: -------------------------------------------------------------------------------- 1 | import { createApp } from 'vue' 2 | import App from './App.vue' 3 | const app = createApp(App); 4 | 5 | app.mount('#app') 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # python 2 | __pycache__ 3 | # vscode 4 | .vscode 5 | # macOS 6 | .DS_Store 7 | 8 | # model 9 | *.model 10 | 11 | # jupyter 12 | .ipynb_checkpoints 13 | -------------------------------------------------------------------------------- /src/fraudd_backend/requirements.txt: -------------------------------------------------------------------------------- 1 | Flask==2.0.1 2 | Flask-Cors==3.0.10 3 | Flask-SocketIO==5.2.0 4 | torch==1.12.0 5 | dgl==0.9.0 6 | PyYAML==5.4.1 7 | git+https://github.com/vesoft-inc/nebula-python.git@8c328c534413b04ccecfd42e64ce6491e09c6ca8 8 | git+https://github.com/wey-gu/nebula-dgl.git@f7a8226a28c4f481a2eb28161904025a807b9b7f 9 | -------------------------------------------------------------------------------- /src/fraudd_backend/wsgi.py: -------------------------------------------------------------------------------- 1 | #!/bin/env python3 2 | from fraudd import create_instance 3 | application = app = create_instance() 4 | 5 | 6 | """ 7 | # How to run the app 8 | export NG_ENDPOINTS="10.1.1.168:9669"; 9 | export FLASK_ENV=development; 10 | export FLASK_APP=wsgi; 11 | python3 -m flask run --reload --host=0.0.0.0 12 | """ 13 | -------------------------------------------------------------------------------- /src/fraudd_frontend/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | 5 | 6 | # local env files 7 | .env.local 8 | .env.*.local 9 | 10 | # Log files 11 | npm-debug.log* 12 | yarn-debug.log* 13 | yarn-error.log* 14 | pnpm-debug.log* 15 | 16 | # Editor directories and files 17 | .idea 18 | .vscode 19 | *.suo 20 | *.ntvs* 21 | *.njsproj 22 | *.sln 23 | *.sw? 24 | -------------------------------------------------------------------------------- /src/fraudd_backend/README.md: -------------------------------------------------------------------------------- 1 | ## How To Run 2 | 3 | First, install and run the backend with `flask run`. 4 | 5 | ```bash 6 | python3 -m pip install -r requirements.txt 7 | 8 | export NG_ENDPOINTS="127.0.0.1:9669"; 9 | export FLASK_ENV=development; 10 | export FLASK_APP=wsgi; 11 | 12 | python3 -m flask run --reload --host=0.0.0.0 13 | ``` 14 | 15 | Then, set up an Nginx to enable CORS, the configuration is under `../nginx.conf` 16 | 17 | -------------------------------------------------------------------------------- /src/fraudd_frontend/README.md: -------------------------------------------------------------------------------- 1 | # fraudd_frontend 2 | 3 | ## Project setup 4 | ``` 5 | npm install 6 | ``` 7 | 8 | ### Compiles and hot-reloads for development 9 | ``` 10 | npm run serve 11 | ``` 12 | 13 | ### Compiles and minifies for production 14 | ``` 15 | npm run build 16 | ``` 17 | 18 | ### Lints and fixes files 19 | ``` 20 | npm run lint 21 | ``` 22 | 23 | ### Customize configuration 24 | See [Configuration Reference](https://cli.vuejs.org/config/). 25 | -------------------------------------------------------------------------------- /src/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | nginx: 3 | image: nginx:1.19.2-alpine 4 | hostname: nginx 5 | volumes: 6 | - ${PWD}/nginx.conf:/etc/nginx/nginx.conf:ro 7 | - ${PWD}/fraudd_frontend/dist:/data:ro 8 | ports: 9 | - "15000:15000" 10 | - "8080:8080" 11 | networks: 12 | - nebula-net 13 | extra_hosts: 14 | - "host.docker.internal:host-gateway" 15 | 16 | networks: 17 | nebula-net: 18 | external: true 19 | -------------------------------------------------------------------------------- /src/fraudd_frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | <%= htmlWebpackPlugin.options.title %> 9 | 10 | 11 | 14 |
15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /notebooks/README.md: -------------------------------------------------------------------------------- 1 | | Notebook | Arch. and Flow | 2 | | ------------------------------------------------------------ | ------------------------------------------------------------ | 3 | | [Train_GraphSAGE.ipynb](https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/tree/main/notebooks/Train_GraphSAGE.ipynb) | | 4 | | [Inference_API.ipynb](https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/tree/main/notebooks/Inference_API.ipynb) | ![GraphSAGE_FraudDetection_Inference](https://user-images.githubusercontent.com/1651790/182292372-2bef1e38-db4e-4949-8f66-bff361ee93d9.svg) | 5 | 6 | -------------------------------------------------------------------------------- /src/fraudd_frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fraudd_frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service serve", 7 | "build": "vue-cli-service build", 8 | "lint": "vue-cli-service lint" 9 | }, 10 | "dependencies": { 11 | "socket.io-client": "^4.5.1", 12 | "vue": "^3.0.0", 13 | "vue3-table-lite": "^1.2.3" 14 | }, 15 | "devDependencies": { 16 | "@vue/cli-plugin-babel": "~4.5.15", 17 | "@vue/cli-plugin-eslint": "~4.5.15", 18 | "@vue/cli-service": "~4.5.15", 19 | "@vue/compiler-sfc": "^3.0.0", 20 | "babel-eslint": "^10.1.0", 21 | "eslint": "^6.7.2", 22 | "eslint-plugin-vue": "^7.0.0" 23 | }, 24 | "eslintConfig": { 25 | "root": true, 26 | "env": { 27 | "node": true 28 | }, 29 | "extends": [ 30 | "plugin:vue/vue3-essential", 31 | "eslint:recommended" 32 | ], 33 | "parserOptions": { 34 | "parser": "babel-eslint" 35 | }, 36 | "rules": {} 37 | }, 38 | "browserslist": [ 39 | "> 1%", 40 | "last 2 versions", 41 | "not dead" 42 | ] 43 | } 44 | -------------------------------------------------------------------------------- /src/fraudd_frontend/src/App.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | 27 | 28 | 69 | -------------------------------------------------------------------------------- /src/nginx.conf: -------------------------------------------------------------------------------- 1 | user nginx; 2 | worker_processes auto; 3 | 4 | error_log /var/log/nginx/error.log warn; 5 | pid /var/run/nginx.pid; 6 | 7 | events { 8 | worker_connections 4096; 9 | } 10 | 11 | http { 12 | include /etc/nginx/mime.types; 13 | default_type application/octet-stream; 14 | 15 | log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 16 | '$status $body_bytes_sent "$http_referer" ' 17 | '"$http_user_agent" "$http_x_forwarded_for"'; 18 | 19 | access_log /var/log/nginx/access.log main; 20 | sendfile on; 21 | keepalive_timeout 65; 22 | 23 | # include /etc/nginx/conf.d/*.conf; 24 | 25 | server { 26 | listen 15000; 27 | server_name nebula-demo.siwei.io; 28 | 29 | location / { 30 | add_header 'Access-Control-Allow-Origin' '*' always; 31 | proxy_pass http://host.docker.internal:5000; # backend 32 | proxy_redirect off; 33 | 34 | proxy_set_header Host $host; 35 | proxy_set_header X-Real-IP $remote_addr; 36 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 37 | } 38 | 39 | # reverse proxy for Socket.IO connections 40 | location /socket.io { 41 | proxy_pass http://host.docker.internal:5000/socket.io; # backend 42 | proxy_http_version 1.1; 43 | proxy_redirect off; 44 | proxy_buffering off; 45 | 46 | proxy_set_header Host $host; 47 | proxy_set_header X-Real-IP $remote_addr; 48 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 49 | 50 | proxy_set_header Upgrade $http_upgrade; 51 | proxy_set_header Connection "Upgrade"; 52 | } 53 | } 54 | server { 55 | listen 8080; 56 | server_name nebula-demo.siwei.io; 57 | root /data ; 58 | gzip on; 59 | gzip_vary on; 60 | gzip_comp_level 6; 61 | gzip_buffers 16 8k; 62 | gzip_min_length 1k; 63 | gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+css text/javascript; 64 | 65 | location / { 66 | # add_header 'Access-Control-Allow-Origin' '*' always; 67 | root /data ; 68 | try_files $uri $uri/ @rewrites; 69 | } 70 | 71 | location @rewrites { 72 | rewrite ^(.+)$ /index.html last; 73 | } 74 | 75 | location ~* \.(?:ico|css|js|gif|jpe?g|png)$ { 76 | # Some basic cache-control for static files to be sent to the browser 77 | expires max; 78 | add_header Pragma public; 79 | add_header Cache-Control "public, must-revalidate, proxy-revalidate"; 80 | } 81 | } 82 | } -------------------------------------------------------------------------------- /src/fraudd_frontend/src/components/Table.vue: -------------------------------------------------------------------------------- 1 | 7 | 8 | 114 | 115 | -------------------------------------------------------------------------------- /src/fraudd_backend/fraudd/__init__.py: -------------------------------------------------------------------------------- 1 | # ┌─────────────────────┐ ┌─────────────────┐ 2 | # │ │ │ │ 3 | # ─────▶│ Transaction Record ├──────2. Fraud Risk ─────▶│ Inference API │◀────┐ 4 | # │ │◀────Prediction with ─────┤ │ │ 5 | # │ │ Sub Graph │ │ │ 6 | # └─────────────────────┘ └─────────────────┘ │ 7 | # │ ▲ │ │ 8 | # │ │ │ │ 9 | # 0. Insert 1. Get New 3.req: Node │ 10 | # Record Record Sub Classification │ 11 | # │ Graph │ │ 12 | # ▼ │ │ │ 13 | # ┌──────────────────────┴─────────────────┐ ┌────────────────────┘ 3.resp: │ 14 | # │┌──────────────────────────────────────┐│ │ Predicted│ 15 | # ││ Graph of Historical Transactions ││ │ Risk │ 16 | # │└──────────────────────────────────────┘│ │ │ 17 | # │ .─. . │ │ │ 18 | # │ ( )◀───────────( ) │ │ │ 19 | # │ `─' ' │ │ ┌──────────────────────┐ │ 20 | # │ . .─. ╲ ◁ │ │ │ GNN Model Λ │ │ 21 | # │ ( )◀────( ) ╲ ╱ │ │ ┌───┴─┐ ╱ ╲ ┌──┴──┐ │ 22 | # │ ' `─' ╲ . ╱ │ │ ├─────┤ ╱ ╲ ├─────┤ │ 23 | # │ ╲ ◀ ╲ ( ) │ └─▶├─────┼─────▶▕ ─────├─────┤──┘ 24 | # │ ╲ . ╱ ◁ ' │ ├─────┤ ╲ ╱ ├─────┤ 25 | # │ ◀( )╱ .─. .─. │ └───┬─┘ ╲ ╱ └──┬──┘ 26 | # │ ' ( )◀──────( )│ │ V │ 27 | # │ `─' `─' │ └──────────────────────┘ 28 | # └────────────────────────────────────────┘ 29 | 30 | # Flask App for the Fraud Detection Backend 31 | # RESTful API for New Record Ingestion and Inference 32 | # SocketIO for broadcast new record to Dashboard 33 | 34 | import os 35 | import json 36 | import gzip 37 | 38 | import urllib.request as urllib2 39 | 40 | import torch 41 | 42 | from flask import Flask, jsonify, request 43 | from flask_cors import CORS 44 | from flask_socketio import SocketIO 45 | from flask_socketio import emit 46 | 47 | from nebula3.gclient.net import ConnectionPool 48 | from nebula3.Config import Config 49 | 50 | from .gnn import gnn_model, do_inference, get_subgraph, to_dgl 51 | 52 | def create_instance(): 53 | 54 | app = Flask(__name__) 55 | app.config['SECRET_KEY'] = 'secret!' 56 | app.config['TESTING'] = True 57 | app.config['ENVRIONMENT'] = 'development' 58 | CORS(app, supports_credentials=True) 59 | socketio = SocketIO( 60 | app, cors_allowed_origins=['http://10.1.1.127:8080', 'http://nebula-demo.siwei.io:8080'], 61 | logger=True, engineio_logger=True) 62 | 63 | 64 | @app.route("/api") 65 | def root(): 66 | return jsonify({"status": "ok"}) 67 | 68 | @socketio.on('my_event') 69 | def my_event(data): 70 | emit('my response', {'data': 'got it!'}) 71 | print('received message: ' + data) 72 | 73 | @socketio.on('test', namespace="/") 74 | def test(): 75 | emit("my_event", broadcast=True) 76 | print("test recieved") 77 | 78 | @app.route("/api/add_review", methods=["POST"]) 79 | def add_review(): 80 | """ 81 | curl -X POST 127.0.0.1:5000/api/add_review \ 82 | -d '{"vertex_id": "2048"}' \ 83 | -H 'Content-Type: application/json' 84 | """ 85 | 86 | request_data = request.get_json() 87 | vertex_id = int(request_data.get("vertex_id", "2048")) 88 | with connection_pool.session_context("root", "nebula") as session: 89 | sub_graph = get_subgraph(session, vertex_id) 90 | g, node_id_map = to_dgl(sub_graph) 91 | pred = do_inference( 92 | graph=g, 93 | node_idx=node_id_map[vertex_id], 94 | model=model).tolist() 95 | # see below 96 | is_fraud = bool((pred[1] - pred[0]) > 2.0) 97 | # let's broadcast the new record to the dashboard 98 | emit("new_review", json.dumps({ 99 | "vertex_id": vertex_id, 100 | "is_fraud": bool(is_fraud), 101 | "feat" : g.ndata["feat"][0].tolist()}), 102 | broadcast=True, 103 | namespace="/") 104 | return jsonify({"is_fraud": is_fraud}) 105 | 106 | # We could see those fraud data comes with pred[1] - pred[0] > 2.0 107 | # In [369]: index_i = 0 108 | 109 | # In [370]: for r_ in result: 110 | # ...: if r_[0] < r_[1]: 111 | # ...: print(str(r_) + ": "+ str(hg_test.ndata['label'][index_i])) 112 | # ...: index_i += 1 113 | # ...: 114 | # tensor([-0.4653, 2.0515]): tensor(1) 115 | # tensor([-0.3854, 1.3931]): tensor(1) 116 | # tensor([-1.1046, 2.5900]): tensor(1) 117 | # tensor([-0.7643, 1.8981]): tensor(1) 118 | # tensor([-0.9891, 1.9606]): tensor(1) 119 | # tensor([-0.8305, 2.1667]): tensor(1) 120 | # tensor([-0.5225, 1.8346]): tensor(1) 121 | # tensor([-0.5545, 1.8461]): tensor(1) 122 | # tensor([-0.7387, 1.7869]): tensor(1) 123 | # tensor([-0.8426, 1.9154]): tensor(1) 124 | # tensor([-1.1986, 1.8055]): tensor(1) 125 | # tensor([-0.9264, 2.2199]): tensor(1) 126 | # tensor([-1.2745, 2.5923]): tensor(1) 127 | # tensor([-0.6774, 1.9199]): tensor(1) 128 | # tensor([-0.8768, 1.4789]): tensor(1) 129 | # tensor([-0.5717, 0.7597]): tensor(0) 130 | # tensor([-0.2695, 1.6488]): tensor(0) 131 | # tensor([-1.1005, 1.9970]): tensor(1) 132 | # tensor([-1.1340, 2.2460]): tensor(1) 133 | # tensor([-0.9052, 2.2489]): tensor(1) 134 | # tensor([-0.1937, 1.3082]): tensor(1) 135 | # tensor([-0.1576, 1.4129]): tensor(1) 136 | # tensor([-0.8976, 1.9711]): tensor(1) 137 | # tensor([-0.9199, 2.1958]): tensor(1) 138 | # tensor([0.2016, 0.8248]): tensor(1) 139 | # tensor([-0.4452, 1.5325]): tensor(1) 140 | # tensor([-0.6960, 1.7163]): tensor(1) 141 | # tensor([0.6867, 0.7077]): tensor(0) 142 | # tensor([-0.7088, 1.5952]): tensor(1) 143 | # tensor([-0.9164, 2.2585]): tensor(1) 144 | # tensor([-0.7836, 2.2548]): tensor(1) 145 | # tensor([0.7041, 0.7049]): tensor(0) 146 | # tensor([-0.6718, 1.7835]): tensor(1) 147 | # tensor([-0.6657, 1.9698]): tensor(1) 148 | # tensor([-0.8179, 1.7891]): tensor(1) 149 | # tensor([-0.4910, 1.6841]): tensor(1) 150 | # tensor([-0.3798, 1.2956]): tensor(1) 151 | # tensor([-1.2844, 2.6029]): tensor(1) 152 | # tensor([-1.3074, 2.6277]): tensor(1) 153 | # tensor([-0.4255, 1.2594]): tensor(0) 154 | # tensor([-0.5220, 1.6514]): tensor(1) 155 | # tensor([-0.2769, 1.5949]): tensor(0) 156 | # tensor([0.6179, 1.1152]): tensor(0) 157 | # tensor([-0.6887, 1.7105]): tensor(1) 158 | # tensor([0.0102, 1.0130]): tensor(1) 159 | # tensor([-0.3933, 1.2951]): tensor(0) 160 | # tensor([-0.4631, 1.3833]): tensor(0) 161 | # tensor([-0.9345, 2.5175]): tensor(1) 162 | # tensor([-0.7374, 1.7976]): tensor(1) 163 | # tensor([-0.4642, 1.1329]): tensor(0) 164 | # tensor([-0.2998, 1.6415]): tensor(1) 165 | # tensor([0.0586, 1.7155]): tensor(0) 166 | # tensor([-0.8710, 2.5655]): tensor(1) 167 | # tensor([-0.1306, 1.4905]): tensor(0) 168 | # tensor([-0.3283, 1.2049]): tensor(1) 169 | # tensor([-0.6847, 1.8038]): tensor(1) 170 | # tensor([-0.6173, 1.7529]): tensor(1) 171 | # tensor([-1.0240, 2.4342]): tensor(1) 172 | # tensor([0.8416, 0.8935]): tensor(0) 173 | # tensor([-0.9524, 2.4270]): tensor(1) 174 | # tensor([-0.7680, 1.6052]): tensor(1) 175 | # tensor([-0.2216, 1.4630]): tensor(1) 176 | 177 | 178 | def parse_nebula_graphd_endpoint(): 179 | ng_endpoints_str = os.environ.get( 180 | 'NG_ENDPOINTS', '127.0.0.1:9669,').split(",") 181 | ng_endpoints = [] 182 | for endpoint in ng_endpoints_str: 183 | if endpoint: 184 | parts = endpoint.split(":") # we dont consider IPv6 now 185 | ng_endpoints.append((parts[0], int(parts[1]))) 186 | return ng_endpoints 187 | 188 | 189 | ng_config = Config() 190 | ng_config.max_connection_pool_size = int( 191 | os.environ.get('NG_MAX_CONN_POOL_SIZE', 10)) 192 | ng_endpoints = parse_nebula_graphd_endpoint() 193 | connection_pool = ConnectionPool() 194 | 195 | MODEL_LOCAL_PATH = "fraud_d.model" 196 | 197 | # load model from online gzip file 198 | DEFAULT_MODEL_URL = "https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/releases/download/v0.0.1/fraud_d.model.gz" 199 | 200 | def load_model(url): 201 | if not os.path.exists(MODEL_LOCAL_PATH): 202 | # Read the file inside the .gz archive located at url 203 | with urllib2.urlopen(url) as response: 204 | with gzip.GzipFile(fileobj=response) as uncompressed: 205 | file_content = uncompressed.read() 206 | # write to file in binary mode 'wb' 207 | with open(MODEL_LOCAL_PATH, 'wb') as f: 208 | f.write(file_content) 209 | gnn_model.load_state_dict(torch.load(MODEL_LOCAL_PATH)) 210 | return gnn_model 211 | 212 | 213 | connection_pool.init(ng_endpoints, ng_config) 214 | model = load_model(os.environ.get('NG_MODEL_URL', DEFAULT_MODEL_URL)) 215 | 216 | return app 217 | -------------------------------------------------------------------------------- /src/fraudd_backend/fraudd/gnn/__init__.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | import dgl 7 | import dgl.nn as dglnn 8 | 9 | from torch import tensor 10 | from dgl import DGLHeteroGraph, heterograph 11 | from dgl import function as fn 12 | from dgl.utils import check_eq_shape 13 | from dgl.dataloading import DataLoader, MultiLayerFullNeighborSampler 14 | 15 | import tqdm 16 | 17 | # https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/blob/main/notebooks/Inference_API.ipynb 18 | 19 | def get_subgraph(session, vertex_id): 20 | r = session.execute_json( 21 | "USE yelp;" 22 | f"GET SUBGRAPH WITH PROP 2 STEPS FROM {vertex_id} " 23 | "YIELD VERTICES AS nodes, EDGES AS relationships;") 24 | r = json.loads(r) 25 | return r.get('results', [{}])[0].get('data') 26 | 27 | 28 | def to_dgl(data): 29 | node_id_map = {} # key: vertex id in NebulaGraph, value: node id in dgl_graph 30 | node_idx = 0 31 | features = [[] for _ in range(32)] + [[]] 32 | for i in range(len(data)): 33 | for index, node in enumerate(data[i]['meta'][0]): 34 | nodeid = data[i]['meta'][0][index]['id'] 35 | if nodeid not in node_id_map: 36 | node_id_map[nodeid] = node_idx 37 | node_idx += 1 38 | for f in range(32): 39 | features[f].append(data[i]['row'][0][index][f"review.f{f}"]) 40 | features[32].append(data[i]['row'][0][index]['review.is_fraud']) 41 | 42 | 43 | rur_start, rur_end, rsr_start, rsr_end, rtr_start, rtr_end = [], [], [], [], [], [] 44 | for i in range(len(data)): 45 | for edge in data[i]['meta'][1]: 46 | edge = edge['id'] 47 | if edge['name'] == 'shares_user_with': 48 | rur_start.append(node_id_map[edge['src']]) 49 | rur_end.append(node_id_map[edge['dst']]) 50 | elif edge['name'] == 'shares_restaurant_rating_with': 51 | rsr_start.append(node_id_map[edge['src']]) 52 | rsr_end.append(node_id_map[edge['dst']]) 53 | elif edge['name'] == 'shares_restaurant_in_one_month_with': 54 | rtr_start.append(node_id_map[edge['src']]) 55 | rtr_end.append(node_id_map[edge['dst']]) 56 | 57 | data_dict = {} 58 | if rur_start: 59 | data_dict[('review', 'shares_user_with', 'review')] = tensor(rur_start), tensor(rur_end) 60 | if rsr_start: 61 | data_dict[('review', 'shares_restaurant_rating_with', 'review')] = tensor(rsr_start), tensor(rsr_end) 62 | if rtr_start: 63 | data_dict[('review', 'shares_restaurant_in_one_month_with', 'review')] = tensor(rtr_start), tensor(rtr_end) 64 | 65 | # construct a dgl_graph 66 | dgl_graph: DGLHeteroGraph = heterograph(data_dict) 67 | 68 | # load node features to dgl_graph 69 | for i in range(32): 70 | dgl_graph.ndata[f"f{i}"] = tensor(features[i]) 71 | dgl_graph.ndata['label'] = tensor(features[32]) 72 | 73 | # to homogeneous graph 74 | features = [] 75 | for i in range(32): 76 | features.append(dgl_graph.ndata[f"f{i}"]) 77 | 78 | dgl_graph.ndata['feat'] = torch.stack(features, dim=1) 79 | 80 | dgl_graph.edges['shares_restaurant_in_one_month_with'].data['he'] = torch.ones( 81 | dgl_graph.number_of_edges('shares_restaurant_in_one_month_with'), dtype=torch.float32) 82 | dgl_graph.edges['shares_restaurant_rating_with'].data['he'] = torch.full( 83 | (dgl_graph.number_of_edges('shares_restaurant_rating_with'),), 2, dtype=torch.float32) 84 | dgl_graph.edges['shares_user_with'].data['he'] = torch.full( 85 | (dgl_graph.number_of_edges('shares_user_with'),), 4, dtype=torch.float32) 86 | 87 | hg = dgl.to_homogeneous(dgl_graph, edata=['he'], ndata=['feat', 'label']) 88 | return hg, node_id_map 89 | 90 | 91 | def do_inference(graph, node_idx, model, batch_size=4096): 92 | model.eval() 93 | with torch.no_grad(): 94 | pred = model.inference(graph, device, batch_size) # pred in buffer_device 95 | return pred[node_idx] 96 | 97 | 98 | class SAGEConv(dglnn.SAGEConv): 99 | def forward(self, graph, feat, edge_weight=None): 100 | r""" 101 | 102 | Description 103 | ----------- 104 | Compute GraphSAGE layer. 105 | 106 | Parameters 107 | ---------- 108 | graph : DGLGraph 109 | The graph. 110 | feat : torch.Tensor or pair of torch.Tensor 111 | If a torch.Tensor is given, it represents the input feature of shape 112 | :math:`(N, D_{in})` 113 | where :math:`D_{in}` is size of input feature, :math:`N` is the number of nodes. 114 | If a pair of torch.Tensor is given, the pair must contain two tensors of shape 115 | :math:`(N_{in}, D_{in_{src}})` and :math:`(N_{out}, D_{in_{dst}})`. 116 | edge_weight : torch.Tensor, optional 117 | Optional tensor on the edge. If given, the convolution will weight 118 | with regard to the message. 119 | 120 | Returns 121 | ------- 122 | torch.Tensor 123 | The output feature of shape :math:`(N_{dst}, D_{out})` 124 | where :math:`N_{dst}` is the number of destination nodes in the input graph, 125 | :math:`D_{out}` is the size of the output feature. 126 | """ 127 | self._compatibility_check() 128 | with graph.local_scope(): 129 | if isinstance(feat, tuple): 130 | feat_src = self.feat_drop(feat[0]) 131 | feat_dst = self.feat_drop(feat[1]) 132 | else: 133 | feat_src = feat_dst = self.feat_drop(feat) 134 | if graph.is_block: 135 | feat_dst = feat_src[:graph.number_of_dst_nodes()] 136 | msg_fn = fn.copy_src('h', 'm') 137 | if edge_weight is not None: 138 | assert edge_weight.shape[0] == graph.number_of_edges() 139 | graph.edata['_edge_weight'] = edge_weight 140 | msg_fn = fn.u_mul_e('h', '_edge_weight', 'm') 141 | 142 | h_self = feat_dst 143 | 144 | # Handle the case of graphs without edges 145 | if graph.number_of_edges() == 0: 146 | graph.dstdata['neigh'] = torch.zeros( 147 | feat_dst.shape[0], self._in_src_feats).to(feat_dst) 148 | 149 | # Determine whether to apply linear transformation before message passing A(XW) 150 | lin_before_mp = self._in_src_feats > self._out_feats 151 | 152 | # Message Passing 153 | if self._aggre_type == 'mean': 154 | graph.srcdata['h'] = self.fc_neigh(feat_src) if lin_before_mp else feat_src 155 | # graph.update_all(msg_fn, fn.mean('m', 'neigh')) 156 | ######################################################################### 157 | # consdier datatype with different weight, g.edata['he'] as weight here 158 | g.update_all(fn.u_mul_e('h', 'he', 'm'), fn.mean('m', 'h')) 159 | ######################################################################### 160 | h_neigh = graph.dstdata['neigh'] 161 | if not lin_before_mp: 162 | h_neigh = self.fc_neigh(h_neigh) 163 | elif self._aggre_type == 'gcn': 164 | check_eq_shape(feat) 165 | graph.srcdata['h'] = self.fc_neigh(feat_src) if lin_before_mp else feat_src 166 | if isinstance(feat, tuple): # heterogeneous 167 | graph.dstdata['h'] = self.fc_neigh(feat_dst) if lin_before_mp else feat_dst 168 | else: 169 | if graph.is_block: 170 | graph.dstdata['h'] = graph.srcdata['h'][:graph.num_dst_nodes()] 171 | else: 172 | graph.dstdata['h'] = graph.srcdata['h'] 173 | graph.update_all(msg_fn, fn.sum('m', 'neigh')) 174 | graph.update_all(fn.copy_e('he', 'm'), fn.sum('m', 'neigh')) 175 | # divide in_degrees 176 | degs = graph.in_degrees().to(feat_dst) 177 | h_neigh = (graph.dstdata['neigh'] + graph.dstdata['h']) / (degs.unsqueeze(-1) + 1) 178 | if not lin_before_mp: 179 | h_neigh = self.fc_neigh(h_neigh) 180 | elif self._aggre_type == 'pool': 181 | graph.srcdata['h'] = F.relu(self.fc_pool(feat_src)) 182 | graph.update_all(msg_fn, fn.max('m', 'neigh')) 183 | graph.update_all(fn.copy_e('he', 'm'), fn.max('m', 'neigh')) 184 | h_neigh = self.fc_neigh(graph.dstdata['neigh']) 185 | elif self._aggre_type == 'lstm': 186 | graph.srcdata['h'] = feat_src 187 | graph.update_all(msg_fn, self._lstm_reducer) 188 | h_neigh = self.fc_neigh(graph.dstdata['neigh']) 189 | else: 190 | raise KeyError('Aggregator type {} not recognized.'.format(self._aggre_type)) 191 | 192 | # GraphSAGE GCN does not require fc_self. 193 | if self._aggre_type == 'gcn': 194 | rst = h_neigh 195 | else: 196 | rst = self.fc_self(h_self) + h_neigh 197 | 198 | # bias term 199 | if self.bias is not None: 200 | rst = rst + self.bias 201 | 202 | # activation 203 | if self.activation is not None: 204 | rst = self.activation(rst) 205 | # normalization 206 | if self.norm is not None: 207 | rst = self.norm(rst) 208 | return rst 209 | 210 | 211 | class SAGE(nn.Module): 212 | def __init__(self, in_size, hid_size, out_size): 213 | super().__init__() 214 | self.layers = nn.ModuleList() 215 | # three-layer GraphSAGE-mean 216 | self.layers.append(dglnn.SAGEConv(in_size, hid_size, 'mean')) 217 | self.layers.append(dglnn.SAGEConv(hid_size, hid_size, 'mean')) 218 | self.layers.append(dglnn.SAGEConv(hid_size, out_size, 'mean')) 219 | self.dropout = nn.Dropout(0.5) 220 | self.hid_size = hid_size 221 | self.out_size = out_size 222 | 223 | def forward(self, blocks, x): 224 | h = x 225 | for l, (layer, block) in enumerate(zip(self.layers, blocks)): 226 | h = layer(block, h) 227 | if l != len(self.layers) - 1: 228 | h = F.relu(h) 229 | h = self.dropout(h) 230 | return h 231 | 232 | def inference(self, g, device, batch_size): 233 | """Conduct layer-wise inference to get all the node embeddings.""" 234 | feat = g.ndata['feat'] 235 | sampler = MultiLayerFullNeighborSampler(1, prefetch_node_feats=['feat']) 236 | dataloader = DataLoader( 237 | g, torch.arange(g.num_nodes()).to(g.device), sampler, device=device, 238 | batch_size=batch_size, shuffle=False, drop_last=False, 239 | num_workers=0) 240 | buffer_device = torch.device('cpu') 241 | pin_memory = (buffer_device != device) 242 | 243 | for l, layer in enumerate(self.layers): 244 | y = torch.empty( 245 | g.num_nodes(), self.hid_size if l != len(self.layers) - 1 else self.out_size, 246 | device=buffer_device, pin_memory=pin_memory) 247 | feat = feat.to(device) 248 | for input_nodes, output_nodes, blocks in tqdm.tqdm(dataloader): 249 | x = feat[input_nodes] 250 | h = layer(blocks[0], x) # len(blocks) = 1 251 | if l != len(self.layers) - 1: 252 | h = F.relu(h) 253 | h = self.dropout(h) 254 | # by design, our output nodes are contiguous 255 | y[output_nodes[0]:output_nodes[-1]+1] = h.to(buffer_device) 256 | feat = y 257 | return y 258 | 259 | 260 | device = torch.device('cpu') 261 | gnn_model = SAGE(32, 256, 2).to(device) 262 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Arch and Flow 2 | 3 | ![GraphSAGE_FraudDetection](https://user-images.githubusercontent.com/1651790/182623863-de5c8ba6-5107-4707-8122-d2130085d5ac.svg) 4 | 5 | ### Model Training 6 | 7 | Check https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/tree/main/notebooks/Train_GraphSAGE.ipynb for details. 8 | 9 | - Input: Graph of Historical Yelp Reviews 10 | - Output: a GraphSAGE Node Classification Model, could be inductive 11 | 12 | ```asciiarmor 13 | ┌──────────────────────────────────────────────┐ 14 | │ ┌──────────────────────────────────────┐ │ 15 | │ │ Graph of Historical Reviews │ │ 16 | │ └──────────────────────────────────────┘ │ 17 | │ .─. . │ 18 | │ ( )◀───────────( ) │ 19 | │ `─' ' │ 20 | │ . .─. ╲ ◁ │ 21 | │ ( )◀────( ) ╲ . ╱ │ 22 | │ ' `─' ╲ ( )╱ │ 23 | │ ╲ ◀ ╲ ' │ 24 | │ ╲ . ╱ ◁ │ 25 | │ ◀( )╱ .─. .─. │ 26 | │ ' ( )◀──────( ) │ 27 | │ `─' `─' │ 28 | │ │ 29 | └──────────────────────────────────────────────┘ 30 | ┃ (Nebula-DGL: NebulaLoader) 31 | ▼ 32 | ┌────────────────────────────────────────────────────────────────────────────────────────┐ 33 | │ ┌────┐ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ┌ ─ ─ ─ ─ ─ ─ ─ ─ │ 34 | │ │GNN │ │ │ │ 35 | │ └────┘ │ │ │ 36 | │ │ │ │ 37 | │ │ ◀ │ ◀ │ 38 | │ . . ╱.─. │ . . ╱.─. │ │ 39 | │ │ ( )◀───╱( ) │ ( )◀───╱( ) │ 40 | │ . .─. '╱ ' `─' │ ┌────────┐ '╱ ' `─' │ . .─. │ 41 | │( )◀────( ) │ . .─. │ ReLU ╱│ │ . .─. ( )◀────( )│ 42 | │ ' `─' ( )◀────( ) │ │ ╱ │ ( )◀────( ) │ ' `─' │ 43 | │ ╲ ◀ ══▶ │ ' `─' │ ╱ │ │ ' `─' ... ══▶ ╲ ◀ │ 44 | │ ╲ . ╱ ╲ ◀ │ │───── │ ╲ ◀ │ ╲ . ╱ │ 45 | │ ◀( )╱ │ ╲ . ╱ └────────┘ │ ╲ . ╱ ◀( )╱ │ 46 | │ ' ◀( )╱ │ ◀( )╱ │ ' │ 47 | │ │ ' │ ' │ 48 | │ . .─. │ . .─. │ │ 49 | │ │ ( )◀────( ) │ ( )◀────( ) │ 50 | │ ' `─' │ ' `─' │ │ 51 | │ │ ╲ ◀ │ ╲ ◀ │ 52 | │ ╲ . ╱ │ ╲ . ╱ │ │ 53 | │ │ ◀( )╱ │ ◀( )╱ │ 54 | │ ' │ ' │ │ 55 | │ └ ─ ─ ─ ─ ─ ─ ─ ─ └ ─ ─ ─ ─ ─ ─ ─ ─ │ 56 | └────────────────────────────────────────────────────────────────────────────────────────┘ 57 | ┃ 58 | ▼ 59 | ┌──────────────────────────────────┐ 60 | │ Λ │ 61 | ┌───┴─┐ GNN Model ╱ ╲ ┌──┴──┐ 62 | ├─────┤ ╱ ╲ ├─────┤ 63 | ├─────┼────────────▶ ───────────▶├─────┤ 64 | ├─────┤ ╲ ╱ ├─────┤ 65 | └───┬─┘ ╲ ╱ └──┬──┘ 66 | │ V │ 67 | └──────────────────────────────────┘ 68 | ``` 69 | 70 | ### Online Fraud Inference System 71 | 72 | - For how it works, check [notebooks/Inference_API.ipynb](https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/tree/main/notebooks/Inference_API.ipynb) for details. 73 | 74 | - For its refererence implementation, see [src/fraudd_backend](https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/tree/main/src/fraudd_backend), [src/fraudd_frontend](https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/tree/main/src/fraudd_frontend) 75 | 76 | #### Backend 77 | - Input: a new review 78 | - Output: is_fraud prediction 79 | - Flow: 80 | 0. A review will be inserted to NebulaGraph 81 | 1. A SubGraph Query will be called 82 | 2. SubGraph will be sent to Inference API 83 | 3. Inference API will predict its `is_fraud` label on the trained model 84 | 85 | ```asciiarmor 86 | ┌─────────────────────┐ ┌─────────────────┐ 87 | │ │ │ │ 88 | ─────▶│ Transaction Record ├──────2. Fraud Risk ─────▶│ Inference API │◀────┐ 89 | │ │◀────Prediction with ─────┤ │ │ 90 | │ │ Sub Graph. │ │ │ 91 | └─────────────────────┘ └─────────────────┘ │ 92 | │ ▲ │ │ 93 | │ │ │ │ 94 | 0. Insert 1. Get New 3.req: Node │ 95 | Record. Record Sub Classification. │ 96 | │ Graph. │ │ 97 | ▼ │ │ │ 98 | ┌──────────────────────┴─────────────────┐ ┌────────────────────┘ 3.resp: │ 99 | │┌──────────────────────────────────────┐│ │ Predicted│ 100 | ││ Graph of Historical Transactions ││ │ Risk. │ 101 | │└──────────────────────────────────────┘│ │ │ 102 | │ .─. . │ │ │ 103 | │ ( )◀───────────( ) │ │ │ 104 | │ `─' ' │ │ ┌──────────────────────┐ │ 105 | │ . .─. ╲ ◁ │ │ │ GNN Model Λ │ │ 106 | │ ( )◀────( ) ╲ ╱ │ │ ┌───┴─┐ ╱ ╲ ┌──┴──┐ │ 107 | │ ' `─' ╲ . ╱ │ │ ├─────┤ ╱ ╲ ├─────┤ │ 108 | │ ╲ ◀ ╲ ( ) │ └─▶├─────┼─────▶▕ ─────├─────┤──┘ 109 | │ ╲ . ╱ ◁ ' │ ├─────┤ ╲ ╱ ├─────┤ 110 | │ ◀( )╱ .─. .─. │ └───┬─┘ ╲ ╱ └──┬──┘ 111 | │ ' ( )◀──────( )│ │ V │ 112 | │ `─' `─' │ └──────────────────────┘ 113 | └────────────────────────────────────────┘ 114 | ``` 115 | 116 | #### Frontend 117 | 118 | As the review request being sent to Graph Database and Inference API, when fraud predict is responded to the Inference API caller, in parallel, the result will be broadcast to Real Time Fraud Monitor Dashboards, too. 119 | 120 | The dashbard are tables subscribing to the flow of reviews sending in, and when some of the records are highlighted with hi risk in fraud, corresponding party will be notified and inovlved for follow-up actions. 121 | 122 | Demo Video 👉🏻: 123 | 124 | https://user-images.githubusercontent.com/1651790/182651965-d489a218-36a6-40c9-9fab-ba288e8d959a.mov 125 | 126 | ```asciiarmor 127 | ┌────────────────────────────────────────────────────────────────────┐ 128 | │ ┌──────────────────────────────────────────────────────────┐ │ 129 | │ │ Real-Time Online Fraud Monitor Web Service │ │ 130 | │ └──────────────────────────────────────────────────────────┘ │ 131 | │ │ 132 | │ ┌────┬────┬──────┬────┬────┬────┬────┬────┬────┬────┬──────┐ │ 133 | │ │ │ │ │ │ │ │ │ │ │ │ OK │ │ 134 | │ ├────┼────┼──────┼────┼────┼────┼────┼────┼────┼────┼──────┤ │ 135 | │ │ │ │ │ │ │ │ │ │ │ │ OK │ │ 136 | │ ├────┼────┼──────┼────┼────┼────┼────┼────┼────┼────┼──────┤ │ 137 | │ │ │ │ │ │ │ │ │ │ │ │ NOK │ │ 138 | │ └────┴────┴──────┴────┴────┴────┴────┴────┴────┴────┴──────┘ │ 139 | └─────────────────────────────────▲──────────────────────────────────┘ 140 | ┃ 141 | ┌───────────────────────┐ ┃ 142 | │ New Review/Requests │ ┃ 143 | │Generated Continuously │ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ 144 | └───────────────────────┘ ┃ 145 | │ ┃ 146 | │ ┃ 147 | │ ┌─────────────────────┐ ┌────────┻────────┐ 148 | │ │ │ │ │ 149 | │ │ │ │ │ 150 | └▶│ Transaction Record ├──────2. Fraud Risk ─────▶│ Inference API │◀────┐ 151 | │ │◀────Prediction with ─────┤ │ │ 152 | │ │ Sub Graph │ │ │ 153 | └─────────────────────┘ └─────────────────┘ │ 154 | ... 155 | ``` 156 | 157 | 158 | ## Graph Model and Data Set 159 | 160 | We will leverage Yelp-Fraud dataset comes from [Enhancing Graph Neural Network-based Fraud Detectors against Camouflaged Fraudsters](https://paperswithcode.com/paper/enhancing-graph-neural-network-based-fraud). 161 | 162 | There will be one type of node and three types of edges: 163 | 164 | - Node: review on restaurant, hotel. With Label and Feature Properties: 165 | - `is_fraud` to be the label 166 | - 32 features being feature-engineered 167 | - Edge: in 3-typed between the nodes. Without Properties: 168 | - R-U-R: share same reviewer, named `shares_user_with` 169 | - R-S-R: share same rate for same object, named `shares_restaurant_rating_with` 170 | - R-T-R: share same review submitting month for same object, named `shares_restaurant_in_one_month_with` 171 | 172 | Before the project, I made the playground to ingest the Yelp Data Graph into NebulaGraph, see more from https://github.com/wey-gu/nebulagraph-yelp-frauddetection. 173 | 174 | ### Playground Setup with Data Ingestion 175 | 176 | You could quickly run the following lines to make it ready: 177 | 178 | ```bash 179 | # Deploy NebulaGraph for Playground 180 | curl -fsSL nebula-up.siwei.io/install.sh | bash 181 | 182 | # Clone the data downloader repo 183 | git clone https://github.com/wey-gu/nebulagraph-yelp-frauddetection && cd nebulagraph-yelp-frauddetection 184 | 185 | # Install requirement, then download the data ready for NebulaGraph 186 | python3 -m pip install -r requirements.txt 187 | python3 data_download.py 188 | 189 | # Import it to NebulaGraph 190 | docker run --rm -ti \ 191 | --network=nebula-net \ 192 | -v ${PWD}/yelp_nebulagraph_importer.yaml:/root/importer.yaml \ 193 | -v ${PWD}/data:/root \ 194 | vesoft/nebula-importer:v3.1.0 \ 195 | --config /root/importer.yaml 196 | ``` 197 | 198 | Then refer to [notebooks/*](https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/tree/main/notebooks/) for Training Model and the Real-time Fraud Detection Web Service itself, and refer to [src/*](https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/tree/main/src/) for the Real-time Fraud Detection Web Service reference implementation. 199 | 200 | 201 | ### Playground of Real-Time Fraud Monitor 202 | 203 | Follow this, you should be able to run the Real-time Fraud Detection Web Service with my trained model being loaded. 204 | 205 | Get your machine's IP (not the 127.0.0.1), say it's `10.0.0.5`. 206 | 207 | ```bash 208 | export MY_IP="10.0.0.5" 209 | ``` 210 | 211 | Run Backend: 212 | 213 | ```bash 214 | git clone https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN.git 215 | cd NebulaGraph-Fraud-Detection-GNN/src 216 | 217 | # ADD MY_IP into CORS & Frontend file, nginx.conf 218 | sed -i "s/nebula-demo.siwei.io/$MY_IP/g" fraudd_backend/fraudd/__init__.py 219 | sed -i "s/nebula-demo.siwei.io/$MY_IP/g" fraudd_frontend/src/components/Table.vue 220 | sed -i "s/nebula-demo.siwei.io/$MY_IP/g" nginx.conf 221 | 222 | # install dep of backend 223 | python3 -m pip install -r requirements.txt 224 | 225 | export NG_ENDPOINTS="127.0.0.1:9669"; 226 | export FLASK_ENV=development; 227 | export FLASK_APP=wsgi; 228 | 229 | # run backend 230 | cd fraudd_backend 231 | 232 | python3 -m flask run --reload --host=0.0.0.0 233 | ``` 234 | 235 | ```bash 236 | # verify 237 | $ curl localhost:5000/api 238 | { 239 | "status": "ok" 240 | } 241 | ``` 242 | 243 | From another terminal, build frontend: 244 | 245 | ```bash 246 | cd NebulaGraph-Fraud-Detection-GNN/src 247 | cd fraudd_frontend 248 | 249 | # sudo apt install npm 250 | 251 | npm install 252 | npm run build 253 | ``` 254 | 255 | From another terminal, run Nginx: 256 | 257 | ```bash 258 | cd NebulaGraph-Fraud-Detection-GNN/src 259 | docker-compose up -d 260 | ``` 261 | 262 | ```bash 263 | # end-to-end verify backend 264 | curl -X POST localhost:15000/api/add_review \ 265 | -d '{"vertex_id": "2049"}' \ 266 | -H 'Content-Type: application/json' 267 | ``` 268 | 269 | ```bash 270 | # return value 271 | { 272 | "is_fraud": false 273 | } 274 | ``` 275 | 276 | From web browser 👉🏻 http://10.0.0.5:8080/ 277 | 278 | > You could check my demo: http://nebula-demo.siwei.io:8080 279 | 280 | -------------------------------------------------------------------------------- /notebooks/Inference_API.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "59bce22b-d5dd-426b-b831-24d35065d0f9", 6 | "metadata": {}, 7 | "source": [ 8 | "# Inference API\n", 9 | "\n", 10 | "Now we have trained the model, then we could use it in our Inference API service, thus, when a new trasaction/review comes to your system, you can predict if it's Fraud or not with it!\n", 11 | "\n", 12 | "This is the arch and workflow of it:\n", 13 | "\n", 14 | "![GraphSAGE_FraudDetection_Inference](https://user-images.githubusercontent.com/1651790/182292372-2bef1e38-db4e-4949-8f66-bff361ee93d9.svg)" 15 | ] 16 | }, 17 | { 18 | "cell_type": "markdown", 19 | "id": "646b9bb0-14b0-474e-b8a2-00a575cfa78e", 20 | "metadata": {}, 21 | "source": [ 22 | "## When A trasaction/review come\n", 23 | "\n", 24 | "Now, let's imagine we have this new record, with vertex id: `2048`.\n", 25 | "\n", 26 | "In `0. Insert Record` phase, it's already inserted into the Graph, together with the edges connected with it.\n", 27 | "\n", 28 | "Then, the next step is to Get the SubGraph from it, in NebulaGraph, it's actuall a query like this:\n", 29 | "\n", 30 | "```SQL\n", 31 | "GET SUBGRAPH WITH PROP FROM 2048 YIELD VERTICES AS nodes, EDGES AS relationships;\n", 32 | "```" 33 | ] 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "id": "3ba6bcac-a3a9-4e55-86ab-209bf3014ec0", 38 | "metadata": {}, 39 | "source": [ 40 | "To Better understand what this SubGraph is, we could see them from NebulaGraph Studio:\n", 41 | "\n", 42 | "![](https://user-images.githubusercontent.com/1651790/182024973-e92c8430-208c-4a0a-bf31-1b7a197d9241.png)\n", 43 | "\n", 44 | "![](https://user-images.githubusercontent.com/1651790/182025007-634b0098-61a6-4c0c-b061-7f2f74b9755c.png)" 45 | ] 46 | }, 47 | { 48 | "cell_type": "markdown", 49 | "id": "50b96775-69d4-4c80-b083-542afae56e78", 50 | "metadata": {}, 51 | "source": [ 52 | "In fact, @HarrisChu had been working on bringing the Graph-Notebook open-sourced by AWS to enable even better way to query NebulaGraph in Notebook.\n", 53 | "\n", 54 | "https://github.com/HarrisChu/nebula-opencypher-adapter\n", 55 | "\n", 56 | "First, let's install the graph-notebook as extension of Jupyter Notebook.\n", 57 | "\n", 58 | "```bash\n", 59 | "# pin specific versions of required dependencies\n", 60 | "pip install rdflib==5.0.0\n", 61 | "pip install markupsafe==2.0.1\n", 62 | "\n", 63 | "# install the package\n", 64 | "pip install graph-notebook\n", 65 | "```\n", 66 | "\n", 67 | "Then, let's setup @HarrisChu's opencypher proxy to \"man-in-the-middle\" our graphD on space `yelp`:\n", 68 | "\n", 69 | "```bash\n", 70 | "./nebula-opencypher-adapter -a graphd:9669 -s yelp --port 8001\n", 71 | "```" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 8, 77 | "id": "a48c0546-6e62-4dc5-8f2b-f5bf1202ba79", 78 | "metadata": {}, 79 | "outputs": [ 80 | { 81 | "name": "stdout", 82 | "output_type": "stream", 83 | "text": [ 84 | "The graph_notebook.magics extension is already loaded. To reload it, use:\n", 85 | " %reload_ext graph_notebook.magics\n" 86 | ] 87 | } 88 | ], 89 | "source": [ 90 | "%load_ext graph_notebook.magics" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": 9, 96 | "id": "e5a93d2c-65f1-4839-986b-bd72c9d90d4e", 97 | "metadata": {}, 98 | "outputs": [ 99 | { 100 | "name": "stdout", 101 | "output_type": "stream", 102 | "text": [ 103 | "set notebook config to:\n", 104 | "{\n", 105 | " \"host\": \"nebula-up\",\n", 106 | " \"port\": 8001,\n", 107 | " \"proxy_host\": \"\",\n", 108 | " \"proxy_port\": 8182,\n", 109 | " \"ssl\": false,\n", 110 | " \"sparql\": {\n", 111 | " \"path\": \"\"\n", 112 | " },\n", 113 | " \"gremlin\": {\n", 114 | " \"traversal_source\": \"g\"\n", 115 | " }\n", 116 | "}\n" 117 | ] 118 | }, 119 | { 120 | "data": { 121 | "text/plain": [ 122 | "" 123 | ] 124 | }, 125 | "execution_count": 9, 126 | "metadata": {}, 127 | "output_type": "execute_result" 128 | } 129 | ], 130 | "source": [ 131 | "%%graph_notebook_config\n", 132 | "{\n", 133 | " \"host\": \"nebula-up\",\n", 134 | " \"port\": 8001,\n", 135 | " \"ssl\": false,\n", 136 | " \"gremlin\": {\n", 137 | " \"traversal_source\": \"g\"\n", 138 | " }\n", 139 | "}" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": 10, 145 | "id": "c828521f-ce12-4aa9-bfcc-6ec399679bbb", 146 | "metadata": {}, 147 | "outputs": [ 148 | { 149 | "data": { 150 | "application/vnd.jupyter.widget-view+json": { 151 | "model_id": "08b9e2ca28ee4e4ea5409ae92d78a871", 152 | "version_major": 2, 153 | "version_minor": 0 154 | }, 155 | "text/plain": [ 156 | "Tab(children=(Output(layout=Layout(max_height='600px', overflow='scroll', width='100%')), Force(network= Note, it's worth to be mentioned that `node_id_map` is mapping NebulaGraph Vertex_ID to node_id in DGL object." 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": 13, 291 | "id": "463a0608-cb11-4ae4-81c7-614c587d79ef", 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [ 295 | "# load node features to dgl_graph\n", 296 | "for i in range(32):\n", 297 | " dgl_graph.ndata[f\"f{i}\"] = tensor(features[i])\n", 298 | "dgl_graph.ndata['label'] = tensor(features[32])" 299 | ] 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "id": "dce9137c-d080-4c1a-9778-6b75463d8edd", 304 | "metadata": {}, 305 | "source": [ 306 | "And we need to transform it to homogeneous graph as we did during the training" 307 | ] 308 | }, 309 | { 310 | "cell_type": "code", 311 | "execution_count": 14, 312 | "id": "00edae7c-0238-446e-88dc-a998597f690e", 313 | "metadata": {}, 314 | "outputs": [], 315 | "source": [ 316 | "import torch\n", 317 | "\n", 318 | "# to homogeneous graph\n", 319 | "features = []\n", 320 | "for i in range(32):\n", 321 | " features.append(dgl_graph.ndata[f\"f{i}\"])\n", 322 | "\n", 323 | "dgl_graph.ndata['feat'] = torch.stack(features, dim=1)\n", 324 | "\n", 325 | "dgl_graph.edges['shares_restaurant_in_one_month_with'].data['he'] = torch.ones(\n", 326 | " dgl_graph.number_of_edges('shares_restaurant_in_one_month_with'), dtype=torch.float32)\n", 327 | "dgl_graph.edges['shares_restaurant_rating_with'].data['he'] = torch.full(\n", 328 | " (dgl_graph.number_of_edges('shares_restaurant_rating_with'),), 2, dtype=torch.float32)\n", 329 | "dgl_graph.edges['shares_user_with'].data['he'] = torch.full(\n", 330 | " (dgl_graph.number_of_edges('shares_user_with'),), 4, dtype=torch.float32)\n", 331 | "\n", 332 | "\n", 333 | "# heterogeneous graph to heterogeneous graph, keep ndata and edata\n", 334 | "import dgl\n", 335 | "hg = dgl.to_homogeneous(dgl_graph, edata=['he'], ndata=['feat', 'label'])" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "id": "3b6c2787-d27f-4faf-af1e-d5b674f3464a", 341 | "metadata": {}, 342 | "source": [ 343 | "## The Inference API\n", 344 | "\n", 345 | "Then here we finaly can build our `do_inference()` API, where the predict happens with the Model we trained and the SubGraph of any new record." 346 | ] 347 | }, 348 | { 349 | "cell_type": "code", 350 | "execution_count": 15, 351 | "id": "24d251c3-1549-42dc-9e06-5184b4366aae", 352 | "metadata": {}, 353 | "outputs": [], 354 | "source": [ 355 | "def do_inference(device, graph, node_idx, model, batch_size):\n", 356 | " model.eval()\n", 357 | " with torch.no_grad():\n", 358 | " pred = model.inference(graph, device, batch_size) # pred in buffer_device\n", 359 | " return pred[node_idx]" 360 | ] 361 | }, 362 | { 363 | "cell_type": "markdown", 364 | "id": "f78cb847-5201-4290-b551-9a95547a068b", 365 | "metadata": {}, 366 | "source": [ 367 | "Let's call it!" 368 | ] 369 | }, 370 | { 371 | "cell_type": "code", 372 | "execution_count": 17, 373 | "id": "953f04d1-bd13-445e-9142-f2360b568890", 374 | "metadata": {}, 375 | "outputs": [], 376 | "source": [ 377 | "import torch\n", 378 | "import torch.nn as nn\n", 379 | "import torch.nn.functional as F\n", 380 | "import dgl\n", 381 | "import dgl.nn as dglnn\n", 382 | "from dgl.data import FraudDataset\n", 383 | "from dgl.dataloading import DataLoader, NeighborSampler, MultiLayerFullNeighborSampler\n", 384 | "import tqdm\n", 385 | "\n", 386 | "\n", 387 | "from dgl import function as fn\n", 388 | "from dgl.utils import check_eq_shape, expand_as_pair\n", 389 | "\n", 390 | "import json\n", 391 | "from torch import tensor\n", 392 | "from dgl import DGLHeteroGraph, heterograph\n", 393 | "from dgl import function as fn\n", 394 | "from dgl.utils import check_eq_shape, expand_as_pair\n", 395 | "\n", 396 | "class SAGEConv(dglnn.SAGEConv):\n", 397 | " def forward(self, graph, feat, edge_weight=None):\n", 398 | " r\"\"\"\n", 399 | "\n", 400 | " Description\n", 401 | " -----------\n", 402 | " Compute GraphSAGE layer.\n", 403 | "\n", 404 | " Parameters\n", 405 | " ----------\n", 406 | " graph : DGLGraph\n", 407 | " The graph.\n", 408 | " feat : torch.Tensor or pair of torch.Tensor\n", 409 | " If a torch.Tensor is given, it represents the input feature of shape\n", 410 | " :math:`(N, D_{in})`\n", 411 | " where :math:`D_{in}` is size of input feature, :math:`N` is the number of nodes.\n", 412 | " If a pair of torch.Tensor is given, the pair must contain two tensors of shape\n", 413 | " :math:`(N_{in}, D_{in_{src}})` and :math:`(N_{out}, D_{in_{dst}})`.\n", 414 | " edge_weight : torch.Tensor, optional\n", 415 | " Optional tensor on the edge. If given, the convolution will weight\n", 416 | " with regard to the message.\n", 417 | "\n", 418 | " Returns\n", 419 | " -------\n", 420 | " torch.Tensor\n", 421 | " The output feature of shape :math:`(N_{dst}, D_{out})`\n", 422 | " where :math:`N_{dst}` is the number of destination nodes in the input graph,\n", 423 | " :math:`D_{out}` is the size of the output feature.\n", 424 | " \"\"\"\n", 425 | " self._compatibility_check()\n", 426 | " with graph.local_scope():\n", 427 | " if isinstance(feat, tuple):\n", 428 | " feat_src = self.feat_drop(feat[0])\n", 429 | " feat_dst = self.feat_drop(feat[1])\n", 430 | " else:\n", 431 | " feat_src = feat_dst = self.feat_drop(feat)\n", 432 | " if graph.is_block:\n", 433 | " feat_dst = feat_src[:graph.number_of_dst_nodes()]\n", 434 | " msg_fn = fn.copy_src('h', 'm')\n", 435 | " if edge_weight is not None:\n", 436 | " assert edge_weight.shape[0] == graph.number_of_edges()\n", 437 | " graph.edata['_edge_weight'] = edge_weight\n", 438 | " msg_fn = fn.u_mul_e('h', '_edge_weight', 'm')\n", 439 | "\n", 440 | " h_self = feat_dst\n", 441 | "\n", 442 | " # Handle the case of graphs without edges\n", 443 | " if graph.number_of_edges() == 0:\n", 444 | " graph.dstdata['neigh'] = torch.zeros(\n", 445 | " feat_dst.shape[0], self._in_src_feats).to(feat_dst)\n", 446 | "\n", 447 | " # Determine whether to apply linear transformation before message passing A(XW)\n", 448 | " lin_before_mp = self._in_src_feats > self._out_feats\n", 449 | "\n", 450 | " # Message Passing\n", 451 | " if self._aggre_type == 'mean':\n", 452 | " graph.srcdata['h'] = self.fc_neigh(feat_src) if lin_before_mp else feat_src\n", 453 | " # graph.update_all(msg_fn, fn.mean('m', 'neigh'))\n", 454 | " #########################################################################\n", 455 | " # consdier datatype with different weight, g.edata['he'] as weight here\n", 456 | " g.update_all(fn.u_mul_e('h', 'he', 'm'), fn.mean('m', 'h'))\n", 457 | " #########################################################################\n", 458 | " h_neigh = graph.dstdata['neigh']\n", 459 | " if not lin_before_mp:\n", 460 | " h_neigh = self.fc_neigh(h_neigh)\n", 461 | " elif self._aggre_type == 'gcn':\n", 462 | " check_eq_shape(feat)\n", 463 | " graph.srcdata['h'] = self.fc_neigh(feat_src) if lin_before_mp else feat_src\n", 464 | " if isinstance(feat, tuple): # heterogeneous\n", 465 | " graph.dstdata['h'] = self.fc_neigh(feat_dst) if lin_before_mp else feat_dst\n", 466 | " else:\n", 467 | " if graph.is_block:\n", 468 | " graph.dstdata['h'] = graph.srcdata['h'][:graph.num_dst_nodes()]\n", 469 | " else:\n", 470 | " graph.dstdata['h'] = graph.srcdata['h']\n", 471 | " graph.update_all(msg_fn, fn.sum('m', 'neigh'))\n", 472 | " graph.update_all(fn.copy_e('he', 'm'), fn.sum('m', 'neigh'))\n", 473 | " # divide in_degrees\n", 474 | " degs = graph.in_degrees().to(feat_dst)\n", 475 | " h_neigh = (graph.dstdata['neigh'] + graph.dstdata['h']) / (degs.unsqueeze(-1) + 1)\n", 476 | " if not lin_before_mp:\n", 477 | " h_neigh = self.fc_neigh(h_neigh)\n", 478 | " elif self._aggre_type == 'pool':\n", 479 | " graph.srcdata['h'] = F.relu(self.fc_pool(feat_src))\n", 480 | " graph.update_all(msg_fn, fn.max('m', 'neigh'))\n", 481 | " graph.update_all(fn.copy_e('he', 'm'), fn.max('m', 'neigh'))\n", 482 | " h_neigh = self.fc_neigh(graph.dstdata['neigh'])\n", 483 | " elif self._aggre_type == 'lstm':\n", 484 | " graph.srcdata['h'] = feat_src\n", 485 | " graph.update_all(msg_fn, self._lstm_reducer)\n", 486 | " h_neigh = self.fc_neigh(graph.dstdata['neigh'])\n", 487 | " else:\n", 488 | " raise KeyError('Aggregator type {} not recognized.'.format(self._aggre_type))\n", 489 | "\n", 490 | " # GraphSAGE GCN does not require fc_self.\n", 491 | " if self._aggre_type == 'gcn':\n", 492 | " rst = h_neigh\n", 493 | " else:\n", 494 | " rst = self.fc_self(h_self) + h_neigh\n", 495 | "\n", 496 | " # bias term\n", 497 | " if self.bias is not None:\n", 498 | " rst = rst + self.bias\n", 499 | "\n", 500 | " # activation\n", 501 | " if self.activation is not None:\n", 502 | " rst = self.activation(rst)\n", 503 | " # normalization\n", 504 | " if self.norm is not None:\n", 505 | " rst = self.norm(rst)\n", 506 | " return rst\n", 507 | "\n", 508 | "\n", 509 | "class SAGE(nn.Module):\n", 510 | " def __init__(self, in_size, hid_size, out_size):\n", 511 | " super().__init__()\n", 512 | " self.layers = nn.ModuleList()\n", 513 | " # three-layer GraphSAGE-mean\n", 514 | " self.layers.append(dglnn.SAGEConv(in_size, hid_size, 'mean'))\n", 515 | " self.layers.append(dglnn.SAGEConv(hid_size, hid_size, 'mean'))\n", 516 | " self.layers.append(dglnn.SAGEConv(hid_size, out_size, 'mean'))\n", 517 | " self.dropout = nn.Dropout(0.5)\n", 518 | " self.hid_size = hid_size\n", 519 | " self.out_size = out_size\n", 520 | "\n", 521 | " def forward(self, blocks, x):\n", 522 | " h = x\n", 523 | " for l, (layer, block) in enumerate(zip(self.layers, blocks)):\n", 524 | " h = layer(block, h)\n", 525 | " if l != len(self.layers) - 1:\n", 526 | " h = F.relu(h)\n", 527 | " h = self.dropout(h)\n", 528 | " return h\n", 529 | "\n", 530 | " def inference(self, g, device, batch_size):\n", 531 | " \"\"\"Conduct layer-wise inference to get all the node embeddings.\"\"\"\n", 532 | " feat = g.ndata['feat']\n", 533 | " sampler = MultiLayerFullNeighborSampler(1, prefetch_node_feats=['feat'])\n", 534 | " dataloader = DataLoader(\n", 535 | " g, torch.arange(g.num_nodes()).to(g.device), sampler, device=device,\n", 536 | " batch_size=batch_size, shuffle=False, drop_last=False,\n", 537 | " num_workers=0)\n", 538 | " buffer_device = torch.device('cpu')\n", 539 | " pin_memory = (buffer_device != device)\n", 540 | "\n", 541 | " for l, layer in enumerate(self.layers):\n", 542 | " y = torch.empty(\n", 543 | " g.num_nodes(), self.hid_size if l != len(self.layers) - 1 else self.out_size,\n", 544 | " device=buffer_device, pin_memory=pin_memory)\n", 545 | " feat = feat.to(device)\n", 546 | " for input_nodes, output_nodes, blocks in tqdm.tqdm(dataloader):\n", 547 | " x = feat[input_nodes]\n", 548 | " h = layer(blocks[0], x) # len(blocks) = 1\n", 549 | " if l != len(self.layers) - 1:\n", 550 | " h = F.relu(h)\n", 551 | " h = self.dropout(h)\n", 552 | " # by design, our output nodes are contiguous\n", 553 | " y[output_nodes[0]:output_nodes[-1]+1] = h.to(buffer_device)\n", 554 | " feat = y\n", 555 | " return y" 556 | ] 557 | }, 558 | { 559 | "cell_type": "code", 560 | "execution_count": 22, 561 | "id": "39d0b6ae-6263-4b01-b7a2-6bfec68e716e", 562 | "metadata": {}, 563 | "outputs": [ 564 | { 565 | "name": "stderr", 566 | "output_type": "stream", 567 | "text": [ 568 | "100%|██████████| 1/1 [00:00<00:00, 12.46it/s]\n", 569 | "100%|██████████| 1/1 [00:00<00:00, 122.68it/s]\n", 570 | "100%|██████████| 1/1 [00:00<00:00, 133.84it/s]\n" 571 | ] 572 | } 573 | ], 574 | "source": [ 575 | "import os\n", 576 | "import urllib.request as urllib2\n", 577 | "import gzip\n", 578 | "\n", 579 | "\n", 580 | "node_idx = node_id_map[vertex_id]\n", 581 | "batch_size = 4096\n", 582 | "device = torch.device('cpu')\n", 583 | "\n", 584 | "\n", 585 | "MODEL_LOCAL_PATH = \"fraud_d.model\"\n", 586 | "\n", 587 | "# load model from online gzip file\n", 588 | "DEFAULT_MODEL_URL = \"https://github.com/wey-gu/NebulaGraph-Fraud-Detection-GNN/releases/download/v0.0.1/fraud_d.model.gz\"\n", 589 | "\n", 590 | "def load_model(url):\n", 591 | " if not os.path.exists(MODEL_LOCAL_PATH):\n", 592 | " # Read the file inside the .gz archive located at url\n", 593 | " with urllib2.urlopen(url) as response:\n", 594 | " with gzip.GzipFile(fileobj=response) as uncompressed:\n", 595 | " file_content = uncompressed.read()\n", 596 | " # write to file in binary mode 'wb'\n", 597 | " with open(MODEL_LOCAL_PATH, 'wb') as f:\n", 598 | " f.write(file_content)\n", 599 | " model.load_state_dict(torch.load(MODEL_LOCAL_PATH))\n", 600 | " return model\n", 601 | "\n", 602 | "\n", 603 | "model = SAGE(32, 256, 2).to(device)\n", 604 | "model = load_model(os.environ.get('NG_MODEL_URL', DEFAULT_MODEL_URL))\n", 605 | "\n", 606 | "\n", 607 | "result = do_inference(device, hg, node_idx, model, batch_size)" 608 | ] 609 | }, 610 | { 611 | "cell_type": "markdown", 612 | "id": "d83cb66d-4bd1-48a6-a293-f13039d77ae4", 613 | "metadata": {}, 614 | "source": [ 615 | "Let's see its Accuracy:" 616 | ] 617 | }, 618 | { 619 | "cell_type": "code", 620 | "execution_count": 24, 621 | "id": "81c5fa0e-b240-4ba8-9f89-af8780eb3d7b", 622 | "metadata": {}, 623 | "outputs": [ 624 | { 625 | "name": "stdout", 626 | "output_type": "stream", 627 | "text": [ 628 | "Collecting torchmetrics\n", 629 | " Downloading torchmetrics-0.9.3-py3-none-any.whl (419 kB)\n", 630 | "\u001b[K |████████████████████████████████| 419 kB 1.6 MB/s eta 0:00:01\n", 631 | "\u001b[?25hRequirement already satisfied: numpy>=1.17.2 in /home/azureuser/.local/lib/python3.8/site-packages (from torchmetrics) (1.23.1)\n", 632 | "Requirement already satisfied: torch>=1.3.1 in /home/azureuser/.local/lib/python3.8/site-packages (from torchmetrics) (1.12.0)\n", 633 | "Requirement already satisfied: packaging in /home/azureuser/.local/lib/python3.8/site-packages (from torchmetrics) (21.3)\n", 634 | "Requirement already satisfied: typing-extensions in /home/azureuser/.local/lib/python3.8/site-packages (from torch>=1.3.1->torchmetrics) (4.3.0)\n", 635 | "Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /home/azureuser/.local/lib/python3.8/site-packages (from packaging->torchmetrics) (3.0.9)\n", 636 | "Installing collected packages: torchmetrics\n", 637 | "Successfully installed torchmetrics-0.9.3\n" 638 | ] 639 | }, 640 | { 641 | "name": "stderr", 642 | "output_type": "stream", 643 | "text": [ 644 | "100%|██████████| 1/1 [00:00<00:00, 42.85it/s]\n", 645 | "100%|██████████| 1/1 [00:00<00:00, 54.13it/s]\n", 646 | "100%|██████████| 1/1 [00:00<00:00, 104.02it/s]" 647 | ] 648 | }, 649 | { 650 | "name": "stdout", 651 | "output_type": "stream", 652 | "text": [ 653 | "Test Accuracy 0.9688\n" 654 | ] 655 | }, 656 | { 657 | "name": "stderr", 658 | "output_type": "stream", 659 | "text": [ 660 | "\n" 661 | ] 662 | } 663 | ], 664 | "source": [ 665 | "!pip install torchmetrics\n", 666 | "import torchmetrics.functional as MF\n", 667 | "\n", 668 | "\n", 669 | "def test_inference(device, graph, nid, model, batch_size):\n", 670 | " model.eval()\n", 671 | " with torch.no_grad():\n", 672 | " pred = model.inference(graph, device, batch_size) # pred in buffer_device\n", 673 | " pred = pred[nid]\n", 674 | " label = graph.ndata['label'][nid].to(pred.device)\n", 675 | " return MF.accuracy(pred, label)\n", 676 | "\n", 677 | "node_idx = torch.tensor(list(node_id_map.values()))\n", 678 | "acc = test_inference(device, hg, node_idx, model, batch_size=4096)\n", 679 | "print(\"Test Accuracy {:.4f}\".format(acc.item()))" 680 | ] 681 | }, 682 | { 683 | "cell_type": "code", 684 | "execution_count": null, 685 | "id": "7c504241-5463-4b94-b0cc-0fb98cf858d3", 686 | "metadata": {}, 687 | "outputs": [], 688 | "source": [] 689 | } 690 | ], 691 | "metadata": { 692 | "kernelspec": { 693 | "display_name": "Python 3", 694 | "language": "python", 695 | "name": "python3" 696 | }, 697 | "language_info": { 698 | "codemirror_mode": { 699 | "name": "ipython", 700 | "version": 3 701 | }, 702 | "file_extension": ".py", 703 | "mimetype": "text/x-python", 704 | "name": "python", 705 | "nbconvert_exporter": "python", 706 | "pygments_lexer": "ipython3", 707 | "version": "3.8.10" 708 | } 709 | }, 710 | "nbformat": 4, 711 | "nbformat_minor": 5 712 | } 713 | -------------------------------------------------------------------------------- /notebooks/Train_GraphSAGE.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "0c4ddb97-eee9-4a14-a6a6-7e086b9ee0b0", 6 | "metadata": {}, 7 | "source": [ 8 | "# Model Training on NebulaGraph\n", 9 | "" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "id": "6dc18097-1780-454b-95f5-f39345a555a7", 15 | "metadata": {}, 16 | "source": [ 17 | "# Prepare for Playground\n", 18 | "\n", 19 | "Now we are setting up a NebulaGraph Playground with a Graph of Yelp-Fraud being loaded.\n", 20 | "\n", 21 | "> Data downloader and importing are located [here](https://github.com/wey-gu/nebulagraph-yelp-frauddetection)\n", 22 | "\n", 23 | "```bash\n", 24 | "# Deploy NebulaGraph Cluster\n", 25 | "curl -fsSL nebula-up.siwei.io/install.sh | bash\n", 26 | "\n", 27 | "# Clone the data downloader Repo\n", 28 | "git clone https://github.com/wey-gu/nebulagraph-yelp-frauddetection && cd nebulagraph-yelp-frauddetection\n", 29 | "\n", 30 | "# Run downloader\n", 31 | "python3 -m pip install -r requirements.txt\n", 32 | "python3 data_download.py\n", 33 | "\n", 34 | "# Ingest to NebulaGraph Cluster\n", 35 | "docker run --rm -ti \\\n", 36 | " --network=nebula-net \\\n", 37 | " -v ${PWD}/yelp_nebulagraph_importer.yaml:/root/importer.yaml \\\n", 38 | " -v ${PWD}/data:/root \\\n", 39 | " vesoft/nebula-importer:v3.1.0 \\\n", 40 | " --config /root/importer.yaml\n", 41 | "```\n" 42 | ] 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "id": "bbc2832b-d2b2-4463-95b2-d8b2399c0e83", 47 | "metadata": {}, 48 | "source": [ 49 | "## Load Graph in NebulaGraph Database into DGL\n", 50 | "\n", 51 | "We are leveraging [Nebula-DGL](https://github.com/wey-gu/nebula-dgl) here.\n", 52 | "\n", 53 | "> You could follow this procedure to setup the Jupyter Playground with connection to our NebulaGraph Playground\n", 54 | "\n", 55 | "```bash\n", 56 | "git clone https://github.com/wey-gu/nebula-dgl.git\n", 57 | "cd nebula-dgl\n", 58 | "\n", 59 | "# Run Jupyter in a Container with network: `nebula-net`\n", 60 | "\n", 61 | "docker run -it --name dgl -p 8888:8888 --network nebula-net \\\n", 62 | " -v \"$PWD\":/home/jovyan/work jupyter/datascience-notebook \\\n", 63 | " start-notebook.sh --NotebookApp.token='nebulagraph'\n", 64 | "```\n", 65 | "\n", 66 | "Access the notebook at http://localhost:8888/lab/tree/work?token=nebulagraph and create a new notebook.\n", 67 | "\n", 68 | "```bash\n", 69 | "# change directory to nebula-dgl for installation\n", 70 | "cd work\n", 71 | "```" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 27, 77 | "id": "2ec214b2-2fc5-4ff0-846c-be30db5bba4d", 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "#!python3 -m pip install git+https://github.com/vesoft-inc/nebula-python.git@8c328c534413b04ccecfd42e64ce6491e09c6ca8\n", 82 | "#!python3 -m pip install .\n", 83 | "\n", 84 | "import torch\n", 85 | "import torch.nn as nn\n", 86 | "import torch.nn.functional as F\n", 87 | "import torchmetrics.functional as MF\n", 88 | "import dgl\n", 89 | "import dgl.nn as dglnn\n", 90 | "from dgl.data import FraudDataset\n", 91 | "from dgl.dataloading import DataLoader, NeighborSampler, MultiLayerFullNeighborSampler\n", 92 | "import tqdm\n", 93 | "\n", 94 | "\n", 95 | "from dgl import function as fn\n", 96 | "from dgl.utils import check_eq_shape, expand_as_pair\n", 97 | "\n", 98 | "import json\n", 99 | "from torch import tensor\n", 100 | "from dgl import DGLHeteroGraph, heterograph\n", 101 | "\n", 102 | "from nebula3.gclient.net import ConnectionPool\n", 103 | "from nebula3.Config import Config\n", 104 | "\n" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "id": "4607e4f2-ecd8-4b8d-a713-38baa6e1f63b", 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "import urllib\n", 115 | "import yaml\n", 116 | "\n", 117 | "from nebula_dgl import NebulaLoader\n", 118 | "\n", 119 | "# load feature_mapper from yaml file\n", 120 | "#with open('nebulagraph_yelp_dgl_mapper.yaml', 'r') as f:\n", 121 | "# feature_mapper = yaml.safe_load(f)\n", 122 | "\n", 123 | "# load feature_mapper from URL\n", 124 | "mapper_url = \"https://raw.githubusercontent.com/wey-gu/nebulagraph-yelp-frauddetection/main/nebulagraph_yelp_dgl_mapper.yaml\"\n", 125 | "f = urllib.request.urlopen(mapper_url)\n", 126 | "feature_mapper = yaml.safe_load(f)\n", 127 | "\n", 128 | "nebula_config = {\n", 129 | " \"graph_hosts\": [\n", 130 | " ('graphd', 9669),\n", 131 | " ('graphd1', 9669),\n", 132 | " ('graphd2', 9669)\n", 133 | " ],\n", 134 | " \"user\": \"root\",\n", 135 | " \"password\": \"nebula\",\n", 136 | "}\n", 137 | "\n", 138 | "nebula_loader = NebulaLoader(nebula_config, feature_mapper)\n", 139 | "g = nebula_loader.load()\n", 140 | "# This will take some time" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "id": "75a235cb-b065-4d31-b11d-5fd5170fd4c6", 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "# When needed, we could save and load the graph, too.\n", 151 | "# from dgl.data.utils import save_graphs, load_graphs\n", 152 | "# save_graphs(\"./data.bin\", [g])\n", 153 | "# g = load_graphs(\"./data.bin\")[0][0]\n", 154 | "\n", 155 | "g = g.to('cpu')\n", 156 | "device = torch.device('cpu')" 157 | ] 158 | }, 159 | { 160 | "cell_type": "markdown", 161 | "id": "e38790cc-f3b2-4470-a746-36e3712245de", 162 | "metadata": {}, 163 | "source": [ 164 | "## Split Data from Graph\n", 165 | "\n", 166 | "We need to split the Graph for training into train, validation and test sets" 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": null, 172 | "id": "cdd06bbd-73f1-4f48-acbe-68f613d66de4", 173 | "metadata": {}, 174 | "outputs": [], 175 | "source": [ 176 | "import pandas as pd\n", 177 | "import numpy as np\n", 178 | "from sklearn.model_selection import train_test_split\n", 179 | "\n", 180 | "# features are g.ndata['f0'], g.ndata['f1'], g.ndata['f2'], ... g.ndata['f31']\n", 181 | "# label is in g.ndata['is_fraud']\n", 182 | "\n", 183 | "# concatenate all features\n", 184 | "features = []\n", 185 | "for i in range(32):\n", 186 | " features.append(g.ndata['f' + str(i)])\n", 187 | "\n", 188 | "g.ndata['feat'] = torch.stack(features, dim=1)\n", 189 | "g.ndata['label'] = g.ndata['is_fraud']\n", 190 | "# numpy array as an index of range n\n", 191 | "\n", 192 | "idx = torch.tensor(np.arange(g.number_of_nodes()), device=device, dtype=torch.int64)\n", 193 | "\n", 194 | "# split based on value distribution of label: the property \"is_fraud\", which is a binary variable.\n", 195 | "X_train_and_val_idx, X_test_idx, y_train_and_val, y_test = train_test_split(\n", 196 | " idx, g.ndata['is_fraud'], test_size=0.2, random_state=42, stratify=g.ndata['is_fraud'])\n", 197 | "\n", 198 | "# split train and val\n", 199 | "X_train_idx, X_val_idx, y_train, y_val = train_test_split(\n", 200 | " X_train_and_val_idx, y_train_and_val, test_size=0.2, random_state=42, stratify=y_train_and_val)\n", 201 | "\n", 202 | "# list of index to mask\n", 203 | "train_mask = torch.zeros(g.number_of_nodes(), dtype=torch.bool)\n", 204 | "train_mask[X_train_idx] = True\n", 205 | "\n", 206 | "val_mask = torch.zeros(g.number_of_nodes(), dtype=torch.bool)\n", 207 | "val_mask[X_val_idx] = True\n", 208 | "\n", 209 | "test_mask = torch.zeros(g.number_of_nodes(), dtype=torch.bool)\n", 210 | "test_mask[X_test_idx] = True\n", 211 | "\n", 212 | "g.ndata['train_mask'] = train_mask\n", 213 | "g.ndata['val_mask'] = val_mask\n", 214 | "g.ndata['test_mask'] = test_mask" 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "id": "3a72f648-f547-43d1-82e3-768babd75a32", 220 | "metadata": {}, 221 | "source": [ 222 | "## Transform the Heterogeneous Graph to Homogeneous Graph\n", 223 | "\n", 224 | "Vanilla GraphSAGE is designed to handle Homogeneous only.\n", 225 | "\n", 226 | "Now, Yelp dataset comes with one type of node and three types of edges, we could make the type of edge as edge features, it could be a (3-1) 2-D feature or one bit-wise feature:\n", 227 | "\n", 228 | "```yaml\n", 229 | "shares_restaurant_in_one_month_with: 1, b\"001\"\n", 230 | "shares_restaurant_rating_with: 2, b\"010\"\n", 231 | "shares_user_with: 4, b\"100\"\n", 232 | "```\n", 233 | "\n", 234 | "> Note after the transformation, `hg.edata['_TYPE']` comes with [0, 1, 2] referring to https://docs.dgl.ai/en/0.9.x/generated/dgl.to_homogeneous.html , we dont want this as 0 could not be used as an edge weight, we'll see why later." 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": null, 240 | "id": "cbe32bb9-220d-4c6c-925c-9cb0e9cb9dc6", 241 | "metadata": {}, 242 | "outputs": [], 243 | "source": [ 244 | "# edge types\n", 245 | "g.etypes\n", 246 | "\n", 247 | "# let's set type info. into edge feature\n", 248 | "g.edges['shares_restaurant_in_one_month_with'].data['he'] = torch.ones(\n", 249 | " g.number_of_edges('shares_restaurant_in_one_month_with'), dtype=torch.int64)\n", 250 | "g.edges['shares_restaurant_rating_with'].data['he'] = torch.full(\n", 251 | " (g.number_of_edges('shares_restaurant_rating_with'),), 2, dtype=torch.int64)\n", 252 | "g.edges['shares_user_with'].data['he'] = torch.full(\n", 253 | " (g.number_of_edges('shares_user_with'),), 4, dtype=torch.int64)\n", 254 | "\n", 255 | "# check it\n", 256 | "\n", 257 | "g.edata['he']" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "id": "12013936-7bc1-4c57-85c9-970f0a8ec9c2", 264 | "metadata": {}, 265 | "outputs": [], 266 | "source": [ 267 | "# ref https://discuss.dgl.ai/t/how-to-convert-from-a-heterogeneous-graph-to-a-homogeneous-graph-with-data/2764\n", 268 | "\n", 269 | "# transform, keep `he` as `edata`\n", 270 | "\n", 271 | "hg = dgl.to_homogeneous(\n", 272 | " g,\n", 273 | " edata=['he'],\n", 274 | " ndata=['feat', 'label', 'train_mask', 'val_mask', 'test_mask'])\n", 275 | "\n", 276 | "# ref https://docs.dgl.ai/en/latest/guide/graph-heterogeneous.html?highlight=to_homogeneous#converting-heterogeneous-graphs-to-homogeneous-graphs" 277 | ] 278 | }, 279 | { 280 | "cell_type": "markdown", 281 | "id": "7afe9e21-7f11-4800-bdc6-97e404452a8c", 282 | "metadata": {}, 283 | "source": [ 284 | "## Add edge feature to GraphSAGE\n", 285 | "\n", 286 | "The vanilla implementation of GraphSAGE doesn't consider edge feature during message passing.\n", 287 | "\n", 288 | "There is an example here: https://github.com/dmlc/dgl/tree/master/examples/pytorch/graphsage\n", 289 | "\n", 290 | "In our case, we have to override the `forward` function of `SAGEConv` in one of the two ways:\n", 291 | "\n", 292 | "a. copy edge feature, too in `update_all()`\n", 293 | "```diff\n", 294 | " graph.update_all(msg_fn, fn.mean('m', 'neigh'))\n", 295 | "+ graph.update_all(fn.copy_e('he', 'm'), fn.mean('m', 'neigh'))\n", 296 | "- h_neigh = graph.dstdata['neigh']\n", 297 | "+ h_neigh = torch.cat((graph.dstdata['neigh'], graph.dstdata['neigh_e'].reshape(-1, 1)), 1)\n", 298 | "```\n", 299 | "> Note, besides the above changes, we need to take care of the dimension, too.\n", 300 | "\n", 301 | "b. make edge feature `he` into edge weight during the `update_all()`\n", 302 | "\n", 303 | "```diff\n", 304 | "- graph.update_all(msg_fn, fn.mean('m', 'neigh'))\n", 305 | "+ # consdier datatype with different weight, g.edata['he'] as weight here\n", 306 | "+ g.update_all(fn.u_mul_e('h', 'he', 'm'), fn.mean('m', 'h'))\n", 307 | "```\n", 308 | "\n", 309 | "And here we will go for option b." 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": null, 315 | "id": "ef1d2a78-ed5e-44e5-a9b3-04966a935bd3", 316 | "metadata": {}, 317 | "outputs": [], 318 | "source": [ 319 | "from dgl import function as fn\n", 320 | "from dgl.utils import check_eq_shape, expand_as_pair\n", 321 | "\n", 322 | "class SAGEConv(dglnn.SAGEConv):\n", 323 | " def forward(self, graph, feat, edge_weight=None):\n", 324 | " r\"\"\"\n", 325 | "\n", 326 | " Description\n", 327 | " -----------\n", 328 | " Compute GraphSAGE layer.\n", 329 | "\n", 330 | " Parameters\n", 331 | " ----------\n", 332 | " graph : DGLGraph\n", 333 | " The graph.\n", 334 | " feat : torch.Tensor or pair of torch.Tensor\n", 335 | " If a torch.Tensor is given, it represents the input feature of shape\n", 336 | " :math:`(N, D_{in})`\n", 337 | " where :math:`D_{in}` is size of input feature, :math:`N` is the number of nodes.\n", 338 | " If a pair of torch.Tensor is given, the pair must contain two tensors of shape\n", 339 | " :math:`(N_{in}, D_{in_{src}})` and :math:`(N_{out}, D_{in_{dst}})`.\n", 340 | " edge_weight : torch.Tensor, optional\n", 341 | " Optional tensor on the edge. If given, the convolution will weight\n", 342 | " with regard to the message.\n", 343 | "\n", 344 | " Returns\n", 345 | " -------\n", 346 | " torch.Tensor\n", 347 | " The output feature of shape :math:`(N_{dst}, D_{out})`\n", 348 | " where :math:`N_{dst}` is the number of destination nodes in the input graph,\n", 349 | " :math:`D_{out}` is the size of the output feature.\n", 350 | " \"\"\"\n", 351 | " self._compatibility_check()\n", 352 | " with graph.local_scope():\n", 353 | " if isinstance(feat, tuple):\n", 354 | " feat_src = self.feat_drop(feat[0])\n", 355 | " feat_dst = self.feat_drop(feat[1])\n", 356 | " else:\n", 357 | " feat_src = feat_dst = self.feat_drop(feat)\n", 358 | " if graph.is_block:\n", 359 | " feat_dst = feat_src[:graph.number_of_dst_nodes()]\n", 360 | " msg_fn = fn.copy_src('h', 'm')\n", 361 | " if edge_weight is not None:\n", 362 | " assert edge_weight.shape[0] == graph.number_of_edges()\n", 363 | " graph.edata['_edge_weight'] = edge_weight\n", 364 | " msg_fn = fn.u_mul_e('h', '_edge_weight', 'm')\n", 365 | "\n", 366 | " h_self = feat_dst\n", 367 | "\n", 368 | " # Handle the case of graphs without edges\n", 369 | " if graph.number_of_edges() == 0:\n", 370 | " graph.dstdata['neigh'] = torch.zeros(\n", 371 | " feat_dst.shape[0], self._in_src_feats).to(feat_dst)\n", 372 | "\n", 373 | " # Determine whether to apply linear transformation before message passing A(XW)\n", 374 | " lin_before_mp = self._in_src_feats > self._out_feats\n", 375 | "\n", 376 | " # Message Passing\n", 377 | " if self._aggre_type == 'mean':\n", 378 | " graph.srcdata['h'] = self.fc_neigh(feat_src) if lin_before_mp else feat_src\n", 379 | " # graph.update_all(msg_fn, fn.mean('m', 'neigh'))\n", 380 | " #########################################################################\n", 381 | " # consdier datatype with different weight, g.edata['he'] as weight here\n", 382 | " g.update_all(fn.u_mul_e('h', 'he', 'm'), fn.mean('m', 'h'))\n", 383 | " #########################################################################\n", 384 | " h_neigh = graph.dstdata['neigh']\n", 385 | " if not lin_before_mp:\n", 386 | " h_neigh = self.fc_neigh(h_neigh)\n", 387 | " elif self._aggre_type == 'gcn':\n", 388 | " check_eq_shape(feat)\n", 389 | " graph.srcdata['h'] = self.fc_neigh(feat_src) if lin_before_mp else feat_src\n", 390 | " if isinstance(feat, tuple): # heterogeneous\n", 391 | " graph.dstdata['h'] = self.fc_neigh(feat_dst) if lin_before_mp else feat_dst\n", 392 | " else:\n", 393 | " if graph.is_block:\n", 394 | " graph.dstdata['h'] = graph.srcdata['h'][:graph.num_dst_nodes()]\n", 395 | " else:\n", 396 | " graph.dstdata['h'] = graph.srcdata['h']\n", 397 | " graph.update_all(msg_fn, fn.sum('m', 'neigh'))\n", 398 | " graph.update_all(fn.copy_e('he', 'm'), fn.sum('m', 'neigh'))\n", 399 | " # divide in_degrees\n", 400 | " degs = graph.in_degrees().to(feat_dst)\n", 401 | " h_neigh = (graph.dstdata['neigh'] + graph.dstdata['h']) / (degs.unsqueeze(-1) + 1)\n", 402 | " if not lin_before_mp:\n", 403 | " h_neigh = self.fc_neigh(h_neigh)\n", 404 | " elif self._aggre_type == 'pool':\n", 405 | " graph.srcdata['h'] = F.relu(self.fc_pool(feat_src))\n", 406 | " graph.update_all(msg_fn, fn.max('m', 'neigh'))\n", 407 | " graph.update_all(fn.copy_e('he', 'm'), fn.max('m', 'neigh'))\n", 408 | " h_neigh = self.fc_neigh(graph.dstdata['neigh'])\n", 409 | " elif self._aggre_type == 'lstm':\n", 410 | " graph.srcdata['h'] = feat_src\n", 411 | " graph.update_all(msg_fn, self._lstm_reducer)\n", 412 | " h_neigh = self.fc_neigh(graph.dstdata['neigh'])\n", 413 | " else:\n", 414 | " raise KeyError('Aggregator type {} not recognized.'.format(self._aggre_type))\n", 415 | "\n", 416 | " # GraphSAGE GCN does not require fc_self.\n", 417 | " if self._aggre_type == 'gcn':\n", 418 | " rst = h_neigh\n", 419 | " else:\n", 420 | " rst = self.fc_self(h_self) + h_neigh\n", 421 | "\n", 422 | " # bias term\n", 423 | " if self.bias is not None:\n", 424 | " rst = rst + self.bias\n", 425 | "\n", 426 | " # activation\n", 427 | " if self.activation is not None:\n", 428 | " rst = self.activation(rst)\n", 429 | " # normalization\n", 430 | " if self.norm is not None:\n", 431 | " rst = self.norm(rst)\n", 432 | " return rst" 433 | ] 434 | }, 435 | { 436 | "cell_type": "markdown", 437 | "id": "c23eecf5-8370-41a5-87d8-857e6a028faf", 438 | "metadata": {}, 439 | "source": [ 440 | "## Defination of the GraphSAGE module" 441 | ] 442 | }, 443 | { 444 | "cell_type": "code", 445 | "execution_count": null, 446 | "id": "f0edd05a-a7f8-418f-8aa4-aa94fd676d96", 447 | "metadata": {}, 448 | "outputs": [], 449 | "source": [ 450 | "class SAGE(nn.Module):\n", 451 | " def __init__(self, in_size, hid_size, out_size):\n", 452 | " super().__init__()\n", 453 | " self.layers = nn.ModuleList()\n", 454 | " # three-layer GraphSAGE-mean\n", 455 | " self.layers.append(dglnn.SAGEConv(in_size, hid_size, 'mean'))\n", 456 | " self.layers.append(dglnn.SAGEConv(hid_size, hid_size, 'mean'))\n", 457 | " self.layers.append(dglnn.SAGEConv(hid_size, out_size, 'mean'))\n", 458 | " self.dropout = nn.Dropout(0.5)\n", 459 | " self.hid_size = hid_size\n", 460 | " self.out_size = out_size\n", 461 | "\n", 462 | " def forward(self, blocks, x):\n", 463 | " h = x\n", 464 | " for l, (layer, block) in enumerate(zip(self.layers, blocks)):\n", 465 | " h = layer(block, h)\n", 466 | " if l != len(self.layers) - 1:\n", 467 | " h = F.relu(h)\n", 468 | " h = self.dropout(h)\n", 469 | " return h\n", 470 | "\n", 471 | " def inference(self, g, device, batch_size):\n", 472 | " \"\"\"Conduct layer-wise inference to get all the node embeddings.\"\"\"\n", 473 | " feat = g.ndata['feat']\n", 474 | " sampler = MultiLayerFullNeighborSampler(1, prefetch_node_feats=['feat'])\n", 475 | " dataloader = DataLoader(\n", 476 | " g, torch.arange(g.num_nodes()).to(g.device), sampler, device=device,\n", 477 | " batch_size=batch_size, shuffle=False, drop_last=False,\n", 478 | " num_workers=0)\n", 479 | " buffer_device = torch.device('cpu')\n", 480 | " pin_memory = (buffer_device != device)\n", 481 | "\n", 482 | " for l, layer in enumerate(self.layers):\n", 483 | " y = torch.empty(\n", 484 | " g.num_nodes(), self.hid_size if l != len(self.layers) - 1 else self.out_size,\n", 485 | " device=buffer_device, pin_memory=pin_memory)\n", 486 | " feat = feat.to(device)\n", 487 | " for input_nodes, output_nodes, blocks in tqdm.tqdm(dataloader):\n", 488 | " x = feat[input_nodes]\n", 489 | " h = layer(blocks[0], x) # len(blocks) = 1\n", 490 | " if l != len(self.layers) - 1:\n", 491 | " h = F.relu(h)\n", 492 | " h = self.dropout(h)\n", 493 | " # by design, our output nodes are contiguous\n", 494 | " y[output_nodes[0]:output_nodes[-1]+1] = h.to(buffer_device)\n", 495 | " feat = y\n", 496 | " return y" 497 | ] 498 | }, 499 | { 500 | "cell_type": "markdown", 501 | "id": "86ec295f-5142-42cd-b3b2-ef415e95a5fc", 502 | "metadata": {}, 503 | "source": [ 504 | "## Define train, inference functions" 505 | ] 506 | }, 507 | { 508 | "cell_type": "code", 509 | "execution_count": null, 510 | "id": "48dbd9dc-287b-4504-b3b7-771eb85bbb1d", 511 | "metadata": {}, 512 | "outputs": [], 513 | "source": [ 514 | "def evaluate(model, graph, dataloader):\n", 515 | " model.eval()\n", 516 | " ys = []\n", 517 | " y_hats = []\n", 518 | " for it, (input_nodes, output_nodes, blocks) in enumerate(dataloader):\n", 519 | " with torch.no_grad():\n", 520 | " x = blocks[0].srcdata['feat']\n", 521 | " ys.append(blocks[-1].dstdata['label'])\n", 522 | " y_hats.append(model(blocks, x))\n", 523 | " return MF.accuracy(torch.cat(y_hats), torch.cat(ys))\n", 524 | "\n", 525 | "def layerwise_infer(device, graph, nid, model, batch_size):\n", 526 | " model.eval()\n", 527 | " with torch.no_grad():\n", 528 | " pred = model.inference(graph, device, batch_size) # pred in buffer_device\n", 529 | " pred = pred[nid]\n", 530 | " label = graph.ndata['label'][nid].to(pred.device)\n", 531 | " return MF.accuracy(pred, label)\n", 532 | "\n", 533 | "def train(device, g, model, train_idx, val_idx):\n", 534 | " # create sampler & dataloader\n", 535 | " sampler = NeighborSampler([10, 10, 10], # fanout for [layer-0, layer-1, layer-2]\n", 536 | " prefetch_node_feats=['feat'],\n", 537 | " prefetch_labels=['label'])\n", 538 | " use_uva = False\n", 539 | " train_dataloader = DataLoader(g, train_idx, sampler, device=device,\n", 540 | " batch_size=1024, shuffle=True,\n", 541 | " drop_last=False, num_workers=0,\n", 542 | " use_uva=use_uva)\n", 543 | "\n", 544 | " val_dataloader = DataLoader(g, val_idx, sampler, device=device,\n", 545 | " batch_size=1024, shuffle=True,\n", 546 | " drop_last=False, num_workers=0,\n", 547 | " use_uva=use_uva)\n", 548 | "\n", 549 | " opt = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=5e-4)\n", 550 | " \n", 551 | " for epoch in range(10):\n", 552 | " model.train()\n", 553 | " total_loss = 0\n", 554 | " for it, (input_nodes, output_nodes, blocks) in enumerate(train_dataloader):\n", 555 | " x = blocks[0].srcdata['feat']\n", 556 | " y = blocks[-1].dstdata['label']\n", 557 | " y_hat = model(blocks, x)\n", 558 | " loss = F.cross_entropy(y_hat, y)\n", 559 | " opt.zero_grad()\n", 560 | " loss.backward()\n", 561 | " opt.step()\n", 562 | " total_loss += loss.item()\n", 563 | " acc = evaluate(model, g, val_dataloader)\n", 564 | " print(\"Epoch {:05d} | Loss {:.4f} | Accuracy {:.4f} \"\n", 565 | " .format(epoch, total_loss / (it+1), acc.item()))" 566 | ] 567 | }, 568 | { 569 | "cell_type": "markdown", 570 | "id": "73780004-921b-459a-bacf-e35f0ae19919", 571 | "metadata": {}, 572 | "source": [ 573 | "## Train and Verify the model" 574 | ] 575 | }, 576 | { 577 | "cell_type": "code", 578 | "execution_count": null, 579 | "id": "45ac1c79-697f-4c30-a1ed-1bbd6eccddd3", 580 | "metadata": {}, 581 | "outputs": [], 582 | "source": [ 583 | "# create GraphSAGE model\n", 584 | "in_size = hg.ndata['feat'].shape[1]\n", 585 | "out_size = 2\n", 586 | "model = SAGE(in_size, 256, out_size).to(device)\n", 587 | "\n", 588 | "# model training\n", 589 | "print('Training...')\n", 590 | "train(device, hg, model, X_train_idx, X_val_idx)\n", 591 | "\n", 592 | "# test the model\n", 593 | "print('Testing...')\n", 594 | "\n", 595 | "acc = layerwise_infer(device, hg, X_test_idx, model, batch_size=4096)\n", 596 | "print(\"Test Accuracy {:.4f}\".format(acc.item()))" 597 | ] 598 | }, 599 | { 600 | "cell_type": "markdown", 601 | "id": "c44f47ca-535e-4944-a4be-1857b10a3609", 602 | "metadata": {}, 603 | "source": [ 604 | "## Save the model\n", 605 | "\n", 606 | "We could save the model into file and load it in other processes." 607 | ] 608 | }, 609 | { 610 | "cell_type": "code", 611 | "execution_count": null, 612 | "id": "074020fc-62cb-4668-82cc-0f0bdd9af823", 613 | "metadata": {}, 614 | "outputs": [], 615 | "source": [ 616 | "# save model\n", 617 | "torch.save(model.state_dict(), \"fraud_d.model\")\n", 618 | "\n", 619 | "# load model, think of it's on our Fraud_detection_API_backend_service\n", 620 | "device = torch.device('cpu')\n", 621 | "model = SAGE(32, 256, 2).to(device)\n", 622 | "model.load_state_dict(torch.load(\"fraud_d.model\"))\n", 623 | "\n", 624 | "# think of this is a query, I know, hg is not, but just an example.\n", 625 | "layerwise_infer(device, hg, X_test_idx, model, batch_size=4096)" 626 | ] 627 | }, 628 | { 629 | "cell_type": "markdown", 630 | "id": "ffabb904-51af-4bf9-b952-c4bff91e7419", 631 | "metadata": {}, 632 | "source": [ 633 | "## Inductive Learning\n", 634 | "\n", 635 | "The reason I choose to use GraphSAGE was due to it's a very simple model for Inductive Learning, which means we could predict **Graph with NEW nodes**, so that the Fraud Detection system could be done online.\n", 636 | "\n", 637 | "But in above example, the data we were verifying the model isn't new, to prove that coudl be done, here is the example on redo the dataset split:\n" 638 | ] 639 | }, 640 | { 641 | "cell_type": "code", 642 | "execution_count": null, 643 | "id": "6f678c4d-20d3-4dcb-b8bf-75b059eb3c8f", 644 | "metadata": {}, 645 | "outputs": [], 646 | "source": [ 647 | "# Inductive Learning, our test dataset are new nodes and new edges\n", 648 | "hg_train = hg.subgraph(torch.cat([X_train_idx, X_val_idx]))\n", 649 | "\n", 650 | "# model training\n", 651 | "print('Training...')\n", 652 | "train(device, hg_train, model, torch.arange(X_train_idx.shape[0]), torch.arange(X_train_idx.shape[0], hg_train.num_nodes()))\n", 653 | "\n", 654 | "# test the model\n", 655 | "print('Testing...')\n", 656 | "\n", 657 | "hg_test = hg.subgraph(torch.cat([X_test_idx]))\n", 658 | "\n", 659 | "sg_X_test_idx = torch.arange(hg_test.num_nodes())\n", 660 | "\n", 661 | "acc = layerwise_infer(device, hg_test, sg_X_test_idx, model, batch_size=4096)\n", 662 | "print(\"Test Accuracy {:.4f}\".format(acc.item()))" 663 | ] 664 | }, 665 | { 666 | "cell_type": "markdown", 667 | "id": "b881791e-dff9-48d9-a64d-837de1fbeb70", 668 | "metadata": {}, 669 | "source": [ 670 | "From above new dataset spliting, we could see the graph: `hg_test` to be predicted are brand new data with no intersection with the training data/graph.\n", 671 | "\n", 672 | "And it worked fine, too😁." 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": null, 678 | "id": "37042321-b942-4f3c-9c12-2d048abe33b8", 679 | "metadata": {}, 680 | "outputs": [], 681 | "source": [] 682 | } 683 | ], 684 | "metadata": { 685 | "kernelspec": { 686 | "display_name": "Python 3", 687 | "language": "python", 688 | "name": "python3" 689 | }, 690 | "language_info": { 691 | "codemirror_mode": { 692 | "name": "ipython", 693 | "version": 3 694 | }, 695 | "file_extension": ".py", 696 | "mimetype": "text/x-python", 697 | "name": "python", 698 | "nbconvert_exporter": "python", 699 | "pygments_lexer": "ipython3", 700 | "version": "3.8.10" 701 | } 702 | }, 703 | "nbformat": 4, 704 | "nbformat_minor": 5 705 | } 706 | --------------------------------------------------------------------------------