-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
51 lines (37 loc) · 1.11 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import random
import numpy as np
import torch
# recommended to seed from 42 to 45
def global_seed(seed=42):
os.environ['PYTHONHASHSEED'] = str(seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
def get_available_device():
device = 'cpu'
if torch.cuda.is_available():
device = 'cuda'
elif torch.backends.mps.is_available():
device = 'mps'
return device
def prepare_padded_seq(seq, max_seq_len):
padded_seq = np.zeros([max_seq_len], dtype=np.int32)
if len(seq) < max_seq_len:
padded_seq[-len(seq):] = seq
else:
padded_seq[:] = seq[-max_seq_len:]
return padded_seq
def sample_negative(seq, num_item):
while True:
item = random.randint(1, num_item)
if item not in seq:
return item
def batch_sample_negative(seq, num_item, neg_num):
closed_set = set()
while len(closed_set) < neg_num:
closed_set.add(sample_negative(seq, num_item))
return list(closed_set)