-
Notifications
You must be signed in to change notification settings - Fork 21
/
three_stage_0_NIR.py
395 lines (321 loc) · 12 KB
/
three_stage_0_NIR.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# !pip install openai
import time
import numpy as np
import json
import openai
import random
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--length_limit', type=int, default=8, help='')
parser.add_argument('--num_cand', type=int, default=19, help='')
parser.add_argument('--random_seed', type=int, default=2023, help='')
parser.add_argument('--api_key', type=str, default="sk-", help="")
args = parser.parse_args()
rseed = args.random_seed
random.seed(rseed)
def read_json(file):
with open(file) as f:
return json.load(f)
def write_json(data, file):
with open(file, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
data_ml_100k = read_json("./ml_100k.json")
# print (data_ml_100k[0][0])
# print (data_ml_100k[0][1])
# print (len(data_ml_100k))
open_ai_keys = [args.api_key]
open_ai_keys_index = 0
openai.api_key = open_ai_keys[open_ai_keys_index]
u_item_dict = {}
u_item_p = 0
for elem in data_ml_100k:
seq_list = elem[0].split(' | ')
for movie in seq_list:
if movie not in u_item_dict:
u_item_dict[movie] = u_item_p
u_item_p +=1
print (len(u_item_dict))
u_item_len = len(u_item_dict)
user_list = []
for i, elem in enumerate(data_ml_100k):
item_hot_list = [0 for ii in range(u_item_len)]
seq_list = elem[0].split(' | ')
for movie in seq_list:
item_pos = u_item_dict[movie]
item_hot_list[item_pos] = 1
user_list.append(item_hot_list)
user_matrix = np.array(user_list)
user_matrix_sim = np.dot(user_matrix, user_matrix.transpose())
pop_dict = {}
for elem in data_ml_100k:
# elem = data_ml_100k[i]
seq_list = elem[0].split(' | ')
for movie in seq_list:
if movie not in pop_dict:
pop_dict[movie] = 0
pop_dict[movie] += 1
i_item_dict = {}
i_item_id_list = []
i_item_user_dict = {}
i_item_p = 0
for i, elem in enumerate(data_ml_100k):
seq_list = elem[0].split(' | ')
for movie in seq_list:
if movie not in i_item_user_dict:
item_hot_list = [0. for ii in range(len(data_ml_100k))]
i_item_user_dict[movie] = item_hot_list
i_item_dict[movie] = i_item_p
i_item_id_list.append(movie)
i_item_p+=1
# item_pos = item_dict[movie]
i_item_user_dict[movie][i] += 1
# user_list.append(item_hot_list)
i_item_s_list = []
for item in i_item_id_list:
i_item_s_list.append(i_item_user_dict[item])
# print (sum(item_user_dict[item]))
item_matrix = np.array(i_item_s_list)
item_matrix_sim = np.dot(item_matrix, item_matrix.transpose())
id_list =list(range(0,len(data_ml_100k)))
### user filtering
def sort_uf_items(target_seq, us, num_u, num_i):
candidate_movies_dict = {}
sorted_us = sorted(list(enumerate(us)), key=lambda x: x[-1], reverse=True)[:num_u]
dvd = sum([e[-1] for e in sorted_us])
for us_i, us_v in sorted_us:
us_w = us_v * 1.0/dvd
# print (us_i)
us_elem = data_ml_100k[us_i]
# print (us_elem[0])
# assert 1==0
us_seq_list = us_elem[0].split(' | ')#+[us_elem[1]]
for us_m in us_seq_list:
# print (f"{us_m} not in {target_seq}, {us_m not in target_seq}")
# break
if us_m not in target_seq:
if us_m not in candidate_movies_dict:
candidate_movies_dict[us_m] = 0.
candidate_movies_dict[us_m]+=us_w
# assert 1==0
candidate_pairs = list(sorted(candidate_movies_dict.items(), key=lambda x:x[-1], reverse=True))
# print (candidate_pairs)
candidate_items = [e[0] for e in candidate_pairs][:num_i]
return candidate_items
### item filtering
def soft_if_items(target_seq, num_i, total_i, item_matrix_sim, item_dict):
candidate_movies_dict = {}
for movie in target_seq:
# print('ttt:',movie)
sorted_is = sorted(list(enumerate(item_matrix_sim[item_dict[movie]])), key=lambda x: x[-1], reverse=True)[:num_i]
for is_i, is_v in sorted_is:
s_item = i_item_id_list[is_i]
if s_item not in target_seq:
if s_item not in candidate_movies_dict:
candidate_movies_dict[s_item] = 0.
candidate_movies_dict[s_item] += is_v
# print (item_id_list[is_i], candidate_movies_dict)
candidate_pairs = list(sorted(candidate_movies_dict.items(), key=lambda x:x[-1], reverse=True))
# print (candidate_pairs)
candidate_items = [e[0] for e in candidate_pairs][:total_i]
# print (candidate_items)
return candidate_items
'''
In order to economize, our initial step is to identify user sequences that exhibit a high probability of obtaining accurate predictions from GPT-3.5 based on their respective candidates.
Subsequently, we proceed to utilize the GPT-3.5 API to generate predictions for these promising user sequences.
'''
results_data_15 = []
length_limit = args.length_limit
num_u= 12
total_i = args.num_cand
count = 0
total = 0
cand_ids = []
for i in id_list[:1000]:
elem = data_ml_100k[i]
seq_list = elem[0].split(' | ')
candidate_items = sort_uf_items(seq_list, user_matrix_sim[i], num_u=num_u, num_i=total_i)
# print (elem[-1], '-',seq_list[-1])
if elem[-1] in candidate_items:
# print ('HIT: 1')
count += 1
cand_ids.append(i)
else:
pass
# print ('HIT: 0')
total +=1
print (f'count/total:{count}/{total}={count*1.0/total}')
print ('-----------------\n')
temp_1 = """
Candidate Set (candidate movies): {}.
The movies I have watched (watched movies): {}.
Step 1: What features are most important to me when selecting movies (Summarize my preferences briefly)?
Answer:
"""
temp_2 = """
Candidate Set (candidate movies): {}.
The movies I have watched (watched movies): {}.
Step 1: What features are most important to me when selecting movies (Summarize my preferences briefly)?
Answer: {}.
Step 2: Selecting the most featured movies from the watched movies according to my preferences (Format: [no. a watched movie.]).
Answer:
"""
temp_3 = """
Candidate Set (candidate movies): {}.
The movies I have watched (watched movies): {}.
Step 1: What features are most important to me when selecting movies (Summarize my preferences briefly)?
Answer: {}.
Step 2: Selecting the most featured movies (at most 5 movies) from the watched movies according to my preferences in descending order (Format: [no. a watched movie.]).
Answer: {}.
Step 3: Can you recommend 10 movies from the Candidate Set similar to the selected movies I've watched (Format: [no. a watched movie - a candidate movie])?.
Answer:
"""
count = 0
total = 0
results_data = []
for i in cand_ids[:]:#[:10] + cand_ids[49:57] + cand_ids[75:81]:
elem = data_ml_100k[i]
seq_list = elem[0].split(' | ')[::-1]
candidate_items = sort_uf_items(seq_list, user_matrix_sim[i], num_u=num_u, num_i=total_i)
random.shuffle(candidate_items)
input_1 = temp_1.format(', '.join(candidate_items), ', '.join(seq_list[-length_limit:]))
try_nums = 5
kk_flag = 1
while try_nums:
try:
response = openai.Completion.create(
engine="text-davinci-003",
prompt=input_1,
max_tokens=512,
temperature=0,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
n = 1,
)
try_nums = 0
kk_flag = 1
except Exception as e:
if 'exceeded your current quota' in str(e):
# open_ai_keys_index +=1
openai.api_key = open_ai_keys[open_ai_keys_index]
time.sleep(1)
try_nums = try_nums-1
kk_flag = 0
if kk_flag == 0:
time.sleep(5)
response = openai.Completion.create(
engine="text-davinci-003",
prompt=input_1,
max_tokens=256,
temperature=0,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
n = 1,
)
predictions_1 = response["choices"][0]['text']
input_2 = temp_2.format(', '.join(candidate_items), ', '.join(seq_list[-length_limit:]), predictions_1)
try_nums = 5
kk_flag = 1
while try_nums:
try:
response = openai.Completion.create(
engine="text-davinci-003",
prompt=input_2,
max_tokens=512,
temperature=0,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
n = 1,
)
try_nums = 0
kk_flag = 1
except Exception as e:
if 'exceeded your current quota' in str(e):
# open_ai_keys_index +=1
openai.api_key = open_ai_keys[open_ai_keys_index]
time.sleep(1)
try_nums = try_nums-1
kk_flag = 0
if kk_flag == 0:
time.sleep(5)
response = openai.Completion.create(
engine="text-davinci-003",
prompt=input_2,
max_tokens=256,
temperature=0,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
n = 1,
)
predictions_2 = response["choices"][0]['text']
input_3 = temp_3.format(', '.join(candidate_items), ', '.join(seq_list[-length_limit:]), predictions_1, predictions_2)
try_nums = 5
kk_flag = 1
while try_nums:
try:
response = openai.Completion.create(
engine="text-davinci-003",
prompt=input_3,
max_tokens=512,
temperature=0,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
n = 1,
)
try_nums = 0
kk_flag = 1
except Exception as e:
if 'exceeded your current quota' in str(e):
# open_ai_keys_index +=1
openai.api_key = open_ai_keys[open_ai_keys_index]
time.sleep(1)
try_nums = try_nums-1
kk_flag = 0
if kk_flag == 0:
time.sleep(5)
response = openai.Completion.create(
engine="text-davinci-003",
prompt=input_3,
max_tokens=256,
temperature=0,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
n = 1,
)
predictions = response["choices"][0]['text']
hit_=0
if elem[1] in predictions:
count += 1
hit_ = 1
else:
pass
total +=1
# print (f"input_1:{input_1}")
# print (f"predictions_1:{predictions_1}\n")
# print (f"input_2:{input_2}")
# print (f"predictions_2:{predictions_2}\n")
# print (f"input_3:{input_3}")
print (f"GT:{elem[1]}")
print (f"predictions:{predictions}")
# print (f"GT:{elem[-1]}")
print (f'PID:{i}; count/total:{count}/{total}={count*1.0/total}\n')
result_json = {"PID": i,
"Input_1": input_1,
"Input_2": input_2,
"Input_3": input_3,
"GT": elem[1],
"Predictions_1": predictions_1,
"Predictions_2": predictions_2,
"Predictions": predictions,
'Hit': hit_,
'Count': count,
'Current_total':total,
'Hit@10':count*1.0/total}
results_data.append(result_json)
file_dir = f"./results_multi_prompting_len{length_limit}_numcand_{total_i}_seed{rseed}.json"
write_json(results_data, file_dir)