-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo.py
342 lines (298 loc) ยท 13.3 KB
/
demo.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import os
import sys
import torch
import numpy as np
import pandas as pd
import datetime as dt
import time as ti
from haversine import haversine
import math
import tqdm
from torch.utils.data import DataLoader
from data_utils import Preprocessing, Input_Dataset
from model_visitor.GMF import GMF
from model_visitor.MLP import MLP
from model_visitor.NeuMF import NeuMF
'''
date : 2018-01-01 ~ 2020-12-31
destination : ๊ด๊ด์ง ์ฝ๋
time : ๋ฐฉ๋ฌธํ ์๊ฐ๋
sex : ์ฑ
age : ๋์ด
visitor : ๋ฐฉ๋ฌธ๊ฐ์
year : ๋
๋
month : ์
day : ์ผ
dayofweek : ์์ผ
total_num : ์ด ์์ฉ์ธ์์
area : ๊ด๊ด์ง ๋ฉด์
date365 : 0~365
congestion_1 : ๋ฐฉ๋ฌธ๊ฐ์ / ์ด์์ฉ์ธ์์
congestion_2 : ๋ฐฉ๋ฌธ๊ฐ์ / ๊ด๊ด์ง๋ฉด์
middle_category(middle_category_name) : ๊ด๊ด์ง ์ค๋ถ๋ฅ ์ ํ ์ฝ๋(์ด๋ฆ)
small_category(small_category_name) : ๊ด๊ด์ง ์๋ถ๋ฅ ์ ํ ์ฝ๋(์ด๋ฆ)
x,y : ๊ฒฝ๋,์๋
city,gu,dong : ์,๊ตฌ,๋
'''
def define_args():
use_pretrain = False
model_name = 'NeuMF' # Choice GMF, MLP, NeuMF
epochs = 10 # Choice 20, 10, 10
num_factors = 36 # Choice 36, 24, 36
return use_pretrain, model_name, epochs, num_factors
def input_filterchar(userinfo:str):
str=""
for token in userinfo:
if ord(token)<48 or ord(token)>57:
break
str+=token
return int(str)
def str2datetime(date_info:list):
year, month, day = None, None, None
for i, token in enumerate(date_info):
if i==0 :
year = int(input_filterchar(token))
if i==1:
month = int(input_filterchar(token))
if i==2:
day = int(input_filterchar(token))
return year, month, day
def time2range(time):
if time<6:
return 1
if time<11:
return 2
if time<14:
return 3
if time<18:
return 4
if time<21:
return 5
if time<24:
return 6
def age2range(age):
return ((age//10)*10)*100 + ((age//10)*10+9)
def sex2int(sex):
return 1 if sex[0]=='๋จ'else 0
def destint2str(li):
dest_dict = {'1':'์ญ์ฌ๊ด๊ด์ง','2':'ํด์๊ด๊ด์ง','3':'์ฒดํ๊ด๊ด์ง','4':'๋ฌธํ์์ค','5':'๊ฑด์ถ/์กฐํ๋ฌผ','6':'์์ฐ๊ด๊ด์ง','7':'์ผํ'}
dest_li=[]
for val in li:
dest_li.append(dest_dict[val])
return dest_li
# destination_id_name_df: 3๊ฐ์ง ์ฅ๋ฅด des id name, ๊ฒฝ๋ ์๋
# df: congestion total
def load_congestion(destination_id_name_df, df, dayofweek, time, month, day):
dayofweek, time, day, month = dayofweek.item(), time.item(), day.item(), month.item()
new_df = df[((df['month'] == month) & (df['day'] == day)) & ((df['dayofweek'] == dayofweek) & (df['time'] == time))]
new_df = new_df[new_df.destination.isin(destination_id_name_df.destination)]
return new_df['congestion_1']
def filter_destination(DEST_PATH,genre_list):
df = pd.read_pickle(DEST_PATH)
new_df = pd.DataFrame(columns=df.columns)
for i in genre_list:
temp_df = df[(df['middle_category_name'] == i)]
new_df = pd.concat([new_df, temp_df], ignore_index=True)
des_list = new_df['destination'].to_list()
return new_df, des_list
# just for visualization for laoding
def progress_bar(text):
ti.sleep(0.01)
t = tqdm.tqdm(total=10, ncols=100, desc=text)
for i in range(5):
ti.sleep(0.2)
t.update(2)
t.close()
############################## Main ##############################
if __name__ == '__main__' :
# check device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'device: {device}')
# print GPU information
if torch.cuda.is_available():
print('Current cuda device:', torch.cuda.current_device())
print('Count of using GPUs:', torch.cuda.device_count())
############################## User Input ##############################
# user info
print("๋ช ๋ช
์ด์ ๊ด๊ดํ ๊ณํ์ด์ ๊ฐ์? ex) 3๋ช
")
num_people = input_filterchar(input())
user_info =[]
for i in range(num_people):
tem_list = []
print(f"{i+1}๋ฒ์งธ ๋ถ์ ์ด๋ค ์ฐ๋ น๋ ์ธ๊ฐ์?. ex) 20๋")
tem_list.append(age2range(input_filterchar(input())))
print(f"{i+1}๋ฒ์งธ ๋ถ์ ์ฑ๋ณ์ ๋ฌด์์ด์ ๊ฐ์?. ex) ๋จ์ฑ/์ฌ์ฑ")
tem_list.append(sex2int(input()))
user_info.append(tem_list)
# time info
print("๊ด๊ด์ ์์ํ ์ฐ ์ ์ผ์ด ์ธ์ ์ธ๊ฐ์? ex) 2022๋
5์ 21์ผ")
date = list(input().split())
year, month, day = str2datetime(date)
print("๋ฉฐ์น ๋์ ๊ด๊ดํ์๋์? ex) 4์ผ(max:7์ผ, min:1์ผ)")
num_term = input_filterchar((input()))
user_df = pd.DataFrame()
for i in range(num_term):
print(f"{i+1}๋ฒ์งธ ๋ ์ ์ด๋ค ์๊ฐ๋๊ฐ ์ข์ผ์ ๊ฐ์? ex) 13์")
timezone = time2range(input_filterchar(input()))
datetime = dt.date(year, month, day) + dt.timedelta(days=i)
m, d, w, t = datetime.month, datetime.day, datetime.weekday(), timezone
tem_df = pd.DataFrame(user_info, columns=['age', 'sex'])
tem_df['month'] = m
tem_df['day'] = d
tem_df['dayofweek'] = w
tem_df['time'] = t
user_df = pd.concat([user_df, tem_df], axis=0, ignore_index=True)
# print(user_df)
# input for staring point
print("์ด๋์ ์ถ๋ฐํ์๋์? ํ์ ๊ตฌ์ ๋์ ์
๋ ฅํด์ฃผ์ธ์. ex) ์ข
๋ก๊ตฌ ์ผ์ฒญ๋")
start_info = input().split(' ')
# select destination genre
print("์ด๋ค ์ฅ๋ฅด์ ๊ด๊ด์ง๋ฅผ ์ํ์๋์? (3๊ฐ ์ด์ ๊ณจ๋ผ์ฃผ์ธ์) ex) 1,2,3"
"\n1.์ญ์ฌ๊ด๊ด์ง \t2.ํด์๊ด๊ด์ง\t3.์ฒดํ๊ด๊ด์ง\t4.๋ฌธํ์์ค\t5.๊ฑด์ถ/์กฐํ๋ฌผ\t6.์์ฐ๊ด๊ด์ง\t7.์ผํ")
genre_list = destint2str(input().split(','))
# select ratio visitor Vs congestion Vs distance
print("๊ด๊ด์ง๋ฅผ ์ ํํ๋ ๊ณผ์ ์์ '์ ํธ๋/ํผ์ก๋/๊ฑฐ๋ฆฌ' ์๋ณ๋ก ์ค์์ํ๋ ๋น์จ์ ๋ถ์ฌํด์ฃผ์ธ์. ex) 0.6:0.2:0.2")
ratio = list(map(float, (input().split(':'))))
############################## Operation ##############################
total_start = ti.time()
progress_bar('Loading Dataset')
ROOT_DIR = 'dataset'
DEST_INFO_PATH = os.path.join(ROOT_DIR, 'destination_id_name_genre_coordinate.pkl')
PREDICTED_CONGEST_PATH = os.path.join(ROOT_DIR, 'congestion_1_2.pkl')
CITY_INFO_PATH = os.path.join(ROOT_DIR, 'seoul_gu_dong_coordinate.pkl')
# 3๊ฐ ์ฅ๋ฅด์ ํฌํจ๋ dataframe, list
destination_id_name_df, destination_list = filter_destination(DEST_INFO_PATH, genre_list)
batch_candidate = len(destination_list)
# load file
congestion_df = pd.read_pickle(PREDICTED_CONGEST_PATH)
city_df = pd.read_pickle(CITY_INFO_PATH)
# user ์ถ๋ฐ์ง ๊ฒฝ๋ ์๋ tuple
start_df = city_df[(city_df['gu'] == start_info[0]) & (city_df['dong'] == start_info[1])]
user_pos = (start_df['y'], start_df['x'])
print(f"\nLoad Destination_info complete\n")
progress_bar('Loading Model')
use_pretrain, model_name, epochs, num_factors = define_args()
FOLDER_PATH = 'pretrain_model'
MODEL_PATH_VISITOR = os.path.join(FOLDER_PATH,f'0_{use_pretrain}_{model_name}_{epochs}_512_{num_factors}_visitor.pth')
if not os.path.exists(MODEL_PATH_VISITOR):
print("Model doesn't exist.\n")
sys.exit()
if model_name == 'GMF':
model_visitor = GMF(num_factor=36,
num_dayofweek=7,
num_time=7,
num_sex=2,
num_age=7001,
num_month=13,
num_day=32,
num_destination=2505928,
use_pretrain=False,
use_NeuMF=False,
pretrained_GMF=None)
elif model_name == 'MLP':
model_visitor = MLP(num_factor=24,
num_layer=3,
num_dayofweek=7,
num_time=7,
num_sex=2,
num_age=7001,
num_month=13,
num_day=32,
num_destination=2505928,
use_pretrain=False,
use_NeuMF=False,
pretrained_MLP=None)
elif model_name == 'NeuMF':
model_visitor = NeuMF(num_factor=36,
num_layer=3,
num_dayofweek=7,
num_time=7,
num_sex=2,
num_age=7001,
num_month=13,
num_day=32,
num_destination=2505928,
use_pretrain=False,
use_NeuMF=True,
pretrained_GMF=None,
pretrained_MLP=None)
model_visitor.load_state_dict(torch.load(MODEL_PATH_VISITOR,map_location=device))
print("Load Model complete\n")
All_day_ranking = [0] * num_term
total_ranking = {}
for i in user_df.index:
tem_df = destination_id_name_df.copy()
user_input = list(user_df.iloc[i,:])
RecSys_dataset = Input_Dataset(destination_list=destination_list, RecSys_input=user_input)
RecSys_dataloader = DataLoader(dataset=RecSys_dataset,
batch_size=batch_candidate,
shuffle=False)
for destination, time, sex, age, dayofweek, month, day in RecSys_dataloader:
destination = destination.to(device)
dayofweek, time, sex, age, month, day =\
dayofweek.to(device), time.to(device), sex.to(device), age.to(device), month.to(device), day.to(device)
pred_visitor = model_visitor(dayofweek, time, sex, age, month, day, destination)
saved_congestion = load_congestion(destination_id_name_df=destination_id_name_df,
df=congestion_df,
dayofweek=dayofweek[0],
time=time[0],
month=month[0],
day=day[0])
pred_visitor = pred_visitor.tolist()
saved_congestion = saved_congestion.tolist()
tem_df['visitor'] = pred_visitor
tem_df['congestion'] = saved_congestion
tem_df = tem_df.sort_values(by='visitor', ascending=False)
for k in range(batch_candidate):
dest_pos = (tem_df.iloc[k, 8], tem_df.iloc[k, 9])
destination_name = tem_df.iloc[k, 1]
small_genre = tem_df.iloc[k, 7]
middle_genre = tem_df.iloc[k, 6]
visitor = tem_df.iloc[k, 10]
congestion = tem_df.iloc[k, 11]
# ์ถ๋ฐ์ง-๊ด๊ด์ง haversine ๊ฑฐ๋ฆฌ
distance = haversine(user_pos, dest_pos)
# destination name์ key๋ก ์ค์
rank_weight = total_ranking.get(destination_name)
if rank_weight is None:
total_ranking[destination_name] = [0, 0, distance, middle_genre, small_genre]
# ํด๋น user info๋ค๊ณผ ๋ ์ง์ ๋ํ visitor, congestion ํฉ ๊ตฌํ๊ธฐ
total_ranking[destination_name][0] += visitor
total_ranking[destination_name][1] += congestion
if i % num_people == num_people - 1:
All_day_ranking[i // num_people] = total_ranking
total_ranking = {}
result_ranking = [0] * num_term
total_dest = {}
for day, each_rank in enumerate(All_day_ranking):
sorted_visitor_ranking = sorted(each_rank.items(), key=lambda item: item[1][0], reverse=True)
sorted_congestion_ranking = sorted(each_rank.items(), key=lambda item: item[1][1], reverse=True)
sorted_distance_ranking = sorted(each_rank.items(), key=lambda item: item[1][2], reverse=True)
tmp_rank = {}
for i, dest in enumerate(sorted_visitor_ranking):
tmp_rank[dest[0]] = ratio[0] * (batch_candidate - i)
for i, dest in enumerate(sorted_congestion_ranking):
tmp_rank[dest[0]] += ratio[1] * (batch_candidate - i)
for i, dest in enumerate(sorted_distance_ranking):
tmp_rank[dest[0]] += ratio[2] * (batch_candidate - i)
val = total_dest.get(dest[0])
if val is None:
total_dest[dest[0]] = []
total_dest[dest[0]].append(tmp_rank[dest[0]])
sorted_total_ranking = sorted(tmp_rank.items(), key=lambda item: item[1], reverse=True)
result_ranking[day] = sorted_total_ranking
# calculate median ranking
median_dest = {}
for k, v in total_dest.items():
v.sort(reverse=True)
median_dest[k] = math.floor(v[len(v) // 2])
for i, day_ranking in enumerate(result_ranking):
print(f'\n{i + 1}์ผ ์งธ ์ถ์ฒ ๊ด๊ด์ง')
rank = 1
for dest in day_ranking:
if median_dest[dest[0]] > dest[1]:
continue
print(f'{rank}๋ฑ: {dest[0]}')
rank += 1
end_time = ti.time()
print(f'์ถ์ฒํ๋๋ฐ ์ด ๊ฑธ๋ฆฐ ์๊ฐ : {end_time - total_start}')