-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmembership.py
78 lines (63 loc) · 2.18 KB
/
membership.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import pandas as pd
import numpy as np
from sklearn.preprocessing import normalize
class MembershipVector():
def __init__(self, userList, groupNum):
"""
randomly initilize the prob
init the userID and group Probability to a map of user'
Args:
userList: a list of user ID
groupNum: a integer
"""
self.groupNum = groupNum
self.dict = {}
self.userList = userList
for i in userList:
self.dict[i] = np.random.dirichlet(np.ones(groupNum))
def getUserProbByGroup(self, userId, groupId):
"""
Get the probability that the user belongs to this group
"""
return self.dict[userId].tolist()[groupId]
def getProbByUserId(self, userId):
"""
Args:
return group prob list of the input user
"""
return self.dict[userId].tolist()
def getUserByGroup(self, groupId):
"""
Args:
return userID in the input group, group ID starts from 0
"""
groupList=[]
for i in self.userList:
userProb = self.dict[i].tolist()
if userProb.index(max(userProb)) == groupId:
groupList.append(i)
return groupList
def getMeanProbByGroup(self, groupId):
"""P(g) = Sum u∈U Mu(g)/|U|.
"""
sum = 0
for i in self.userList:
userProb = self.dict[i].tolist()
sum += userProb[groupId]
return sum/len(self.userList)
def setProbByGroupUser(self, prob, userId, groupId):
self.dict[userId][groupId] = prob
return
def check_normal(self):
for key in self.dict:
sum_prob = self.dict[key]
if sum_prob != 1:
raise ValueError("The sum of the membership vector should be 1")
def getProbOfUser(self, id):
return self.dict[id]
def normalize(self):
for key in self.dict:
if not (self.dict[key] > 0).all:
raise ValueError("Probability is negative: " + str(self.dict[key]))
for key in self.dict:
self.dict[key] = np.concatenate(normalize(self.dict[key].reshape(1,-1)))