-
Notifications
You must be signed in to change notification settings - Fork 0
/
ISWC_Challange-final.py
460 lines (364 loc) · 15.9 KB
/
ISWC_Challange-final.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import json
# ==============================================================================
# Preparing the Dataset - WordNet
# ==============================================================================
# Read the input JSON file
with open('wordnet_train.json', 'r') as file:
input_data = json.load(file)
output_data = []
# Process each item in the input JSON
for item in input_data:
term = item["term"]
pos_type = item["type"]
sentence = item["sentence"]
if sentence:
user_content = f"Perform a sentence completion on the following sentence: The part of speech of the term \"{term}\" in the sentence \"{sentence}\" is ___ "
assistant_content = f"The part of speech of the term \"{term}\" in the sentence \"{sentence}\" is {pos_type}."
else:
user_content = f"Perform a sentence completion on the following sentence: The part of speech of the term \"{term}\" is ___ "
assistant_content = f"The part of speech of the term \"{term}\" is {pos_type}."
output_data.append({
"messages": [
{"role": "user", "content": user_content},
{"role": "assistant", "content": assistant_content}
]
})
# Write the output data to a JSONL file
with open('wordnet_train.jsonl', 'w') as file:
for entry in output_data:
file.write(json.dumps(entry) + "\n")
print("The JSON file has been successfully converted to JSONL format.")
# ==============================================================================
# Preparing the Dataset - GeoNames
# ==============================================================================
# Read the input JSON file
with open('geonames_train.json', 'r') as file:
input_data = json.load(file)
output_data = []
# Process each item in the input JSON
for item in input_data:
term = item["term"]
geo_type = item["type"]
user_content = f"Perform a sentence completion on the following sentence: \"{term}\" geographically is a ___ "
assistant_content = f"\"{term}\" geographically is a {geo_type}."
output_data.append({
"messages": [
{"role": "user", "content": user_content},
{"role": "assistant", "content": assistant_content}
]
})
# Write the output data to a JSONL file
with open('geonames_train.jsonl', 'w') as file:
for entry in output_data:
file.write(json.dumps(entry) + "\n")
print("The JSON file has been successfully converted to JSONL format.")
# ==============================================================================
# Preparing the Dataset - UMLS MedCin
# ==============================================================================
# Read the input JSON file
with open('medcin_train.json', 'r') as file:
input_data = json.load(file)
output_data = []
# Process each item in the input JSON
for item in input_data:
term = item["term"]
umls_type = item["type"]
user_content = f"Perform a sentence completion on the following sentence: \"{term}\" in medicine can be described as ___"
assistant_content = f"The type of \"{term}\" in medicine can be described as: {umls_type}."
output_data.append({
"messages": [
{"role": "user", "content": user_content},
{"role": "assistant", "content": assistant_content}
]
})
# Write the output data to a JSONL file
with open('medcin_train.jsonl', 'w') as file:
for entry in output_data:
file.write(json.dumps(entry) + "\n")
print("The JSON file has been successfully converted to JSONL format.")
# ==============================================================================
# Preparing the Dataset - UMLS NCI
# ==============================================================================
# Read the input JSON file
with open('nci_train.json', 'r') as file:
input_data = json.load(file)
output_data = []
# Process each item in the input JSON
for item in input_data:
term = item["term"]
umls_type = item["type"]
user_content = f"Perform a sentence completion on the following sentence: \"{term}\" in medicine can be described as ___"
assistant_content = f"The type of \"{term}\" in medicine can be described as: {umls_type}."
output_data.append({
"messages": [
{"role": "user", "content": user_content},
{"role": "assistant", "content": assistant_content}
]
})
# Write the output data to a JSONL file
with open('nci_train.jsonl', 'w') as file:
for entry in output_data:
file.write(json.dumps(entry) + "\n")
print("The JSON file has been successfully converted to JSONL format.")
# ==============================================================================
# Preparing the Dataset - UMLS SNOMEDCT_US
# ==============================================================================
# Read the input JSON file
with open('snomedct_us_train.json', 'r') as file:
input_data = json.load(file)
output_data = []
# Process each item in the input JSON
for item in input_data:
term = item["term"]
umls_type = item["type"]
user_content = f"Perform a sentence completion on the following sentence: \"{term}\" in medicine can be described as ___"
assistant_content = f"The type of \"{term}\" in medicine can be described as: {umls_type}."
output_data.append({
"messages": [
{"role": "user", "content": user_content},
{"role": "assistant", "content": assistant_content}
]
})
# Write the output data to a JSONL file
with open('snomedct_us_train.jsonl', 'w') as file:
for entry in output_data:
file.write(json.dumps(entry) + "\n")
print("The JSON file has been successfully converted to JSONL format.")
# ==============================================================================
# OpenAI API Setup and Installation
# ==============================================================================
# Install OpenAI library
# pip install openai --user
# pip install openai --upgrade
import openai
print(openai.VERSION)
# ==============================================================================
# Uploading the Training Dataset for Fine-Tuning
# ==============================================================================
# Define your OpenAI API key
from openai import OpenAI
client = OpenAI(api_key='your OpenAI key')
def upload_file_for_fine_tuning(file_path):
try:
with open(file_path, "rb") as file:
response = client.files.create(
file=file,
purpose="fine-tune"
)
print("File uploaded successfully:", response)
except Exception as e:
print("An error occurred:", e)
# Example usage
upload_file_for_fine_tuning("wordnet_train.jsonl")
# ==============================================================================
# Creating the Fine-Tuning Job
# ==============================================================================
def create_fine_tuning_job(training_file_id, model="gpt-3.5-turbo-0125", suffix="wordnet_all"):
try:
response = client.fine_tuning.jobs.create(
training_file=training_file_id,
model=model,
suffix=suffix
)
print("Fine-tuning job created successfully:", response)
except Exception as e:
print("An error occurred:", e)
# Example usage
training_file_id = "file-tAzN3X2PJfZk1RHJdDlYYBcd" # replace with your training file id
create_fine_tuning_job(training_file_id, model="gpt-3.5-turbo-0125", suffix="wordnet_all") # Change model and suffix as needed
# Retrieve the state of a fine-tune
client.fine_tuning.jobs.retrieve("ftjob-13vPfnbqztHnpD9Awq8TT4xd") # replace with your job id
# ==============================================================================
# Evaluating Results - WordNet
# ==============================================================================
import openai
# Define your OpenAI API key
from openai import OpenAI
client = OpenAI(api_key = 'Your OpenAI key')
def get_term_types(term, sentence):
if sentence:
prompt = f"Perform a sentence completion on the following sentence: The part of speech of the term \"{term}\" in the sentence \"{sentence}\" is ___"
else:
prompt = f"Perform a sentence completion on the following sentence: The part of speech of the term \"{term}\" is ___"
try:
response = client.chat.completions.create(
model="ft:gpt-3.5-turbo-0125:kansas-state-university:wordnet-all:9gNNcSRE", # change to your finetuned model name
messages=[{'role': 'user', 'content': prompt}],
#max_tokens=50,
#n=1,
#stop=None,
temperature=0.0,
)
completion_text = response.choices[0].message.content.strip()
# Extract the types from the completion text
if "is" in completion_text:
types_start_index = completion_text.index("is") + len("is")
types_text = completion_text[types_start_index:].strip()
# Remove trailing period if present
if types_text.endswith("."):
types_text = types_text[:-1]
types = [t.strip() for t in types_text.split(",")]
else:
types = []
return types
except Exception as e:
print(f"An error occurred: {e}")
return []
def process_file(input_file, output_file):
with open(input_file, 'r') as infile:
data = json.load(infile)
results = []
for entry in data:
term = entry['term']
sentence = entry['sentence']
types = get_term_types(term, sentence)
results.append({
"ID": entry['ID'],
"type": types
})
with open(output_file, 'w') as outfile:
json.dump(results, outfile, indent=4)
# Example usage
input_file = 'A.1(FS)_WordNet_Test.json' # Replace with your input file path
output_file = 'output_wordnet.json' # Replace with your output file path
process_file(input_file, output_file)
#Cleaning up the output file - wordnet
import json
def extract_last_word_from_type(input_file, output_file):
with open(input_file, 'r') as infile:
data = json.load(infile)
results = []
for entry in data:
types = entry['type']
# Extract the last word from each type entry
last_words = [t.split()[-1] for t in types]
results.append({
"ID": entry['ID'],
"type": last_words
})
with open(output_file, 'w') as outfile:
json.dump(results, outfile, indent=4)
# Example usage
input_file = 'output_wordnet.json' # Replace with your input file path
output_file = 'output_wordnet_new.json' # Replace with your output file path
extract_last_word_from_type(input_file, output_file)
# ==============================================================================
# Evaluating Results - GeoNames
# ==============================================================================
import openai
import json
from openai import OpenAI
client = OpenAI(api_key = 'Your OpenAI key')
def get_term_types(term):
prompt = f"Perform a sentence completion on the following sentence: \"{term}\" geographically is a ___."
try:
response = client.chat.completions.create(
model="ft:gpt-3.5-turbo-0125:kansas-state-university:geonames-10percent:9gnjksT9", # change to your finetuned model name
messages=[{'role': 'user', 'content': prompt}],
temperature=0.0,
)
completion_text = response.choices[0].message.content.strip()
# Extract the words after "is a" from the completion text
if "is a" in completion_text:
types_text = completion_text.split("is a", 1)[1].strip()
# Remove trailing period if present
if types_text.endswith("."):
types_text = types_text[:-1]
types = [t.strip() for t in types_text.split(",")]
else:
types = []
return types, completion_text
except Exception as e:
print(f"An error occurred: {e}")
return None, None
def process_file(input_file, output_file, response_file):
with open(input_file, 'r') as infile:
data = json.load(infile)
results = []
responses = []
for entry in data:
term = entry['term']
last_word, completion_text = get_term_types(term)
if last_word and completion_text:
result = {
"ID": entry['ID'],
"type": last_word
}
response = {
"ID": entry['ID'],
"response": completion_text
}
results.append(result)
responses.append(response)
# Write the results and responses to files as the code runs
with open(output_file, 'w') as outfile:
json.dump(results, outfile, indent=4)
with open(response_file, 'w') as respfile:
json.dump(responses, respfile, indent=4)
# Print the extracted types for the term
print(f"Extracted types for term '{term}': {result['type']}")
# Example usage
input_file = 'A.2(FS)_GeoNames_Test.json' # Replace with your input file path
output_file = 'output_geonames.json' # Replace with your output file path
response_file = 'response_geonames.json' # Replace with your response file path
process_file(input_file, output_file, response_file)
# ==============================================================================
# Evaluating Results - UMLS
# ==============================================================================
import openai
import json
from openai import OpenAI
client = OpenAI(api_key = 'your OpenAI key')
def get_term_types(term):
prompt = f"Perform a sentence completion on the following sentence: \"{term}\" in medicine can be described as ___ ."
try:
response = client.chat.completions.create(
model="ft:gpt-3.5-turbo-0125:kansas-state-university:nci-all:9lWu1IfQ", # change to your finetuned model name
messages=[{'role': 'user', 'content': prompt}],
temperature=0.0,
)
completion_text = response.choices[0].message.content.strip()
# Extract the words after "as" from the completion text
if "as" in completion_text:
types_text = completion_text.split("as", 1)[1].strip()
# Remove trailing period if present
if types_text.endswith("."):
types_text = types_text[:-1]
types = [t.strip() for t in types_text.split(",")]
else:
types = []
return types, completion_text
except Exception as e:
print(f"An error occurred: {e}")
return None, None
def process_file(input_file, output_file, response_file):
with open(input_file, 'r') as infile:
data = json.load(infile)
results = []
responses = []
for entry in data:
term = entry['term']
last_word, completion_text = get_term_types(term)
if last_word and completion_text:
result = {
"ID": entry['ID'],
"type": last_word
}
response = {
"ID": entry['ID'],
"response": completion_text
}
results.append(result)
responses.append(response)
# Write the results and responses to files as the code runs
with open(output_file, 'w') as outfile:
json.dump(results, outfile, indent=4)
with open(response_file, 'w') as respfile:
json.dump(responses, respfile, indent=4)
# Print the extracted types for the term
print(f"Extracted types for term '{term}': {result['type']}")
# Example usage
input_file = 'A.3(FS)_UMLS_NCI_Test.json' # Replace with your input file path
output_file = 'output_nci.json' # Replace with your output file path
response_file = 'response_nci.json' # Replace with your response file path
process_file(input_file, output_file, response_file)