-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
executable file
·203 lines (168 loc) · 5.93 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import pandas as pd
import numpy as np
import scipy.integrate as integrate
import scipy.sparse as sparse
from datetime import datetime
import time
import json
from tqdm import tqdm
def load_raw_df(dataset, data_to_file, data_to_sep):
if dataset in ['amusic', 'acd', 'acna', 'agames']:
return load_amusic_df(data_to_file[dataset])
elif dataset == 'gowalla':
return load_gowalla_df(data_to_file[dataset], data_to_sep[dataset])
elif dataset == 'citeulike':
return load_citeulike_df(data_to_file[dataset], data_to_sep[dataset])
elif dataset in ['epinions', 'pinterest', 'yelp2018']:
return load_epinions_df(data_to_file[dataset], data_to_sep[dataset])
skiprows = 1 if dataset in ['ml-20m', 'ml-25m'] else None
df = pd.read_csv(data_to_file[dataset], sep=data_to_sep[dataset], names=['user', 'item', 'ratings', 'timestamp'], skiprows=skiprows)
return df
def load_citeulike_df(filepath, sep):
with open(filepath, 'rt') as f:
lines = f.readlines()
users = []
items = []
for u, line in enumerate(lines):
line = line.strip().split(sep)
num_cite = int(line[0])
u_items = line[1:]
if num_cite == 0:
continue
users += [u] * num_cite
items += u_items
ratings = [1] * len(users)
timestamps = [1] * len(users)
df_dict = {
'user': users,
'item': items,
'ratings': ratings,
'timestamp': timestamps
}
df = pd.DataFrame(df_dict)
return df
def load_epinions_df(filepath, sep):
df = pd.read_csv(filepath, sep=sep, names=['user', 'item', 'ratings'], skiprows=1).dropna()
df['ratings'] = np.ones(len(df))
df['timestamp'] = np.ones(len(df))
return df
def load_gowalla_df(filepath, sep):
df = pd.read_csv(filepath, sep=sep, names=['user', 'timestamp', 'latitude', 'longitude', 'item'])
df['timestamp'] = df['timestamp'].apply(process_time)
df['ratings'] = np.ones(len(df))
df = df.loc[:, ['user', 'item', 'ratings', 'timestamp']]
return df
def load_yelp_df(filepath):
with open(filepath, 'rt') as f:
lines = f.readlines()
users = []
items = []
ratings = []
timestamps = []
for line in tqdm(lines, total=len(lines)):
d = json.loads(line)
users.append(d['user_id'])
items.append(d['business_id'])
ratings.append(d['stars'])
t = d['date']
date_arr = time.strptime(t, "%Y-%m-%d %H:%M:%S")
timestamps.append(int(time.mktime(date_arr)))
# ratings = [1] * len(users)
df_dict = {
'user': users,
'item': items,
'ratings': ratings,
'timestamp': timestamps
}
df = pd.DataFrame(df_dict)
return df
def load_amusic_df(filepath):
with open(filepath, 'rt') as f:
lines = f.readlines()
users = []
items = []
ratings = []
timestamps = []
for line in tqdm(lines, total=len(lines)):
d = json.loads(line)
users.append(d['reviewerID'])
items.append(d['asin'])
ratings.append(d['overall'])
timestamps.append(d['unixReviewTime'])
# ratings = [1] * len(users)
df_dict = {
'user': users,
'item': items,
'ratings': ratings,
'timestamp': timestamps
}
df = pd.DataFrame(df_dict)
return df
def load_ciao_df(filepath, sep):
df = pd.read_csv(filepath, sep=sep, names=['user', 'item'], skiprows=1).dropna()
df['ratings'] = np.ones(len(df))
df['timestamp'] = np.ones(len(df))
return df
def process_time(time_str):
standard_time_list = list(time_str)
standard_time_list[10] = " "
standard_time_list.pop()
standard_time = "".join(standard_time_list)
date_arr = time.strptime(standard_time, "%Y-%m-%d %H:%M:%S")
timestamp = int(time.mktime(date_arr))
return timestamp
def df_to_sparse(df, shape):
rows, cols = df.user, df.item
values = df.ratings
sp_data = sparse.csr_matrix((values, (rows, cols)), dtype='float64', shape=shape)
num_nonzeros = np.diff(sp_data.indptr)
rows_to_drop = num_nonzeros == 0
if sum(rows_to_drop) > 0:
print('%d empty users are dropped from matrix.' % sum(rows_to_drop))
sp_data = sp_data[num_nonzeros != 0]
return sp_data
def dist_lorentz(x):
y = np.array(x) # y-axis data
y = np.sort(y, kind='mergesort')
x = np.repeat(1, len(y)) # x-axis data
pct_x = x / sum(x) # x normalized
pct_x = np.cumsum(pct_x) # CDF x
pct_y = y / sum(y) # y normalized
pct_y = np.cumsum(pct_y) # CDF y
# starts with (0,0)
pct_y = np.insert(pct_y, 0, 0)
pct_x = np.insert(pct_x, 0, 0)
return pct_x, pct_y
def gini(x):
x, y = dist_lorentz(x)
B = integrate.trapz(y, x) # area under lorentz curve
AB = 0.5 # area under bisetrix curve
A = AB - B # area between lorentz and bisetrix
res = A / AB # gini index
return res
def get_stat_dict(rating_matrix):
NUM_USERS, NUM_ITEMS = rating_matrix.shape
NUM_RATINGS = rating_matrix.nnz
NUM_RATINGS_PER_USER = NUM_RATINGS / NUM_USERS
DENSITY = NUM_RATINGS / (NUM_USERS * NUM_ITEMS)
SPARSITY = 1 - DENSITY
SHAPE = NUM_USERS / NUM_ITEMS
user_popularity = rating_matrix.sum(1).A.reshape(-1)
item_popularity = rating_matrix.sum(0).A.reshape(-1)
sorted_user_popularity = np.sort(user_popularity)
sorted_item_popularity = np.sort(item_popularity)
GINI_USER = gini(sorted_user_popularity)
GINI_ITEM = gini(sorted_item_popularity)
CONCENTRATION = sum(sorted_item_popularity[-int(len(item_popularity) * 0.05):]) / NUM_RATINGS
ret = {
'# Users': NUM_USERS,
'# Items': NUM_ITEMS,
'# Ratings': NUM_RATINGS,
'# Ratings per user': NUM_RATINGS_PER_USER,
'Sparsity': SPARSITY,
'Shape': SHAPE,
'Gini User': GINI_USER,
'Gini Item': GINI_ITEM,
'Concen.': CONCENTRATION
}
return ret