-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
223 lines (184 loc) · 7.5 KB
/
test.py
File metadata and controls
223 lines (184 loc) · 7.5 KB
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
# sudah bagus
# import torch
# from transformers import AutoTokenizer, AutoModel
# from models.finetune import FinetuneV2 # Ganti sesuai versi saat training
# tokenizer = AutoTokenizer.from_pretrained('indolem/indobert-base-uncased', return_token_type_ids=True, use_fast=False)
# pretrained_model = AutoModel.from_pretrained('indolem/indobert-base-uncased')
# checkpoint_path = '/kaggle/input/model-fake-news/epoch6-step3759.ckpt'
# model = FinetuneV2.load_from_checkpoint(
# checkpoint_path,
# model=pretrained_model
# )
# model.eval()
# text = "polda nusa tenggara barat mengklarifkasi kejadian perkosaan turis perancis gili trawangan lombok"
# encoding = tokenizer(
# text,
# truncation=True,
# padding='max_length',
# max_length=128,
# return_tensors='pt'
# )
# with torch.no_grad():
# logits = model(
# input_ids=encoding['input_ids'],
# attention_mask=encoding['attention_mask'],
# token_type_ids=encoding.get('token_type_ids', None)
# )
# if isinstance(logits, tuple):
# logits = logits[1]
# prediction = torch.argmax(logits, dim=1).item()
# label_map = {0: "HOAX", 1: "BENAR"}
# print(f"Prediction: {label_map[prediction]}")
# import torch
# from transformers import AutoTokenizer, AutoModel
# from models.finetune import FinetuneV2 # Ganti sesuai versi modelmu
# from sklearn.metrics import accuracy_score, classification_report
# # Load tokenizer dan pretrained backbone
# tokenizer = AutoTokenizer.from_pretrained('indolem/indobert-base-uncased', return_token_type_ids=True, use_fast=False)
# pretrained_model = AutoModel.from_pretrained('indolem/indobert-base-uncased')
# # Load checkpoint yang sudah di-finetune
# checkpoint_path = '/kaggle/input/model-fake-news/epoch6-step3759.ckpt'
# model = FinetuneV2.load_from_checkpoint(checkpoint_path, model=pretrained_model)
# model.eval()
# # Data uji (texts) dan label ground-truth (labels)
# texts = [
# "kemenhub klarifikasi kabar pegawai ditahan kebakaran gedung kemenhub", # BENAR
# "kemenkeu klarifikasi sri mulyani pakai topi kalimat tauhid", # BENAR
# "klarifikasi camat kemalang terkait isu pungli perekrutan perdes tangkil", # BENAR
# "penangkapan penyusup membawa bom acara pernikahan putri presiden jokowi", #HOAX
# "polisi israel mencekik anak palestina mati sabtu demonstrasi kedutaan amerika pindah yerusalem", #HOAX
# ]
# labels = [1, 1, 1, 0, 0] # 0: HOAX, 1: BENAR
# # Prediksi model
# predictions = []
# for text in texts:
# encoding = tokenizer(
# text,
# truncation=True,
# padding='max_length',
# max_length=128,
# return_tensors='pt'
# )
# with torch.no_grad():
# logits = model(
# input_ids=encoding['input_ids'],
# attention_mask=encoding['attention_mask'],
# token_type_ids=encoding.get('token_type_ids', None)
# )
# if isinstance(logits, tuple):
# logits = logits[1]
# pred = torch.argmax(logits, dim=1).item()
# predictions.append(pred)
# # Hitung metrik evaluasi
# accuracy = accuracy_score(labels, predictions)
# report = classification_report(labels, predictions, target_names=["HOAX", "BENAR"])
# # Output hasil
# label_map = {0: "HOAX", 1: "BENAR"}
# print("=== Prediction Results ===")
# for i, text in enumerate(texts):
# print(f"[{label_map[labels[i]]}] {text}")
# print(f" --> Predicted: {label_map[predictions[i]]}")
# print("\n=== Evaluation Metrics ===")
# print(f"Akurasi: {accuracy:.2f}")
# print(report)
#test pake json
# import torch
# import json
# from transformers import AutoTokenizer, AutoModel
# from models.finetune import FinetuneV2
# from sklearn.metrics import accuracy_score, classification_report
# # Load tokenizer dan backbone IndoBERT
# tokenizer = AutoTokenizer.from_pretrained('indolem/indobert-base-uncased', return_token_type_ids=True, use_fast=False)
# pretrained_model = AutoModel.from_pretrained('indolem/indobert-base-uncased')
# # Load checkpoint
# checkpoint_path = '/kaggle/input/model-fake-news/epoch6-step3759.ckpt'
# model = FinetuneV2.load_from_checkpoint(checkpoint_path, model=pretrained_model)
# model.eval()
# # Load data uji dari mendaley_sentenced_test.json
# test_file_path = 'datasets/github/github_sentenced_test.json'
# with open(test_file_path, 'r') as f:
# test_data = json.load(f)
# # Siapkan list untuk teks dan label
# texts = [item['query'] for item in test_data]
# labels = [item['label'] for item in test_data]
# # Prediksi
# predictions = []
# for text in texts:
# encoding = tokenizer(
# text,
# truncation=True,
# padding='max_length',
# max_length=128,
# return_tensors='pt'
# )
# with torch.no_grad():
# logits = model(
# input_ids=encoding['input_ids'],
# attention_mask=encoding['attention_mask'],
# token_type_ids=encoding.get('token_type_ids', None)
# )
# if isinstance(logits, tuple):
# logits = logits[1]
# pred = torch.argmax(logits, dim=1).item()
# predictions.append(pred)
# # Evaluasi
# accuracy = accuracy_score(labels, predictions)
# report = classification_report(labels, predictions, target_names=["HOAX", "BENAR"])
# # Tampilkan hasil prediksi dan evaluasi
# label_map = {0: "HOAX", 1: "BENAR"}
# print("=== Prediction Results (first 10 samples) ===")
# for i in range(min(10, len(texts))):
# print(f"[{label_map[labels[i]]}] {texts[i]}")
# print(f" --> Predicted: {label_map[predictions[i]]}")
# print("\n=== Evaluation Metrics ===")
# print(f"Akurasi: {accuracy:.2f}")
# print(report)
import json
import torch
from transformers import AutoTokenizer, AutoModel
from models.finetune import FinetuneV2
from sklearn.metrics import accuracy_score, classification_report
# === Load tokenizer dan model backbone ===
tokenizer = AutoTokenizer.from_pretrained('indolem/indobert-base-uncased', return_token_type_ids=True, use_fast=False)
pretrained_model = AutoModel.from_pretrained('indolem/indobert-base-uncased')
# === Load checkpoint ===
checkpoint_path = '/kaggle/input/model-fake-news/epoch6-step3759.ckpt'
model = FinetuneV2.load_from_checkpoint(checkpoint_path, model=pretrained_model)
model.eval()
# === Load data test ===
test_path = "datasets/github/github_sentenced_test.json" # Ganti sesuai path di Kaggle
with open(test_path, "r") as f:
data = json.load(f)
texts = [item["query"] for item in data]
labels = [item["label"] for item in data] # 0 = HOAX, 1 = BENAR
# === Predict ===
predictions = []
for text in texts:
encoding = tokenizer(
text,
truncation=True,
padding='max_length',
max_length=128,
return_tensors='pt'
)
with torch.no_grad():
logits = model(
input_ids=encoding['input_ids'],
attention_mask=encoding['attention_mask'],
token_type_ids=encoding.get('token_type_ids', None)
)
logits = torch.squeeze(logits, dim=1)
pred = (torch.sigmoid(logits) >= 0.5).int().item()
predictions.append(pred)
# === Evaluation ===
accuracy = accuracy_score(labels, predictions)
report = classification_report(labels, predictions, target_names=["HOAX", "BENAR"], zero_division=0)
print("=== Evaluation Metrics ===")
print(f"Akurasi: {accuracy:.2f}")
print(report)
# === Print 10 contoh prediksi ===
label_map = {0: "HOAX", 1: "BENAR"}
print("\n=== Prediction Results (10 contoh) ===")
for i in range(min(10, len(texts))):
print(f"[Label: {label_map[labels[i]]}] {texts[i]}")
print(f" --> Predicted: {label_map[predictions[i]]}")