├── README.md ├── model.py ├── data_preprocess.py ├── utils.py ├── main.py ├── data_splitter.py ├── output_result.py └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # Wyze Rule Recommendation Example Code 2 | ## Introduction 3 | This is the example code for the Wyze rule recommendation challenge hosted in HF (https://huggingface.co/spaces/competitions/wyze-rule-recommendation), which reproduces the GraphRule algorithm for this dataset. The GraphRule is the centralized training of [FedRule](https://arxiv.org/abs/2211.06812). This is only for demonstration purposes and serves as a simple baseline model. We do not perform any hyperparameter optimization. The key steps implemented here include: 4 | 5 | - Loading and preprocessing the Wyze rule and device datasets 6 | - Constructing user-rule and user-device graphs from the data 7 | - Applying graph neural network propagation and embedding techniques 8 | - Training a model on the centralized graph embeddings 9 | - Using the model to predict missing rules for new users 10 | 11 | This is intended as a sample starter code to illustrate one modeling approach for the competition. There are many other innovative modeling techniques that could be applied to effectively recommend personalized rules on this dataset. 12 | 13 | ## Usage 14 | ```cli 15 | python data_preprocess.py 16 | 17 | python main.py 18 | 19 | python output_result 20 | ``` 21 | -------------------------------------------------------------------------------- /model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from dgl.nn import SAGEConv, GraphConv, GATConv 5 | import dgl.function as fn 6 | 7 | class GraphSAGE(nn.Module): 8 | def __init__(self, in_feats, h_feats, dropout = 0.5): 9 | super(GraphSAGE, self).__init__() 10 | self.conv1 = SAGEConv(in_feats, h_feats, 'mean') 11 | self.dropout = nn.Dropout(dropout) 12 | self.conv2 = SAGEConv(h_feats, h_feats, 'mean') 13 | 14 | def forward(self, g, in_feat): 15 | h = self.conv1(g, in_feat) 16 | h = self.dropout(h) #dropout before relu 17 | h = F.relu(h) 18 | h = self.conv2(g, h) 19 | return h 20 | 21 | class GCN(nn.Module): 22 | def __init__(self, in_feats, h_feats, dropout = 0.5): 23 | super(GCN, self).__init__() 24 | self.conv1 = GraphConv(in_feats, h_feats, allow_zero_in_degree = True) 25 | self.dropout = nn.Dropout(dropout) 26 | self.conv2 = GraphConv(h_feats, h_feats, allow_zero_in_degree = True) 27 | 28 | def forward(self, g, in_feat): 29 | h = self.conv1(g, in_feat) 30 | h = self.dropout(h) #dropout before relu 31 | h = F.relu(h) 32 | h = self.conv2(g, h) 33 | return h 34 | 35 | class GAT(nn.Module): 36 | def __init__(self, in_feats, h_feats, dropout = 0.5): 37 | super(GAT, self).__init__() 38 | self.conv1 = GATConv(in_feats, h_feats, 1, allow_zero_in_degree = True) 39 | self.dropout = nn.Dropout(dropout) 40 | self.conv2 = GATConv(h_feats, h_feats, 1, allow_zero_in_degree = True) 41 | 42 | def forward(self, g, in_feat): 43 | h = self.conv1(g, in_feat) 44 | h = h.reshape(h.shape[0],h.shape[2]) #1 attention head 45 | h = self.dropout(h) #dropout before relu 46 | h = F.relu(h) 47 | h = self.conv2(g, h) 48 | h = h.reshape(h.shape[0],h.shape[2]) #1 attention head 49 | return h 50 | 51 | class MLPPredictor(nn.Module): 52 | def __init__(self, h_feats): 53 | super().__init__() 54 | self.W1 = nn.Linear(h_feats * 2, h_feats) 55 | self.W2 = nn.Linear(h_feats, 1) 56 | self.sig = nn.Sigmoid() 57 | 58 | def apply_edges(self, edges): 59 | h = torch.cat([edges.src['h'], edges.dst['h']], 1) 60 | return {'score': self.sig(self.W2(F.relu(self.W1(h)))).squeeze(1)} 61 | 62 | def forward(self, g, h): 63 | with g.local_scope(): 64 | g.ndata['h'] = h 65 | g.apply_edges(self.apply_edges) 66 | return g.edata['score'] 67 | 68 | class HeteroDotProductPredictor(nn.Module): 69 | def forward(self, graph, h, etype): 70 | with graph.local_scope(): 71 | graph.ndata['h'] = h # assigns 'h' of all node types in one shot 72 | graph.apply_edges(fn.u_dot_v('h', 'h', 'score'), etype=etype) 73 | return graph.edges[etype].data['score'] 74 | 75 | 76 | class HeteroMLPPredictor(nn.Module): 77 | def __init__(self, h_feats, edge_types, dropout = 0.5): 78 | super().__init__() 79 | self.W1 = nn.Linear(h_feats * 2, h_feats) 80 | self.dropout = nn.Dropout(dropout) 81 | self.W2 = nn.Linear(h_feats, edge_types) 82 | self.sig = nn.Sigmoid() 83 | def apply_edges(self, edges): 84 | h = torch.cat([edges.src['h'], edges.dst['h']], 1) 85 | return {'score': self.sig(self.W2(F.relu(self.dropout(self.W1(h)))))} # dim: edge_types 86 | 87 | def forward(self, g, h): 88 | with g.local_scope(): 89 | g.ndata['h'] = h 90 | g.apply_edges(self.apply_edges) 91 | return g.edata['score'] -------------------------------------------------------------------------------- /data_preprocess.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | from huggingface_hub import login 5 | # enter your token of huggingface 6 | # https://huggingface.co/docs/hub/security-tokens 7 | login(token="XXXXXXXXXXXXXX") 8 | 9 | from datasets import load_dataset 10 | import collections 11 | import torch 12 | import torch.nn.functional as F 13 | import dgl 14 | import json 15 | 16 | train_device = load_dataset("wyzelabs/RuleRecommendation", data_files="train_device.csv") 17 | train_rule = load_dataset("wyzelabs/RuleRecommendation", data_files="train_rule.csv") 18 | test_device = load_dataset("wyzelabs/RuleRecommendation", data_files="test_device.csv") 19 | test_rule = load_dataset("wyzelabs/RuleRecommendation", data_files="test_rule.csv") 20 | 21 | print("start preprocessing") 22 | df = train_rule['train'].to_pandas() 23 | all_devices = {'Camera': 0, 24 | 'ClimateSensor': 1, 25 | 'Cloud': 2, 26 | 'ContactSensor': 3, 27 | 'Irrigation': 4, 28 | 'LeakSensor': 5, 29 | 'Light': 6, 30 | 'LightStrip': 7, 31 | 'Lock': 8, 32 | 'MeshLight': 9, 33 | 'MotionSensor': 10, 34 | 'OutdoorPlug': 11, 35 | 'Plug': 12, 36 | 'RobotVacuum': 13, 37 | 'Switch': 14, 38 | 'Thermostat': 15} 39 | 40 | all_trigger_actions = collections.defaultdict(int) 41 | for index, row in df.iterrows(): 42 | all_trigger_actions[str(row['trigger_state_id'])+' '+str(row['action_id'])] += 1 43 | 44 | #filter some action 45 | for index in list(all_trigger_actions.keys()): 46 | if all_trigger_actions[index] <= 10: 47 | all_trigger_actions.pop(index) 48 | 49 | 50 | for index, key in enumerate(all_trigger_actions): 51 | all_trigger_actions[key] = index 52 | 53 | class_num = len(set(all_devices.values())) 54 | one_hot_matrix = F.one_hot(torch.tensor(list(range(class_num))), num_classes=class_num) 55 | 56 | user_device_id_to_node_id = collections.defaultdict(dict) 57 | user_number_of_devices = collections.defaultdict(int) 58 | 59 | user_graphs = collections.defaultdict(dgl.DGLGraph) 60 | 61 | count = 0 62 | for index, row in df.iterrows(): 63 | trigger_action = str(row['trigger_state_id'])+' '+str(row['action_id']) 64 | if trigger_action in all_trigger_actions and row['trigger_device'] in all_devices and row['action_device'] in all_devices: 65 | 66 | if row['trigger_device_id'] not in user_device_id_to_node_id[row["user_id"]]: 67 | #assign id to the current device for supporting multiple devices with the same type 68 | user_device_id_to_node_id[row["user_id"]][row['trigger_device_id']] = user_number_of_devices[row["user_id"]] 69 | user_number_of_devices[row["user_id"]] += 1 70 | 71 | device = all_devices[row['trigger_device']] 72 | user_graphs[row["user_id"]].add_nodes(1, data = {'feat':one_hot_matrix[device].reshape(1,-1)}) 73 | 74 | if row['action_device_id'] not in user_device_id_to_node_id[row["user_id"]]: 75 | user_device_id_to_node_id[row["user_id"]][row['action_device_id']] = user_number_of_devices[row["user_id"]] 76 | user_number_of_devices[row["user_id"]] += 1 77 | 78 | device = all_devices[row['action_device']] 79 | user_graphs[row["user_id"]].add_nodes(1, data = {'feat':one_hot_matrix[device].reshape(1,-1)}) 80 | node1 = user_device_id_to_node_id[row["user_id"]][row['trigger_device_id']] 81 | node2 = user_device_id_to_node_id[row["user_id"]][row['action_device_id']] 82 | #the file contains same rules but with different devices 83 | user_graphs[row["user_id"]].add_edges(node1, node2, data = {'etype':torch.tensor([all_trigger_actions[trigger_action]])}) #directed 84 | count += 1 85 | if count > 1000: 86 | break 87 | 88 | #filter, remove graph with devices < 3 89 | for i in list(user_graphs.keys()): 90 | if user_graphs[i].number_of_nodes() <= 2: 91 | user_graphs.pop(i) 92 | 93 | print("save processed data") 94 | 95 | user_id_dict = dict() 96 | for i in user_graphs.keys(): 97 | user_id_dict[i] = i 98 | 99 | with open('user_id_dict.json', 'w') as f: 100 | json.dump(user_id_dict, f) 101 | 102 | dgl.save_graphs("usergraphs.bin", list(user_graphs.values())) 103 | 104 | with open('all_trigger_actions.json', 'w') as f: 105 | json.dump(all_trigger_actions, f) 106 | 107 | with open('all_devices.json', 'w') as f: 108 | json.dump(all_devices, f) 109 | 110 | with open('user_device_id_to_node_id.json', 'w') as f: 111 | json.dump(user_device_id_to_node_id, f) 112 | 113 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | from sklearn.metrics import roc_auc_score 4 | import numpy as np 5 | import networkx as nx 6 | import dgl 7 | from pathlib import Path 8 | import glob 9 | import re 10 | 11 | def compute_loss(pos_score, neg_score): 12 | scores = torch.cat([pos_score, neg_score]) 13 | labels = torch.cat([torch.ones(pos_score.shape[0]), torch.zeros(neg_score.shape[0])]).to(pos_score.device) 14 | return F.binary_cross_entropy(scores, labels) 15 | 16 | def compute_auc(pos_score, neg_score): 17 | scores = torch.cat([pos_score, neg_score]).cpu().numpy() 18 | scores = np.nan_to_num(scores, nan=0, posinf=0, neginf=0) 19 | #deal with overflow 20 | labels = torch.cat( 21 | [torch.ones(pos_score.shape[0]), torch.zeros(neg_score.shape[0])]).numpy() 22 | return roc_auc_score(labels, scores) 23 | 24 | def compute_mr(predictions, test_g): 25 | _, indices = torch.sort(predictions, descending = True) 26 | hits = (test_g.edata['etype'].view(-1, 1) == indices).nonzero()[:,-1] 27 | return hits.float().mean() 28 | 29 | def test_global_model(train_gs, train_pos_gs, train_neg_gs, test_pos_gs, test_neg_gs, global_model, global_pred): 30 | global_model.eval() 31 | global_pred.eval() 32 | total_loss = 0 33 | total_AUC = 0 34 | total_pos_MR = 0 35 | 36 | total_train_loss = 0 37 | total_train_AUC = 0 38 | total_train_pos_MR = 0 39 | with torch.no_grad(): 40 | for user_index in test_pos_gs: 41 | train_g = train_gs[user_index] 42 | train_pos_g = train_pos_gs[user_index] 43 | train_neg_g = train_neg_gs[user_index] 44 | 45 | h = global_model(train_g, train_g.ndata['feat']) 46 | pos_score = global_pred(train_pos_g, h)[ 47 | list(range(len(train_pos_g.edata['etype']))), train_pos_g.edata['etype']] 48 | neg_score = global_pred(train_neg_g, h)[ 49 | list(range(len(train_neg_g.edata['etype']))), train_neg_g.edata['etype']] 50 | 51 | total_train_loss += compute_loss(pos_score, neg_score) 52 | total_train_AUC += compute_auc(pos_score, neg_score) 53 | total_train_pos_MR += compute_mr(global_pred(train_pos_g, h), train_pos_g) 54 | 55 | test_pos_g = test_pos_gs[user_index] 56 | test_neg_g = test_neg_gs[user_index] 57 | 58 | pos_score = global_pred(test_pos_g, h)[ 59 | list(range(len(test_pos_g.edata['etype']))), test_pos_g.edata['etype']] 60 | 61 | neg_score = global_pred(test_neg_g, h)[ 62 | list(range(len(test_neg_g.edata['etype']))), test_neg_g.edata['etype']] 63 | 64 | total_loss += compute_loss(pos_score, neg_score) 65 | total_pos_MR += compute_mr(global_pred(test_pos_g, h), test_pos_g) 66 | total_AUC += compute_auc(pos_score, neg_score) 67 | 68 | print('Global Test Loss', total_loss / len(test_pos_gs)) 69 | print('Global Test AUC', total_AUC / len(test_pos_gs)) 70 | print('Global Test Positive MR', float(total_pos_MR / len(test_pos_gs))) 71 | 72 | return float(total_train_loss / len(train_pos_gs)), total_train_AUC / len(train_pos_gs), float( 73 | total_train_pos_MR / len(train_pos_gs)), float(total_loss / len(test_pos_gs)), total_AUC / len( 74 | test_pos_gs), float(total_pos_MR / len(test_pos_gs)) 75 | 76 | 77 | def get_recommendation_result(G, model, pred, topk): 78 | Complete_G = nx.complete_graph(list(G.nodes()), nx.MultiDiGraph()) 79 | Complete_G = dgl.from_networkx(Complete_G) 80 | 81 | model.eval() 82 | pred.eval() 83 | with torch.no_grad(): 84 | h = model(G, G.ndata['feat']) 85 | # predictor, use node embeddings of source node and target node as input, predict the link probability of current edge 86 | # need a complete graph as input 87 | scores = pred(Complete_G, h) 88 | L = [] 89 | edges = Complete_G.edges() 90 | for i in range(scores.shape[0]): 91 | for j in range(scores.shape[1]): 92 | L.append([int(edges[0][i]), int(edges[1][i]), j, float(scores[i][j])]) 93 | L = torch.tensor(sorted(L, key=lambda e: e[3], reverse=True))[:, :-1] 94 | 95 | return L[:topk] 96 | 97 | def increment_dir(dir, comment=''): 98 | # Increments a directory runs/exp1 --> runs/exp2_comment 99 | n = 0 # number 100 | dir = str(Path(dir)) # os-agnostic 101 | dirs = sorted(glob.glob(dir + '*')) # directories 102 | if dirs: 103 | matches = [re.search(r"exp(\d+)", d) for d in dirs] 104 | idxs = [int(m.groups()[0]) for m in matches if m] 105 | if idxs: 106 | n = max(idxs) + 1 # increment 107 | return dir + str(n) + ('_' + comment if comment else '') -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | import os 5 | import yaml 6 | from pathlib import Path 7 | import torch 8 | import argparse 9 | import dgl 10 | import json 11 | import itertools 12 | import numpy as np 13 | from torch.utils.tensorboard import SummaryWriter 14 | 15 | from data_splitter import split_data 16 | from utils import compute_loss, increment_dir, test_global_model, get_recommendation_result 17 | from model import GraphSAGE, GCN, GAT, HeteroMLPPredictor 18 | 19 | 20 | if __name__=="__main__": 21 | parser = argparse.ArgumentParser() 22 | parser.add_argument('-d', '--dataset', default='wyze', type=str) 23 | parser.add_argument('-l', '--logdir', default='./runs', type=str) 24 | parser.add_argument('-lr', '--learning_rate', default=0.1, type=float) 25 | parser.add_argument('-c', '--num_comms',default=100, type=int) # num_iterations in centralized training 26 | parser.add_argument('-m', '--model_type', default='graphsage', type=str) 27 | parser.add_argument('-neg', '--more_negative', action='store_true') 28 | 29 | seed = 0 30 | dgl.seed(seed) 31 | torch.manual_seed(seed) 32 | np.random.seed(seed) 33 | 34 | args = parser.parse_args() 35 | 36 | args.log_dir = increment_dir(Path(args.logdir) / 'exp') 37 | args.log_dir += args.dataset + "_" + 'center' 38 | os.makedirs(args.log_dir) 39 | yaml_file = str(Path(args.log_dir) / "args.yaml") 40 | with open(yaml_file, 'w') as out: 41 | yaml.dump(args.__dict__, out, default_flow_style=False) 42 | args.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 43 | 44 | tb_writer = SummaryWriter(log_dir=args.log_dir) 45 | 46 | print("load data") 47 | user_graphs_list, _ = dgl.load_graphs("usergraphs.bin") 48 | user_id_dict = json.load(open('user_id_dict.json', 'r')) 49 | user_graphs = dict() 50 | user_ids = list(user_id_dict.keys()) 51 | 52 | for i in range(len(user_ids)): 53 | user_graphs[user_ids[i]] = user_graphs_list[i] 54 | 55 | all_trigger_actions = json.load(open('all_trigger_actions.json', 'r')) 56 | all_devices = json.load(open('all_devices.json', 'r')) 57 | user_device_id_to_node_id = json.load(open('user_device_id_to_node_id.json', 'r')) 58 | 59 | train_gs, train_pos_gs, train_neg_gs, test_pos_gs, test_neg_gs = split_data(user_graphs, all_trigger_actions, args.more_negative) 60 | if args.model_type == 'graphsage': 61 | model = GraphSAGE(len(set(all_devices.values())), 32).to(args.device) #feature dim: len(set(all_devices.values())) 62 | elif args.model_type == 'gcn': 63 | model = GCN(len(set(all_devices.values())), 32).to(args.device) 64 | elif args.model_type == 'gat': 65 | model = GAT(len(set(all_devices.values())), 32).to(args.device) 66 | 67 | pred = HeteroMLPPredictor(32, len(set(all_trigger_actions.values()))).to(args.device) 68 | optimizer = torch.optim.Adam(itertools.chain(model.parameters(), pred.parameters()), lr=args.learning_rate) 69 | 70 | print("start training") 71 | for e in range(args.num_comms): 72 | model.train() 73 | pred.train() 74 | loss = None 75 | for user_index in train_gs: 76 | train_g = train_gs[user_index] 77 | train_pos_g = train_pos_gs[user_index] 78 | train_neg_g = train_neg_gs[user_index] 79 | 80 | h = model(train_g, train_g.ndata['feat']) 81 | pos_score = pred(train_pos_g, h)[list(range(len(train_pos_g.edata['etype']))), train_pos_g.edata['etype']] 82 | neg_score = pred(train_neg_g, h)[list(range(len(train_neg_g.edata['etype']))), train_neg_g.edata['etype']] 83 | if loss == None: 84 | loss = compute_loss(pos_score, neg_score) 85 | else: 86 | loss += compute_loss(pos_score, neg_score) 87 | 88 | tb_writer.add_scalar('Train/Loss',loss.item() / len(train_gs),e-1) #-1 since it is before backward 89 | optimizer.zero_grad() 90 | loss.backward() 91 | optimizer.step() 92 | 93 | print('In epoch {}, loss: {}'.format(e-1, loss.item() / len(train_gs))) 94 | 95 | if (e + 1) % 5 == 0: 96 | global_train_loss, global_train_AUC, global_train_MR, global_test_loss, global_test_AUC, global_test_MR = test_global_model(train_gs, train_pos_gs, train_neg_gs, test_pos_gs, test_neg_gs, model, pred) 97 | 98 | tb_writer.add_scalar('Global Train/Loss', global_train_loss, e) 99 | tb_writer.add_scalar('Global Train/AUC', global_train_AUC, e) 100 | tb_writer.add_scalar('Global Train/POS_MR', global_train_MR, e) 101 | 102 | tb_writer.add_scalar('Global Test/Loss', global_test_loss, e) 103 | tb_writer.add_scalar('Global Test/AUC', global_test_AUC, e) 104 | tb_writer.add_scalar('Global Test/POS_MR', global_test_MR, e) 105 | 106 | torch.save(model.state_dict(), args.dataset + "central_model_" + args.model_type) 107 | torch.save(pred.state_dict(), args.dataset + "central_pred_" + args.model_type) -------------------------------------------------------------------------------- /data_splitter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import dgl 3 | import torch 4 | import torch.nn.functional as F 5 | 6 | def split_data(user_graphs, all_trigger_actions, more_neg = False): 7 | train_gs = dict() 8 | train_pos_gs = dict() 9 | train_neg_gs = dict() 10 | test_pos_gs = dict() 11 | test_neg_gs = dict() 12 | 13 | for user_index in user_graphs: 14 | g = user_graphs[user_index] 15 | 16 | # Split edge set for training and testing 17 | u, v = g.edges() 18 | 19 | # eids = np.arange(g.number_of_edges()) 20 | eids = torch.randperm(g.number_of_edges()).to(g.device) 21 | test_size = int(len(eids) * 0.2) 22 | train_size = g.number_of_edges() - test_size 23 | test_pos_u, test_pos_v = u[eids[:test_size]], v[eids[:test_size]] 24 | train_pos_u, train_pos_v = u[eids[test_size:]], v[eids[test_size:]] 25 | 26 | test_pos_edata = g.edata['etype'][eids[:test_size]] 27 | train_pos_edata = g.edata['etype'][eids[test_size:]] 28 | 29 | if len(test_pos_u) == 0: 30 | continue #remove some graph with few edges 31 | 32 | # Find all negative edges and split them for training and testing 33 | adj = g.adjacency_matrix().to(g.device) 34 | adj_neg = 1 - adj.to_dense() - torch.eye(g.number_of_nodes()).to(g.device) #no self loop, filtered before 35 | neg_inds = torch.nonzero(adj_neg) 36 | neg_edata = torch.randint(len(set(all_trigger_actions.values())), (neg_inds.shape[0],)).to(g.device) 37 | 38 | 39 | #add the same edge in dataset but different edge type for negative sampleing 40 | neg_u_different_type = u 41 | neg_v_different_type = v 42 | #neg_sampling 43 | if more_neg == True: 44 | for i in range(10): 45 | neg_u_different_type = torch.cat((neg_u_different_type, u), 0) 46 | neg_v_different_type = torch.cat((neg_v_different_type, v), 0) 47 | 48 | neg_edge_fetures = torch.randint(len(set(all_trigger_actions.values())), (len(neg_u_different_type),)).to(g.device) 49 | 50 | for i in range(len(u)): 51 | same_edges_with_different_type = g.edata['etype'][g.edge_ids(u[i],v[i], return_uv = True)[2]] 52 | while neg_edge_fetures[i] in same_edges_with_different_type: 53 | neg_edge_fetures[i] = np.random.choice(len(set(all_trigger_actions.values())), 1)[0] 54 | 55 | neg_u = torch.cat((neg_inds[:,0], neg_u_different_type), 0) 56 | neg_v = torch.cat((neg_inds[:,1], neg_v_different_type), 0) 57 | neg_edata = torch.cat((neg_edata, neg_edge_fetures), 0) 58 | 59 | #print(len(neg_u), len(neg_edata)) 60 | 61 | if len(neg_u) == 0: 62 | continue #some graphs are too small, become complete graphs, skip it 63 | 64 | #neg_eids = list(range(len(neg_u)))#np.random.choice(len(neg_u), len(neg_u)) #### super negative sampling, many edges 65 | 66 | neg_eids = torch.randperm(len(neg_u))[:g.number_of_edges()] 67 | 68 | test_neg_edata = neg_edata[neg_eids[:test_size]] 69 | train_neg_edata = neg_edata[neg_eids[test_size:]] 70 | 71 | test_neg_u, test_neg_v = neg_u[neg_eids[:test_size]], neg_v[neg_eids[:test_size]] 72 | train_neg_u, train_neg_v = neg_u[neg_eids[test_size:]], neg_v[neg_eids[test_size:]] 73 | 74 | train_pos_g = dgl.graph((train_pos_u, train_pos_v), num_nodes=g.number_of_nodes()) 75 | train_pos_g.edata['etype'] = train_pos_edata 76 | 77 | train_neg_g = dgl.graph((train_neg_u, train_neg_v), num_nodes=g.number_of_nodes()) 78 | train_neg_g.edata['etype'] = train_neg_edata 79 | 80 | test_pos_g = dgl.graph((test_pos_u, test_pos_v), num_nodes=g.number_of_nodes()) 81 | test_pos_g.edata['etype'] = test_pos_edata 82 | 83 | test_neg_g = dgl.graph((test_neg_u, test_neg_v), num_nodes=g.number_of_nodes()) 84 | test_neg_g.edata['etype'] = test_neg_edata 85 | 86 | train_g = dgl.remove_edges(g, eids[:test_size]) 87 | 88 | train_g.ndata['feat'] = train_g.ndata['feat'].float() 89 | 90 | 91 | #add efeat 92 | edge_types = len(set(all_trigger_actions.values())) 93 | one_hot_matrix = F.one_hot(torch.tensor(list(range(edge_types))), num_classes=edge_types).to(g.device) 94 | train_g.edata['efeat'] = one_hot_matrix[train_g.edata['etype']] 95 | train_pos_g.edata['efeat'] = one_hot_matrix[train_pos_g.edata['etype']] 96 | train_neg_g.edata['efeat'] = one_hot_matrix[train_neg_g.edata['etype']] 97 | test_pos_g.edata['efeat'] = one_hot_matrix[test_pos_g.edata['etype']] 98 | test_neg_g.edata['efeat'] = one_hot_matrix[test_neg_g.edata['etype']] 99 | 100 | 101 | train_gs[user_index] = train_g 102 | train_pos_gs[user_index] = train_pos_g 103 | train_neg_gs[user_index] = train_neg_g 104 | test_pos_gs[user_index] = test_pos_g 105 | test_neg_gs[user_index] = test_neg_g 106 | return train_gs, train_pos_gs, train_neg_gs, test_pos_gs, test_neg_gs 107 | -------------------------------------------------------------------------------- /output_result.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | # In[1]: 5 | 6 | 7 | from huggingface_hub import login 8 | login(token="XXXXXXXXXXXXXX") 9 | from datasets import load_dataset 10 | import collections 11 | import torch 12 | import torch.nn.functional as F 13 | import dgl 14 | import json 15 | import numpy as np 16 | import networkx as nx 17 | from model import GraphSAGE, GCN, GAT, HeteroMLPPredictor 18 | 19 | test_rule = load_dataset("wyzelabs/RuleRecommendation", data_files="test_rule.csv") 20 | test_rule_df = test_rule['train'].to_pandas() 21 | 22 | 23 | all_trigger_actions = json.load(open('all_trigger_actions.json', 'r')) 24 | all_devices = json.load(open('all_devices.json', 'r')) 25 | 26 | 27 | class_num = len(set(all_devices.values())) 28 | one_hot_matrix = F.one_hot(torch.tensor(list(range(class_num))), num_classes=class_num) 29 | 30 | test_device_df = load_dataset("wyzelabs/RuleRecommendation", data_files="test_device.csv")['train'].to_pandas() 31 | 32 | 33 | user_device_id_to_node_id = collections.defaultdict(dict) 34 | user_number_of_devices = collections.defaultdict(int) 35 | test_user_graphs = collections.defaultdict(dgl.DGLGraph) 36 | 37 | ''' 38 | # add devices that have no rules 39 | for index, row in test_device_df.iterrows(): 40 | user_device_id_to_node_id[row["user_id"]][row['device_id']] = user_number_of_devices[row["user_id"]] 41 | user_number_of_devices[row["user_id"]] += 1 42 | 43 | device_type = all_devices[row['device_model']] 44 | test_user_graphs[row["user_id"]].add_nodes(1, data = {'feat':one_hot_matrix[device_type].reshape(1,-1)}) 45 | ''' 46 | 47 | for index, row in test_rule_df.iterrows(): 48 | trigger_action = str(row['trigger_state_id'])+' '+str(row['action_id']) 49 | if trigger_action in all_trigger_actions and row['trigger_device'] in all_devices and row['action_device'] in all_devices: 50 | if row['trigger_device_id'] not in user_device_id_to_node_id[row["user_id"]]: 51 | #assign id to the current device for supporting multiple devices with the same type 52 | user_device_id_to_node_id[row["user_id"]][row['trigger_device_id']] = user_number_of_devices[row["user_id"]] 53 | user_number_of_devices[row["user_id"]] += 1 54 | 55 | device = all_devices[row['trigger_device']] 56 | test_user_graphs[row["user_id"]].add_nodes(1, data = {'feat':one_hot_matrix[device].reshape(1,-1)}) 57 | 58 | if row['action_device_id'] not in user_device_id_to_node_id[row["user_id"]]: 59 | user_device_id_to_node_id[row["user_id"]][row['action_device_id']] = user_number_of_devices[row["user_id"]] 60 | user_number_of_devices[row["user_id"]] += 1 61 | 62 | device = all_devices[row['action_device']] 63 | test_user_graphs[row["user_id"]].add_nodes(1, data = {'feat':one_hot_matrix[device].reshape(1,-1)}) 64 | node1 = user_device_id_to_node_id[row["user_id"]][row['trigger_device_id']] 65 | node2 = user_device_id_to_node_id[row["user_id"]][row['action_device_id']] 66 | #the file contains same rules but with different devices 67 | test_user_graphs[row["user_id"]].add_edges(node1, node2, data = {'etype':torch.tensor([all_trigger_actions[trigger_action]])}) #directed 68 | 69 | model = GraphSAGE(len(set(all_devices.values())), 32) 70 | pred = HeteroMLPPredictor(32, len(set(all_trigger_actions.values()))) 71 | model.load_state_dict(torch.load("wyzecentral_model_graphsage")) 72 | pred.load_state_dict(torch.load("wyzecentral_pred_graphsage")) 73 | 74 | 75 | def get_recommendation_result(G, model, pred, topk, rule_dict=None): 76 | Complete_G = nx.complete_graph(list(G.nodes()), nx.MultiDiGraph()) 77 | Complete_G = dgl.from_networkx(Complete_G) 78 | Complete_G = dgl.add_self_loop(Complete_G) 79 | 80 | model.eval() 81 | pred.eval() 82 | with torch.no_grad(): 83 | h = model(G, G.ndata['feat']) 84 | #predictor, use node embeddings of source node and target node as input, predict the link probability of current edge 85 | #need a complete graph as input 86 | scores = pred(Complete_G, h) 87 | L = [] 88 | edges = Complete_G.edges() 89 | for i in range(scores.shape[0]): 90 | for j in range(scores.shape[1]): 91 | # trigger_device, action_device, trigger_action_pair, score 92 | L.append([int(edges[0][i]), int(edges[1][i]), j, float(scores[i][j])]) 93 | 94 | # rule filter 95 | if rule_dict is not None: 96 | node_transfer = np.argmax(G.ndata['feat'].numpy(), axis = 1) 97 | for i in L: 98 | trigger_device_type = node_transfer[int(i[0])] 99 | action_device_type = node_transfer[int(i[1])] 100 | trigger_action_pair = int(i[2]) 101 | rule = f"{trigger_device_type} {action_device_type} {trigger_action_pair}" 102 | # give more score if the rule in rule_dict 103 | if rule in rule_dict: 104 | i[3] += 1 105 | L = torch.tensor(sorted(L, key= lambda e:e[3], reverse = True))[:,:-1] 106 | 107 | return L[:topk] 108 | 109 | 110 | train_rule = load_dataset("wyzelabs/RuleRecommendation", data_files="train_rule.csv") 111 | train_df = train_rule['train'].to_pandas() 112 | 113 | rule_dict = dict() 114 | for index, row in train_df.iterrows(): 115 | trigger_action = str(row['trigger_state_id'])+' '+str(row['action_id']) 116 | if trigger_action in all_trigger_actions: 117 | current_rule = f"{all_devices[row['trigger_device']]} {all_devices[row['action_device']]} {all_trigger_actions[trigger_action]}" 118 | rule_dict[current_rule] = 1 119 | 120 | 121 | inv_all_trigger_actions_with_id = dict() 122 | for key in all_trigger_actions: 123 | inv_all_trigger_actions_with_id[all_trigger_actions[key]] = key 124 | 125 | a = open("recommended_result.csv", "w") 126 | a.write("user_id,rule,rank\n") 127 | for user_index in test_user_graphs: 128 | test_user_graphs[user_index].ndata['feat'] = test_user_graphs[user_index].ndata['feat'].float() 129 | L = get_recommendation_result(test_user_graphs[user_index], model, pred, topk = 50, rule_dict=rule_dict) 130 | current_user_devices = list(user_device_id_to_node_id[user_index].keys()) 131 | for rank in range(len(L)): 132 | current_rule = L[rank] 133 | trigger_device = current_user_devices[int(current_rule[0])] 134 | action_device = current_user_devices[int(current_rule[1])] 135 | trigger_state, action = inv_all_trigger_actions_with_id[int(current_rule[2])].split(' ') 136 | a.write(f"{user_index},{trigger_device}_{trigger_state}_{action}_{action_device},{rank + 1}\n") 137 | a.close() 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------