Stage-2 artefak (12 fitur, tanpa gensim)
Browse files- .virtual_documents/__notebook_source__.ipynb +593 -0
- ablation_l1.csv +10 -10
- ablation_l1.png +3 -0
- ablation_l2.csv +8 -8
- ablation_text_meta.csv +4 -4
- ablation_text_meta.png +3 -0
- best_model_curves.png +3 -0
- classifier.pkl +2 -2
- classifier_comparison.csv +4 -4
- classifier_comparison.png +3 -0
- easy_vs_hard_negative.png +3 -0
- feature_correlation.png +3 -0
- feature_distributions.png +3 -0
- feature_extractors.pkl +2 -2
- feature_importance.png +3 -0
- scaler.pkl +2 -2
- stage2_efficiency.json +2 -2
- summary.json +10 -12
.virtual_documents/__notebook_source__.ipynb
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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, time, json, pickle, warnings
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from itertools import product
|
| 12 |
+
from collections import Counter, namedtuple
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
warnings.filterwarnings('ignore')
|
| 15 |
+
plt.rcParams['figure.dpi'] = 110; plt.rcParams['font.size'] = 10
|
| 16 |
+
|
| 17 |
+
from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold
|
| 18 |
+
from sklearn.preprocessing import StandardScaler
|
| 19 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 20 |
+
from sklearn.decomposition import TruncatedSVD, LatentDirichletAllocation
|
| 21 |
+
from sklearn.linear_model import LogisticRegression
|
| 22 |
+
from sklearn.neural_network import MLPClassifier
|
| 23 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 24 |
+
from sklearn.metrics import (f1_score, precision_score, recall_score, accuracy_score,
|
| 25 |
+
confusion_matrix, classification_report, precision_recall_curve,
|
| 26 |
+
roc_curve, auc, average_precision_score)
|
| 27 |
+
from sklearn.inspection import permutation_importance
|
| 28 |
+
try:
|
| 29 |
+
import xgboost as xgb; HAS_XGB = True
|
| 30 |
+
except Exception:
|
| 31 |
+
HAS_XGB = False
|
| 32 |
+
try:
|
| 33 |
+
import torch; ENV_HAS_GPU = torch.cuda.is_available()
|
| 34 |
+
except Exception:
|
| 35 |
+
ENV_HAS_GPU = False
|
| 36 |
+
print('GPU:', ENV_HAS_GPU, '| XGBoost:', HAS_XGB)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
SEED = 42; VAL_FRAC = 0.20
|
| 40 |
+
W2V_DIM = 100; N_TOPICS_LDA = 30; N_TOPICS_LSA = 50
|
| 41 |
+
K_RETRIEVAL = 50 # dari Stage 1
|
| 42 |
+
HF_SBERT_FT = 'HariishHafiiz/sbert-bug-eclipse-ft' # model SBERT-FT hasil Stage-1
|
| 43 |
+
HF_REPO = 'HariishHafiiz/stage2-classifier-eclipse'
|
| 44 |
+
QUICK_TEST = False # True utk uji cepat (subset)
|
| 45 |
+
np.random.seed(SEED)
|
| 46 |
+
|
| 47 |
+
INPUT_DIR = '/kaggle/input/datasets/hpeace090104/skripsi'
|
| 48 |
+
if not Path(INPUT_DIR).exists(): INPUT_DIR = '/mnt/user-data/uploads'
|
| 49 |
+
OUT_DIR = '/kaggle/working' if Path('/kaggle/working').exists() else './stage2_out'
|
| 50 |
+
Path(OUT_DIR).mkdir(parents=True, exist_ok=True)
|
| 51 |
+
FILES = {'train_dup':f'{INPUT_DIR}/EP_Eclipse_train_dup_metadata.csv',
|
| 52 |
+
'train_nondup':f'{INPUT_DIR}/EP_Eclipse_train_nondup_metadata.csv',
|
| 53 |
+
'test_dup':f'{INPUT_DIR}/EP_Eclipse_test_dup_metadata.csv',
|
| 54 |
+
'test_nondup':f'{INPUT_DIR}/EP_Eclipse_test_nondup_metadata.csv'}
|
| 55 |
+
print('INPUT_DIR:', INPUT_DIR, '| OUT_DIR:', OUT_DIR)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
train_dup_full = pd.read_csv(FILES['train_dup'])
|
| 62 |
+
train_nondup_full = pd.read_csv(FILES['train_nondup'])
|
| 63 |
+
test_dup = pd.read_csv(FILES['test_dup'])
|
| 64 |
+
test_nondup = pd.read_csv(FILES['test_nondup'])
|
| 65 |
+
|
| 66 |
+
if QUICK_TEST:
|
| 67 |
+
train_dup_full=train_dup_full.head(1000); train_nondup_full=train_nondup_full.head(1000)
|
| 68 |
+
test_dup=test_dup.head(200); test_nondup=test_nondup.head(600)
|
| 69 |
+
|
| 70 |
+
train_dup, val_dup = train_test_split(train_dup_full, test_size=VAL_FRAC, random_state=SEED)
|
| 71 |
+
train_nondup, val_nondup = train_test_split(train_nondup_full, test_size=VAL_FRAC, random_state=SEED)
|
| 72 |
+
train_df = pd.concat([train_dup, train_nondup]).sample(frac=1, random_state=SEED).reset_index(drop=True)
|
| 73 |
+
val_df = pd.concat([val_dup, val_nondup ]).sample(frac=1, random_state=SEED).reset_index(drop=True)
|
| 74 |
+
test_df = pd.concat([test_dup, test_nondup ]).reset_index(drop=True)
|
| 75 |
+
|
| 76 |
+
for nm, d in [('train',train_df),('val',val_df),('test',test_df)]:
|
| 77 |
+
print(f"{nm:5s}: {len(d):,} | dup={int(d.Label.sum()):,} nondup={int((d.Label==0).sum()):,} ratio={d.Label.mean():.0%}")
|
| 78 |
+
if not QUICK_TEST:
|
| 79 |
+
print('train_dup:', len(train_dup), '| val_dup:', len(val_dup), '(harusnya 5920 / 1480 — konsisten Stage-1)')
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
STOPWORDS = set(
|
| 86 |
+
"a about above after again against all an and any are arent as at be because been before being "
|
| 87 |
+
"below between both but by cant cannot could couldnt did didnt do does doesnt doing dont down during "
|
| 88 |
+
"each few for from further get got had hadnt has hasnt have havent having he hed hell hes her here "
|
| 89 |
+
"heres hers herself him himself his how hows id ill im ive if in into is isnt it its itself lets me "
|
| 90 |
+
"more most mustnt my myself nor of off on once only or other ought our ours ourselves out over own "
|
| 91 |
+
"same shant she shed shell shes should shouldnt so some such than that thats the their theirs them "
|
| 92 |
+
"themselves then there theres these they theyd theyll theyre theyve this those through to too under "
|
| 93 |
+
"until up upon us very was wasnt we wed were weve werent what whats when whens where wheres which "
|
| 94 |
+
"while who whos whom why whys with wont would wouldnt you youd youll youre youve your yours yourself "
|
| 95 |
+
"yourselves also just like will may shall still yet already even much many really actually however "
|
| 96 |
+
"another simply perhaps since using used one two three way etc via see eg ie thus hence therefore "
|
| 97 |
+
"accordingly note notes pm".split()
|
| 98 |
+
)
|
| 99 |
+
STOPWORDS -= {'not','no','cannot','error','bug','crash','fail','null','unable','invalid','missing','broken','wrong'}
|
| 100 |
+
|
| 101 |
+
def preprocess_ir(text):
|
| 102 |
+
if pd.isna(text): return ''
|
| 103 |
+
text = str(text).lower()
|
| 104 |
+
text = re.sub(r'https?://\S+|www\.\S+|<[^>]+>|\S+@\S+', '', text)
|
| 105 |
+
text = re.sub(r'[^a-z0-9\s]', ' ', text) # pertahankan huruf & digit
|
| 106 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 107 |
+
return ' '.join([t for t in text.split() if t not in STOPWORDS and len(t) > 1])
|
| 108 |
+
|
| 109 |
+
def ir_pair(ti, de):
|
| 110 |
+
return ' '.join([preprocess_ir(ti)]*3 + [preprocess_ir(de)]) # judul x3, seperti Stage-1
|
| 111 |
+
|
| 112 |
+
def raw_text(ti, de):
|
| 113 |
+
a = '' if pd.isna(ti) else str(ti); b = '' if pd.isna(de) else str(de)
|
| 114 |
+
return re.sub(r'\s+', ' ', (a + ' ' + b)).strip() # teks natural utk SBERT
|
| 115 |
+
|
| 116 |
+
def parse_time_diff_days(s1, s2):
|
| 117 |
+
t1 = pd.to_datetime(s1, errors='coerce', utc=True)
|
| 118 |
+
t2 = pd.to_datetime(s2, errors='coerce', utc=True)
|
| 119 |
+
return (t1 - t2).dt.total_seconds().abs().fillna(0) / 86400
|
| 120 |
+
|
| 121 |
+
for df in [train_df, val_df, test_df]:
|
| 122 |
+
df['text1'] = df.apply(lambda r: ir_pair(r['Title1'], r['Description1']), axis=1) # IR (leksikal/topik)
|
| 123 |
+
df['text2'] = df.apply(lambda r: ir_pair(r['Title2'], r['Description2']), axis=1)
|
| 124 |
+
df['text1_raw'] = df.apply(lambda r: raw_text(r['Title1'], r['Description1']), axis=1) # raw (SBERT)
|
| 125 |
+
df['text2_raw'] = df.apply(lambda r: raw_text(r['Title2'], r['Description2']), axis=1)
|
| 126 |
+
|
| 127 |
+
corpus_train = list(set(train_df['text1'].tolist() + train_df['text2'].tolist()))
|
| 128 |
+
print(f'Corpus train (IR, judul x3, unik): {len(corpus_train):,} dokumen')
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# TF-IDF
|
| 135 |
+
tfidf_c = TfidfVectorizer(analyzer='char_wb', ngram_range=(2,4), max_features=30000, sublinear_tf=True).fit(corpus_train)
|
| 136 |
+
tfidf_w = TfidfVectorizer(analyzer='word', ngram_range=(1,2), max_features=30000, sublinear_tf=True).fit(corpus_train)
|
| 137 |
+
|
| 138 |
+
# BM25: document frequency yang BENAR (dihitung dari set token tiap dokumen)
|
| 139 |
+
tokenized_corpus = [t.split() for t in corpus_train]
|
| 140 |
+
DF_COUNT = Counter()
|
| 141 |
+
for doc in tokenized_corpus:
|
| 142 |
+
for t in set(doc): DF_COUNT[t] += 1
|
| 143 |
+
N_DOCS = len(tokenized_corpus)
|
| 144 |
+
BM25_AVGDL = float(np.mean([len(d) for d in tokenized_corpus])) if tokenized_corpus else 1.0
|
| 145 |
+
print(f'BM25: N_DOCS={N_DOCS:,} | AVGDL={BM25_AVGDL:.1f} | vocab(DF)={len(DF_COUNT):,}')
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# W2V/FastText/Doc2Vec DIHAPUS: kontribusi ~0 pada feature importance, dan paling lambat
|
| 149 |
+
# untuk dilatih + menyebabkan masalah sidecar .npy saat upload. Fitur akhir = 12 (tanpa SEM_STAT).
|
| 150 |
+
print('SEM_STAT (W2V/FT/D2V) tidak digunakan. Fitur leksikal/semantik = TF-IDF/BM25 + SBERT.')
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# LDA + LSA
|
| 154 |
+
count_vec = TfidfVectorizer(analyzer='word', ngram_range=(1,1), max_features=10000)
|
| 155 |
+
X_count = count_vec.fit_transform(corpus_train)
|
| 156 |
+
lda_model = LatentDirichletAllocation(n_components=N_TOPICS_LDA, random_state=SEED, learning_method='online', n_jobs=-1).fit(X_count)
|
| 157 |
+
tfidf_lsa = TfidfVectorizer(analyzer='word', ngram_range=(1,1), max_features=10000)
|
| 158 |
+
X_tfidf = tfidf_lsa.fit_transform(corpus_train)
|
| 159 |
+
lsa_model = TruncatedSVD(n_components=N_TOPICS_LSA, random_state=SEED).fit(X_tfidf)
|
| 160 |
+
print('Topic model (LDA/LSA) siap.')
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# SBERT-FT dari Stage-1 (HuggingFace). Bila tak tersedia, fitur cosine_sbert diisi 0 (notebook tetap jalan).
|
| 164 |
+
sbert_model = None; SBERT_OK = False
|
| 165 |
+
if ENV_HAS_GPU or True:
|
| 166 |
+
try:
|
| 167 |
+
from sentence_transformers import SentenceTransformer
|
| 168 |
+
sbert_model = SentenceTransformer(HF_SBERT_FT)
|
| 169 |
+
SBERT_OK = True
|
| 170 |
+
print('SBERT-FT Stage-1 dimuat:', HF_SBERT_FT)
|
| 171 |
+
except Exception as e:
|
| 172 |
+
print('SBERT gagal dimuat (', repr(e)[:120], ') -> cosine_sbert diisi 0.')
|
| 173 |
+
sbert_model = None
|
| 174 |
+
print('SBERT_OK:', SBERT_OK)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def cosine_rows(A, B):
|
| 181 |
+
return np.einsum('ij,ij->i', A, B) / (np.linalg.norm(A,axis=1)*np.linalg.norm(B,axis=1) + 1e-9)
|
| 182 |
+
def bm25_pair(q_tokens, d_tokens, k1=1.5, b=0.75):
|
| 183 |
+
if not q_tokens or not d_tokens: return 0.0
|
| 184 |
+
dl = len(d_tokens); fr = Counter(d_tokens); s = 0.0
|
| 185 |
+
for w in set(q_tokens):
|
| 186 |
+
if w in fr:
|
| 187 |
+
dft = DF_COUNT.get(w, 0)
|
| 188 |
+
s += np.log((N_DOCS - dft + 0.5)/(dft + 0.5) + 1.0) * (fr[w]*(k1+1))/(fr[w] + k1*(1-b+b*dl/BM25_AVGDL))
|
| 189 |
+
return s
|
| 190 |
+
|
| 191 |
+
ALL_FEATURES = ['cosine_tfidf_c','cosine_tfidf_w','bm25_score','cosine_sbert_ft','cosine_lda','cosine_lsa',
|
| 192 |
+
'same_component','same_priority','same_version','same_comp_ver','time_diff_created','log_time_diff']
|
| 193 |
+
FEATURE_GROUPS = {'LEX':['cosine_tfidf_c','cosine_tfidf_w','bm25_score'],
|
| 194 |
+
'SEM_CTX':['cosine_sbert_ft'],
|
| 195 |
+
'TOPIC':['cosine_lda','cosine_lsa'],
|
| 196 |
+
'META':['same_component','same_priority','same_version','same_comp_ver','time_diff_created','log_time_diff']}
|
| 197 |
+
|
| 198 |
+
def extract_features(df, batch=256, sbert_batch=64):
|
| 199 |
+
n = len(df); t1 = df['text1'].tolist(); t2 = df['text2'].tolist()
|
| 200 |
+
cc = np.zeros(n); cw = np.zeros(n)
|
| 201 |
+
for i in range(0, n, batch):
|
| 202 |
+
sl = slice(i, i+batch)
|
| 203 |
+
cc[sl] = cosine_rows(tfidf_c.transform(t1[sl]).toarray(), tfidf_c.transform(t2[sl]).toarray())
|
| 204 |
+
cw[sl] = cosine_rows(tfidf_w.transform(t1[sl]).toarray(), tfidf_w.transform(t2[sl]).toarray())
|
| 205 |
+
bm = np.array([bm25_pair(t2[i].split(), t1[i].split()) for i in range(n)], dtype=float)
|
| 206 |
+
bm = bm / (bm.max() + 1e-9)
|
| 207 |
+
if sbert_model is not None:
|
| 208 |
+
e1 = sbert_model.encode(df['text1_raw'].tolist(), batch_size=sbert_batch, show_progress_bar=False, convert_to_numpy=True)
|
| 209 |
+
e2 = sbert_model.encode(df['text2_raw'].tolist(), batch_size=sbert_batch, show_progress_bar=False, convert_to_numpy=True)
|
| 210 |
+
cs = cosine_rows(e1, e2)
|
| 211 |
+
else:
|
| 212 |
+
cs = np.zeros(n)
|
| 213 |
+
cl = np.zeros(n); ls = np.zeros(n)
|
| 214 |
+
for i in range(0, n, batch):
|
| 215 |
+
sl = slice(i, i+batch)
|
| 216 |
+
cl[sl] = cosine_rows(lda_model.transform(count_vec.transform(t1[sl])), lda_model.transform(count_vec.transform(t2[sl])))
|
| 217 |
+
ls[sl] = cosine_rows(lsa_model.transform(tfidf_lsa.transform(t1[sl])), lsa_model.transform(tfidf_lsa.transform(t2[sl])))
|
| 218 |
+
sc = (df['Component_1'].fillna('') == df['Component_2'].fillna('')).astype(float).values
|
| 219 |
+
sp = (df['Priority_1'].fillna('') == df['Priority_2'].fillna('')).astype(float).values
|
| 220 |
+
sv = (df['Version_1'].fillna('') == df['Version_2'].fillna('')).astype(float).values
|
| 221 |
+
td = parse_time_diff_days(df['Created_time_1'], df['Created_time_2']).values
|
| 222 |
+
return np.column_stack([cc, cw, bm, cs, cl, ls, sc, sp, sv, sc*sv, td, np.log1p(td)])
|
| 223 |
+
print('Fitur terdefinisi:', len(ALL_FEATURES))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
t0=time.time(); X_train = extract_features(train_df); y_train = train_df['Label'].values; print('train', round(time.time()-t0), 's')
|
| 227 |
+
t0=time.time(); X_val = extract_features(val_df); y_val = val_df['Label'].values; print('val', round(time.time()-t0), 's')
|
| 228 |
+
t0=time.time(); X_test = extract_features(test_df); y_test = test_df['Label'].values; print('test', round(time.time()-t0), 's')
|
| 229 |
+
# print('Shape:', X_train.shape, X_val.shape, X_test.shape)
|
| 230 |
+
# print('BM25 std (harus >0, bukan konstan):', round(X_train[:,2].std(), 4))
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
print('Shape:', X_train.shape, X_val.shape, X_test.shape)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
scaler = StandardScaler().fit(X_train)
|
| 240 |
+
X_train_s = scaler.transform(X_train); X_val_s = scaler.transform(X_val); X_test_s = scaler.transform(X_test)
|
| 241 |
+
print('Scaler fit pada train saja. Mean train ~0:', np.round(X_train_s.mean(0)[:3], 3))
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
feat_idx = {f:i for i,f in enumerate(ALL_FEATURES)}
|
| 248 |
+
def get_feat_idx(groups):
|
| 249 |
+
idxs = []
|
| 250 |
+
for g in groups: idxs.extend([feat_idx[f] for f in FEATURE_GROUPS[g]])
|
| 251 |
+
return sorted(set(idxs))
|
| 252 |
+
|
| 253 |
+
L1_SCENARIOS = {
|
| 254 |
+
'TEXT': get_feat_idx(['LEX','SEM_CTX','TOPIC']),
|
| 255 |
+
'META': get_feat_idx(['META']),
|
| 256 |
+
'TEXT+META': get_feat_idx(['LEX','SEM_CTX','TOPIC','META']),
|
| 257 |
+
'LEX+META': get_feat_idx(['LEX','META']),
|
| 258 |
+
'SEM+META': get_feat_idx(['SEM_CTX','META']),
|
| 259 |
+
'TOPIC+META': get_feat_idx(['TOPIC','META']),
|
| 260 |
+
}
|
| 261 |
+
def make_classifiers():
|
| 262 |
+
d = {'LR': LogisticRegression(max_iter=500, random_state=SEED),
|
| 263 |
+
'MLP': MLPClassifier(hidden_layer_sizes=(100,50), max_iter=300, random_state=SEED)}
|
| 264 |
+
return d
|
| 265 |
+
|
| 266 |
+
ablation_l1 = []
|
| 267 |
+
for scen, fidxs in L1_SCENARIOS.items():
|
| 268 |
+
Xtr, Xv = X_train_s[:, fidxs], X_val_s[:, fidxs]
|
| 269 |
+
for cn, clf in make_classifiers().items():
|
| 270 |
+
clf.fit(Xtr, y_train); yp = clf.predict(Xv)
|
| 271 |
+
ablation_l1.append({'scenario':scen, 'classifier':cn, 'n_features':len(fidxs),
|
| 272 |
+
'precision':round(precision_score(y_val,yp),4),
|
| 273 |
+
'recall':round(recall_score(y_val,yp),4),
|
| 274 |
+
'f1':round(f1_score(y_val,yp),4)})
|
| 275 |
+
df_abl1 = pd.DataFrame(ablation_l1).sort_values('f1', ascending=False).reset_index(drop=True)
|
| 276 |
+
print(df_abl1.to_string(index=False))
|
| 277 |
+
best_l1 = df_abl1.iloc[0]
|
| 278 |
+
BEST_L1_SCENARIO = best_l1['scenario']; WINNER_CLASSIFIER = best_l1['classifier']
|
| 279 |
+
print(f"\nBest L1: scenario={BEST_L1_SCENARIO}, clf={WINNER_CLASSIFIER}, F1(val)={best_l1['f1']}")
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
# Grafik ablation L1 (F1 val per skenario, per classifier)
|
| 283 |
+
piv = df_abl1.pivot(index='scenario', columns='classifier', values='f1')
|
| 284 |
+
fig, ax = plt.subplots(figsize=(10,4.5))
|
| 285 |
+
piv.plot(kind='bar', ax=ax, width=0.8)
|
| 286 |
+
ax.set_ylabel('F1 (validasi)'); ax.set_ylim(0, 1.02); ax.set_title('Ablation L1: F1 per Skenario Fitur dan Classifier')
|
| 287 |
+
ax.legend(title='Classifier'); plt.xticks(rotation=15, ha='right'); ax.grid(alpha=0.3, axis='y')
|
| 288 |
+
plt.tight_layout(); plt.savefig(f'{OUT_DIR}/ablation_l1.png', bbox_inches='tight'); plt.show()
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
L2Config = namedtuple('L2Config', ['LEX','SEM_CTX','TOPIC'])
|
| 295 |
+
l2_configs = [L2Config(l,s,t) for l,s,t in product([True,False],repeat=3) if any([l,s,t])]
|
| 296 |
+
ablation_l2 = []
|
| 297 |
+
for cfg in l2_configs:
|
| 298 |
+
groups = ['META']
|
| 299 |
+
if cfg.LEX: groups.append('LEX')
|
| 300 |
+
if cfg.SEM_CTX: groups.append('SEM_CTX')
|
| 301 |
+
if cfg.TOPIC: groups.append('TOPIC')
|
| 302 |
+
fidxs = get_feat_idx(groups)
|
| 303 |
+
clf = make_classifiers()[WINNER_CLASSIFIER]
|
| 304 |
+
clf.fit(X_train_s[:,fidxs], y_train); yp = clf.predict(X_val_s[:,fidxs])
|
| 305 |
+
ablation_l2.append({'LEX':cfg.LEX,'SEM_CTX':cfg.SEM_CTX,'TOPIC':cfg.TOPIC,'n_features':len(fidxs),
|
| 306 |
+
'precision':round(precision_score(y_val,yp),4),'recall':round(recall_score(y_val,yp),4),
|
| 307 |
+
'f1':round(f1_score(y_val,yp),4)})
|
| 308 |
+
df_abl2 = pd.DataFrame(ablation_l2).sort_values('f1', ascending=False).reset_index(drop=True)
|
| 309 |
+
print(df_abl2.to_string(index=False))
|
| 310 |
+
best_l2 = df_abl2.iloc[0]
|
| 311 |
+
best_groups = ['META'] + (['LEX'] if best_l2['LEX'] else []) + (['SEM_CTX'] if best_l2['SEM_CTX'] else []) + (['TOPIC'] if best_l2['TOPIC'] else [])
|
| 312 |
+
BEST_L2_FIDXS = get_feat_idx(best_groups); BEST_L2_FEATS = [ALL_FEATURES[i] for i in BEST_L2_FIDXS]
|
| 313 |
+
print(f"\nBest L2: LEX={best_l2['LEX']} SEM_CTX={best_l2['SEM_CTX']} TOPIC={best_l2['TOPIC']} | {len(BEST_L2_FEATS)} fitur")
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
TEXT_IDX = get_feat_idx(['LEX','SEM_CTX','TOPIC'])
|
| 320 |
+
META_IDX = get_feat_idx(['META'])
|
| 321 |
+
ALL_IDX = get_feat_idx(['LEX','SEM_CTX','TOPIC','META'])
|
| 322 |
+
scen_main = {'Text only':TEXT_IDX, 'Meta only':META_IDX, 'Text+Meta':ALL_IDX}
|
| 323 |
+
clf_main = {'LR': LogisticRegression(max_iter=500, random_state=SEED),
|
| 324 |
+
'MLP': MLPClassifier(hidden_layer_sizes=(50,100,50), activation='relu', solver='adam',
|
| 325 |
+
learning_rate='adaptive', alpha=0.05, max_iter=500, random_state=SEED)}
|
| 326 |
+
rows = []
|
| 327 |
+
for scen, fidxs in scen_main.items():
|
| 328 |
+
for cn, clf in clf_main.items():
|
| 329 |
+
clf.fit(X_train_s[:,fidxs], y_train)
|
| 330 |
+
yv = clf.predict(X_val_s[:,fidxs]); yt = clf.predict(X_test_s[:,fidxs])
|
| 331 |
+
rows.append({'scenario':scen,'classifier':cn,'n_features':len(fidxs),
|
| 332 |
+
'val_p':round(precision_score(y_val,yv),4),'val_r':round(recall_score(y_val,yv),4),'val_f1':round(f1_score(y_val,yv),4),
|
| 333 |
+
'test_p':round(precision_score(y_test,yt),4),'test_r':round(recall_score(y_test,yt),4),'test_f1':round(f1_score(y_test,yt),4)})
|
| 334 |
+
df_ablmain = pd.DataFrame(rows)
|
| 335 |
+
print(df_ablmain.to_string(index=False))
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# Grafik ablation inti (Text/Meta/Text+Meta) F1 test
|
| 339 |
+
fig, ax = plt.subplots(figsize=(9,4.5))
|
| 340 |
+
piv = df_ablmain.pivot(index='scenario', columns='classifier', values='test_f1').reindex(['Meta only','Text only','Text+Meta'])
|
| 341 |
+
piv.plot(kind='bar', ax=ax, width=0.7)
|
| 342 |
+
ax.set_ylabel('F1 (test)'); ax.set_ylim(0,1.02); ax.set_title('Kontribusi Fitur: Text vs Meta vs Text+Meta (F1 test)')
|
| 343 |
+
ax.legend(title='Classifier'); plt.xticks(rotation=0); ax.grid(alpha=0.3, axis='y')
|
| 344 |
+
plt.tight_layout(); plt.savefig(f'{OUT_DIR}/ablation_text_meta.png', bbox_inches='tight'); plt.show()
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
comp_clfs = {'LogReg': LogisticRegression(max_iter=500, random_state=SEED),
|
| 351 |
+
'MLP': MLPClassifier(hidden_layer_sizes=(50,100,50), activation='relu', solver='adam',
|
| 352 |
+
learning_rate='adaptive', alpha=0.05, max_iter=500, random_state=SEED),
|
| 353 |
+
'RandomForest': RandomForestClassifier(n_estimators=300, random_state=SEED, n_jobs=-1)}
|
| 354 |
+
if HAS_XGB:
|
| 355 |
+
comp_clfs['XGBoost'] = xgb.XGBClassifier(n_estimators=300, max_depth=6, random_state=SEED, eval_metric='logloss', verbosity=0)
|
| 356 |
+
rows = []; fitted = {}
|
| 357 |
+
for name, clf in comp_clfs.items():
|
| 358 |
+
clf.fit(X_train_s[:,BEST_L2_FIDXS], y_train); fitted[name] = clf
|
| 359 |
+
yp = clf.predict(X_test_s[:,BEST_L2_FIDXS])
|
| 360 |
+
p,r,f,_ = (precision_score(y_test,yp), recall_score(y_test,yp), f1_score(y_test,yp), None)
|
| 361 |
+
rows.append({'Classifier':name,'Precision':round(p,4),'Recall':round(r,4),'F1':round(f,4),'Accuracy':round(accuracy_score(y_test,yp),4)})
|
| 362 |
+
df_clf = pd.DataFrame(rows).sort_values('F1', ascending=False).reset_index(drop=True)
|
| 363 |
+
print(df_clf.to_string(index=False))
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# Grafik perbandingan classifier
|
| 367 |
+
fig, ax = plt.subplots(figsize=(10,5))
|
| 368 |
+
xi = np.arange(len(df_clf)); w = 0.2
|
| 369 |
+
for k, met in enumerate(['Precision','Recall','F1','Accuracy']):
|
| 370 |
+
ax.bar(xi + (k-1.5)*w, df_clf[met], w, label=met)
|
| 371 |
+
ax.set_xticks(xi); ax.set_xticklabels(df_clf['Classifier']); ax.set_ylim(0.8, 1.005)
|
| 372 |
+
ax.set_ylabel('Skor'); ax.legend(ncol=4, fontsize=8); ax.set_title('Perbandingan Classifier (test 3.700, fitur terbaik)')
|
| 373 |
+
ax.grid(alpha=0.3, axis='y'); plt.tight_layout(); plt.savefig(f'{OUT_DIR}/classifier_comparison.png', bbox_inches='tight'); plt.show()
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
PARAM_GRIDS = {
|
| 380 |
+
'LR' : {'C':[0.01,0.1,1,10], 'solver':['lbfgs','liblinear']},
|
| 381 |
+
'MLP': {'hidden_layer_sizes':[(50,),(100,),(50,50),(100,50),(100,100),(50,100,50),(100,50,100),(100,100,50)],
|
| 382 |
+
'activation':['relu','tanh'], 'solver':['adam'], 'learning_rate':['constant','adaptive'], 'alpha':[0.0001,0.001,0.01,0.05]},
|
| 383 |
+
}
|
| 384 |
+
base = {'LR': LogisticRegression(max_iter=500, random_state=SEED),
|
| 385 |
+
'MLP': MLPClassifier(max_iter=300, random_state=SEED)}[WINNER_CLASSIFIER]
|
| 386 |
+
pg = PARAM_GRIDS[WINNER_CLASSIFIER]
|
| 387 |
+
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)
|
| 388 |
+
gscv = GridSearchCV(base, pg, cv=cv, scoring='f1', n_jobs=-1, verbose=0)
|
| 389 |
+
gscv.fit(X_train_s[:,BEST_L2_FIDXS], y_train)
|
| 390 |
+
print('Best params:', gscv.best_params_); print('Best CV F1 :', round(gscv.best_score_,4))
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
# Final fit pada trainval (train+val), evaluasi sekali pada test
|
| 394 |
+
X_trainval = np.vstack([X_train, X_val]); y_trainval = np.concatenate([y_train, y_val])
|
| 395 |
+
X_trainval_s = scaler.transform(X_trainval)[:, BEST_L2_FIDXS]
|
| 396 |
+
if WINNER_CLASSIFIER == 'LR':
|
| 397 |
+
final_clf = LogisticRegression(**gscv.best_params_, max_iter=500, random_state=SEED)
|
| 398 |
+
else:
|
| 399 |
+
final_clf = MLPClassifier(**gscv.best_params_, max_iter=300, random_state=SEED)
|
| 400 |
+
final_clf.fit(X_trainval_s, y_trainval)
|
| 401 |
+
print(f'Final classifier ({WINNER_CLASSIFIER}) dilatih pada trainval ({len(y_trainval):,} pasangan).')
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
yp_test = final_clf.predict(X_test_s[:, BEST_L2_FIDXS])
|
| 408 |
+
f1_t = f1_score(y_test, yp_test); p_t = precision_score(y_test, yp_test); r_t = recall_score(y_test, yp_test); acc_t = accuracy_score(y_test, yp_test)
|
| 409 |
+
print('='*55); print('HASIL STAGE-2 ISOLATED (test 3.700)'); print('='*55)
|
| 410 |
+
print(f'Precision={p_t:.4f} Recall={r_t:.4f} F1={f1_t:.4f} Acc={acc_t:.4f}')
|
| 411 |
+
print(); print(classification_report(y_test, yp_test, target_names=['Non-Duplicate','Duplicate']))
|
| 412 |
+
cm = confusion_matrix(y_test, yp_test); print('Confusion Matrix [TN FP / FN TP]:'); print(cm)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
proba = final_clf.predict_proba(X_test_s[:,BEST_L2_FIDXS])[:,1] if hasattr(final_clf,'predict_proba') else final_clf.decision_function(X_test_s[:,BEST_L2_FIDXS])
|
| 416 |
+
fig, axes = plt.subplots(1, 3, figsize=(16, 4.5))
|
| 417 |
+
im = axes[0].imshow(cm, cmap='Blues')
|
| 418 |
+
for (i,j), v in np.ndenumerate(cm): axes[0].text(j, i, str(v), ha='center', va='center', fontsize=13)
|
| 419 |
+
axes[0].set_xticks([0,1]); axes[0].set_xticklabels(['non-dup','dup']); axes[0].set_yticks([0,1]); axes[0].set_yticklabels(['non-dup','dup'])
|
| 420 |
+
axes[0].set_xlabel('Prediksi'); axes[0].set_ylabel('Aktual'); axes[0].set_title(f'Confusion Matrix ({WINNER_CLASSIFIER})')
|
| 421 |
+
prec, rec, _ = precision_recall_curve(y_test, proba)
|
| 422 |
+
axes[1].plot(rec, prec, color='#cc3311'); axes[1].set_xlabel('Recall'); axes[1].set_ylabel('Precision')
|
| 423 |
+
axes[1].set_title(f'PR Curve (AP={average_precision_score(y_test, proba):.3f})'); axes[1].grid(alpha=0.3)
|
| 424 |
+
fpr, tpr, _ = roc_curve(y_test, proba)
|
| 425 |
+
axes[2].plot(fpr, tpr, color='#4477aa'); axes[2].plot([0,1],[0,1],'--',color='gray')
|
| 426 |
+
axes[2].set_xlabel('FPR'); axes[2].set_ylabel('TPR'); axes[2].set_title(f'ROC (AUC={auc(fpr,tpr):.3f})'); axes[2].grid(alpha=0.3)
|
| 427 |
+
plt.tight_layout(); plt.savefig(f'{OUT_DIR}/best_model_curves.png', bbox_inches='tight'); plt.show()
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
key_feats = ['cosine_tfidf_w','cosine_sbert_ft','time_diff_created','same_component']
|
| 434 |
+
idx = {f:i for i,f in enumerate(ALL_FEATURES)}
|
| 435 |
+
fig, axes = plt.subplots(1, 4, figsize=(16, 3.6))
|
| 436 |
+
for ax, fn in zip(axes, key_feats):
|
| 437 |
+
col = X_test[:, idx[fn]]; dup = col[y_test==1]; non = col[y_test==0]
|
| 438 |
+
hi = np.percentile(col, 95) if fn=='time_diff_created' else col.max()
|
| 439 |
+
bins = np.linspace(col.min(), hi+1e-9, 40)
|
| 440 |
+
ax.hist(non, bins=bins, alpha=0.6, label='non-dup', color='#4477aa', density=True)
|
| 441 |
+
ax.hist(dup, bins=bins, alpha=0.6, label='dup', color='#ee6677', density=True)
|
| 442 |
+
ax.set_title(fn, fontsize=9); ax.legend(fontsize=7)
|
| 443 |
+
plt.suptitle('Distribusi Fitur: Duplikat vs Non-duplikat (test)')
|
| 444 |
+
plt.tight_layout(); plt.savefig(f'{OUT_DIR}/feature_distributions.png', bbox_inches='tight'); plt.show()
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
corr = np.corrcoef(X_train.T)
|
| 448 |
+
fig, ax = plt.subplots(figsize=(9, 7.5))
|
| 449 |
+
im = ax.imshow(corr, cmap='coolwarm', vmin=-1, vmax=1)
|
| 450 |
+
ax.set_xticks(range(len(ALL_FEATURES))); ax.set_xticklabels(ALL_FEATURES, rotation=90, fontsize=7)
|
| 451 |
+
ax.set_yticks(range(len(ALL_FEATURES))); ax.set_yticklabels(ALL_FEATURES, fontsize=7)
|
| 452 |
+
for i in range(len(ALL_FEATURES)):
|
| 453 |
+
for j in range(len(ALL_FEATURES)):
|
| 454 |
+
ax.text(j, i, f'{corr[i,j]:.1f}', ha='center', va='center', fontsize=5.5, color='white' if abs(corr[i,j])>0.6 else 'black')
|
| 455 |
+
plt.colorbar(im, fraction=0.046); plt.title('Korelasi Antar-Fitur (train)')
|
| 456 |
+
plt.tight_layout(); plt.savefig(f'{OUT_DIR}/feature_correlation.png', bbox_inches='tight'); plt.show()
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
pi = permutation_importance(final_clf, X_test_s[:,BEST_L2_FIDXS], y_test, n_repeats=10, random_state=SEED, n_jobs=-1)
|
| 463 |
+
order = np.argsort(pi.importances_mean)
|
| 464 |
+
fig, ax = plt.subplots(figsize=(9,5))
|
| 465 |
+
ax.barh([BEST_L2_FEATS[i] for i in order], pi.importances_mean[order], xerr=pi.importances_std[order], color='#aa3377')
|
| 466 |
+
ax.set_title(f'Permutation Importance ({WINNER_CLASSIFIER}, test)'); ax.tick_params(labelsize=8)
|
| 467 |
+
plt.tight_layout(); plt.savefig(f'{OUT_DIR}/feature_importance.png', bbox_inches='tight'); plt.show()
|
| 468 |
+
imp_df = pd.DataFrame({'feature':BEST_L2_FEATS,'perm_importance':pi.importances_mean,'perm_std':pi.importances_std}).sort_values('perm_importance', ascending=False)
|
| 469 |
+
print(imp_df.to_string(index=False))
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
# Ambil N korpus dari Stage-1 (untuk proyeksi O(N) Ben). Fallback bila file tak ada.
|
| 476 |
+
BEN_N_CORPUS = None
|
| 477 |
+
for p in [f'{INPUT_DIR}/retrieval_efficiency.json', f'{OUT_DIR}/retrieval_efficiency.json',
|
| 478 |
+
'./output_stage1/retrieval_efficiency.json', '/kaggle/working/retrieval_efficiency.json']:
|
| 479 |
+
if Path(p).exists():
|
| 480 |
+
try: BEN_N_CORPUS = int(json.load(open(p)).get('corpus_size')); break
|
| 481 |
+
except Exception: pass
|
| 482 |
+
if BEN_N_CORPUS is None:
|
| 483 |
+
BEN_N_CORPUS = 31916 # ganti dgn corpus_size Stage-1 Anda bila file tak terbaca
|
| 484 |
+
print(f'[catatan] retrieval_efficiency.json tak ditemukan, pakai N={BEN_N_CORPUS} (sesuaikan).')
|
| 485 |
+
print('N korpus (untuk O(N)):', BEN_N_CORPUS)
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
# Ukur ms/report = waktu klasifikasi 1 query thd K kandidat (batch). Ulang beberapa query.
|
| 489 |
+
def time_per_report(n_reports=20, K=K_RETRIEVAL):
|
| 490 |
+
base = test_df.reset_index(drop=True); idxs = list(range(len(base)))
|
| 491 |
+
times = []
|
| 492 |
+
for r in range(n_reports):
|
| 493 |
+
sel = [(idxs[(r*K + j) % len(idxs)]) for j in range(K)] # K baris sbg kandidat 1 query
|
| 494 |
+
batch = base.iloc[sel]
|
| 495 |
+
t0 = time.perf_counter()
|
| 496 |
+
fr = extract_features(batch); frs = scaler.transform(fr)[:, BEST_L2_FIDXS]; _ = final_clf.predict(frs)
|
| 497 |
+
times.append((time.perf_counter()-t0)*1000)
|
| 498 |
+
return float(np.mean(times)), float(np.std(times))
|
| 499 |
+
ms_report, ms_std = time_per_report()
|
| 500 |
+
ms_pair = ms_report / K_RETRIEVAL
|
| 501 |
+
print(f'Stage-2 ms/report (batch K={K_RETRIEVAL}): {ms_report:.2f} ms (std {ms_std:.2f})')
|
| 502 |
+
print(f' -> setara ms/pair: {ms_pair:.3f} ms')
|
| 503 |
+
print('Catatan: total Two-Stage = Stage1_ms + ms/report ini (ditambahkan di notebook E2E).')
|
| 504 |
+
eff = {'ms_per_report_OK_batch': round(ms_report,3), 'ms_per_pair_batched': round(ms_pair,4),
|
| 505 |
+
'K_retrieval': K_RETRIEVAL, 'N_corpus_for_ON': int(BEN_N_CORPUS)}
|
| 506 |
+
json.dump(eff, open(f'{OUT_DIR}/stage2_efficiency.json','w'), indent=2)
|
| 507 |
+
print('Disimpan: stage2_efficiency.json')
|
| 508 |
+
# Perbandingan Ben (angka diisi dari notebook replikasi Ben Anda)
|
| 509 |
+
# BEN_AVG_MS_PAIR = <hasil replikasi>; ben_ms_report = BEN_AVG_MS_PAIR * BEN_N_CORPUS
|
| 510 |
+
print('\n[Ben] isi BEN_AVG_MS_PAIR dari notebook replikasi Anda, lalu Ben O(N) ms/report = BEN_AVG_MS_PAIR * N.')
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
pickle.dump({'clf':final_clf,'best_params':gscv.best_params_,'feature_idx':BEST_L2_FIDXS,
|
| 517 |
+
'feature_names':BEST_L2_FEATS,'all_features':ALL_FEATURES,'feature_groups':FEATURE_GROUPS,
|
| 518 |
+
'winner_clf':WINNER_CLASSIFIER}, open(f'{OUT_DIR}/classifier.pkl','wb'))
|
| 519 |
+
pickle.dump(scaler, open(f'{OUT_DIR}/scaler.pkl','wb'))
|
| 520 |
+
pickle.dump({'tfidf_c':tfidf_c,'tfidf_w':tfidf_w,'count_vec':count_vec,'lda_model':lda_model,
|
| 521 |
+
'tfidf_lsa':tfidf_lsa,'lsa_model':lsa_model,'DF_COUNT':DF_COUNT,'N_DOCS':N_DOCS,
|
| 522 |
+
'BM25_AVGDL':BM25_AVGDL,'sbert_model_name':HF_SBERT_FT}, open(f'{OUT_DIR}/feature_extractors.pkl','wb'))
|
| 523 |
+
df_abl1.to_csv(f'{OUT_DIR}/ablation_l1.csv', index=False); df_abl2.to_csv(f'{OUT_DIR}/ablation_l2.csv', index=False)
|
| 524 |
+
df_ablmain.to_csv(f'{OUT_DIR}/ablation_text_meta.csv', index=False); df_clf.to_csv(f'{OUT_DIR}/classifier_comparison.csv', index=False)
|
| 525 |
+
summary = {'winner_classifier':WINNER_CLASSIFIER,'best_params':gscv.best_params_,'n_features':len(BEST_L2_FEATS),
|
| 526 |
+
'features':BEST_L2_FEATS,'test':{'F1':float(f1_t),'Precision':float(p_t),'Recall':float(r_t),'Accuracy':float(acc_t)},
|
| 527 |
+
'efficiency':eff,'split':{'train':len(train_df),'val':len(val_df),'test':len(test_df)}}
|
| 528 |
+
json.dump(summary, open(f'{OUT_DIR}/summary.json','w'), indent=2)
|
| 529 |
+
print('Artefak tersimpan di', OUT_DIR)
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
RUN_HARD_NEG = True # set False utk melewati
|
| 536 |
+
if RUN_HARD_NEG:
|
| 537 |
+
# Untuk tiap query positif (bug1 pada test_dup), cari kandidat paling mirip (TF-IDF word) yg BUKAN partner -> hard negative
|
| 538 |
+
pos = test_df[test_df['Label']==1].reset_index(drop=True)
|
| 539 |
+
pool_text = corpus_train + pos['text1'].tolist()
|
| 540 |
+
Vpool = tfidf_w.transform(pool_text); Vq = tfidf_w.transform(pos['text1'].tolist())
|
| 541 |
+
sims = (Vq @ Vpool.T)
|
| 542 |
+
easy_neg_cos = X_test[:, feat_idx['cosine_tfidf_w']][y_test==0]
|
| 543 |
+
hard_neg_cos = np.array([np.sort(sims.getrow(i).toarray().ravel())[-2] for i in range(len(pos))]) # -2: lewati diri sendiri
|
| 544 |
+
print('Median cosine_tfidf_w:')
|
| 545 |
+
print(f' negatif Ben (acak) : {np.median(easy_neg_cos):.3f}')
|
| 546 |
+
print(f' hard-neg (top mirip) : {np.median(hard_neg_cos):.3f}')
|
| 547 |
+
fig, ax = plt.subplots(figsize=(8,4.5))
|
| 548 |
+
ax.hist(easy_neg_cos, bins=40, alpha=0.6, density=True, label='negatif Ben (acak/mudah)', color='#4477aa')
|
| 549 |
+
ax.hist(hard_neg_cos, bins=40, alpha=0.6, density=True, label='hard-neg (Top-K retrieval)', color='#ee6677')
|
| 550 |
+
ax.set_xlabel('cosine_tfidf_w'); ax.set_ylabel('densitas'); ax.legend()
|
| 551 |
+
ax.set_title('Easy vs Hard Negative: distribusi kemiripan tekstual')
|
| 552 |
+
plt.tight_layout(); plt.savefig(f'{OUT_DIR}/easy_vs_hard_negative.png', bbox_inches='tight'); plt.show()
|
| 553 |
+
print('\nInterpretasi: hard-neg punya cosine jauh lebih tinggi -> lebih sulit dipisahkan.')
|
| 554 |
+
print('Konsekuensi: F1 pada Two-Stage E2E (negatif = Top-K retrieval) diperkirakan LEBIH RENDAH')
|
| 555 |
+
print('daripada F1 isolated ini. Ini temuan kunci, bukan kelemahan implementasi.')
|
| 556 |
+
else:
|
| 557 |
+
print('Dilewati (RUN_HARD_NEG=False).')
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
# try:
|
| 564 |
+
# from kaggle_secrets import UserSecretsClient
|
| 565 |
+
# HF_TOKEN = UserSecretsClient().get_secret('HF_TOKEN')
|
| 566 |
+
# except Exception:
|
| 567 |
+
# HF_TOKEN = os.environ.get('HF_TOKEN', None)
|
| 568 |
+
# if HF_TOKEN:
|
| 569 |
+
# from huggingface_hub import HfApi, create_repo
|
| 570 |
+
# api = HfApi(token=HF_TOKEN)
|
| 571 |
+
# create_repo(HF_REPO, repo_type='dataset', exist_ok=True, token=HF_TOKEN)
|
| 572 |
+
# for fn in ['classifier.pkl','scaler.pkl','feature_extractors.pkl','summary.json']:
|
| 573 |
+
# p = Path(f'{OUT_DIR}/{fn}')
|
| 574 |
+
# if p.exists(): api.upload_file(path_or_fileobj=str(p), path_in_repo=fn, repo_id=HF_REPO, repo_type='dataset', token=HF_TOKEN)
|
| 575 |
+
# print('Upload selesai:', HF_REPO)
|
| 576 |
+
# else:
|
| 577 |
+
# print('HF_TOKEN tidak ada, skip upload.')
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
from huggingface_hub import notebook_login
|
| 581 |
+
notebook_login()
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
from huggingface_hub import HfApi, create_repo
|
| 585 |
+
api = HfApi()
|
| 586 |
+
create_repo(HF_REPO, repo_type='dataset', exist_ok=True)
|
| 587 |
+
# upload SELURUH isi OUT_DIR sekaligus -> tidak ada file/sidecar yang ketinggalan
|
| 588 |
+
api.upload_folder(folder_path=OUT_DIR, repo_id=HF_REPO, repo_type='dataset',
|
| 589 |
+
commit_message='Stage-2 artefak (12 fitur, tanpa gensim)')
|
| 590 |
+
print('Selesai:', f'https://huggingface.co/datasets/{HF_REPO}')
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
|
ablation_l1.csv
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
scenario,classifier,n_features,precision,recall,f1
|
| 2 |
-
LEX+META,MLP,9,0.
|
|
|
|
| 3 |
META,MLP,6,1.0,0.9932,0.9966
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
LEX+META,LR,9,0.
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
TEXT+META,LR,15,0.9986,0.9865,0.9925
|
| 10 |
META,LR,6,1.0,0.9845,0.9922
|
| 11 |
-
SEM+META,LR,
|
| 12 |
-
TEXT,LR,
|
| 13 |
-
TEXT,MLP,
|
|
|
|
| 1 |
scenario,classifier,n_features,precision,recall,f1
|
| 2 |
+
LEX+META,MLP,9,0.998,0.9966,0.9973
|
| 3 |
+
TOPIC+META,MLP,8,1.0,0.9939,0.997
|
| 4 |
META,MLP,6,1.0,0.9932,0.9966
|
| 5 |
+
SEM+META,MLP,7,0.9986,0.9926,0.9956
|
| 6 |
+
TEXT+META,MLP,12,0.9993,0.9899,0.9946
|
| 7 |
+
LEX+META,LR,9,0.9986,0.9899,0.9942
|
| 8 |
+
TOPIC+META,LR,8,0.9959,0.9905,0.9932
|
| 9 |
+
TEXT+META,LR,12,0.9986,0.9872,0.9929
|
|
|
|
| 10 |
META,LR,6,1.0,0.9845,0.9922
|
| 11 |
+
SEM+META,LR,7,0.9986,0.9845,0.9915
|
| 12 |
+
TEXT,LR,6,0.9891,0.9189,0.9527
|
| 13 |
+
TEXT,MLP,6,0.9897,0.9128,0.9497
|
ablation_l1.png
ADDED
|
Git LFS Details
|
ablation_l2.csv
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
LEX,
|
| 2 |
-
True,False,
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
False,True,False,
|
| 6 |
-
True,True,
|
| 7 |
-
|
| 8 |
-
|
|
|
|
| 1 |
+
LEX,SEM_CTX,TOPIC,n_features,precision,recall,f1
|
| 2 |
+
True,False,False,9,0.998,0.9966,0.9973
|
| 3 |
+
False,False,True,8,1.0,0.9939,0.997
|
| 4 |
+
True,False,True,11,0.9973,0.9966,0.997
|
| 5 |
+
False,True,False,7,0.9986,0.9926,0.9956
|
| 6 |
+
True,True,True,12,0.9993,0.9899,0.9946
|
| 7 |
+
True,True,False,10,0.998,0.9912,0.9946
|
| 8 |
+
False,True,True,9,0.9986,0.9899,0.9942
|
ablation_text_meta.csv
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
scenario,classifier,n_features,val_p,val_r,val_f1,test_p,test_r,test_f1
|
| 2 |
-
Text only,LR,
|
| 3 |
-
Text only,MLP,
|
| 4 |
Meta only,LR,6,1.0,0.9845,0.9922,1.0,0.9275,0.9624
|
| 5 |
Meta only,MLP,6,1.0,0.9932,0.9966,0.9985,0.9644,0.9812
|
| 6 |
-
Text+Meta,LR,
|
| 7 |
-
Text+Meta,MLP,
|
|
|
|
| 1 |
scenario,classifier,n_features,val_p,val_r,val_f1,test_p,test_r,test_f1
|
| 2 |
+
Text only,LR,6,0.9891,0.9189,0.9527,0.9608,0.9417,0.9511
|
| 3 |
+
Text only,MLP,6,0.9884,0.9196,0.9527,0.9472,0.9445,0.9459
|
| 4 |
Meta only,LR,6,1.0,0.9845,0.9922,1.0,0.9275,0.9624
|
| 5 |
Meta only,MLP,6,1.0,0.9932,0.9966,0.9985,0.9644,0.9812
|
| 6 |
+
Text+Meta,LR,12,0.9986,0.9872,0.9929,0.9928,0.9787,0.9857
|
| 7 |
+
Text+Meta,MLP,12,0.998,0.9919,0.9949,0.9928,0.9872,0.99
|
ablation_text_meta.png
ADDED
|
Git LFS Details
|
best_model_curves.png
ADDED
|
Git LFS Details
|
classifier.pkl
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:160dd2c2705a1c2e7106b08df6f75d391e0a8072b5364024fa3fced486334f77
|
| 3 |
+
size 352094
|
classifier_comparison.csv
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
Classifier,Precision,Recall,F1,Accuracy
|
| 2 |
-
MLP,0.9942,0.
|
| 3 |
-
LogReg,0.
|
| 4 |
-
|
| 5 |
-
|
|
|
|
| 1 |
Classifier,Precision,Recall,F1,Accuracy
|
| 2 |
+
MLP,0.9942,0.9687,0.9813,0.993
|
| 3 |
+
LogReg,0.9926,0.9559,0.9739,0.9903
|
| 4 |
+
XGBoost,0.9186,0.9787,0.9477,0.9795
|
| 5 |
+
RandomForest,0.8809,0.9787,0.9272,0.9708
|
classifier_comparison.png
ADDED
|
Git LFS Details
|
easy_vs_hard_negative.png
ADDED
|
Git LFS Details
|
feature_correlation.png
ADDED
|
Git LFS Details
|
feature_distributions.png
ADDED
|
Git LFS Details
|
feature_extractors.pkl
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f4aa29cbf3a6b4d60a251435d128fc5964ff4c52850825b8471fd01900823eca
|
| 3 |
+
size 13566511
|
feature_importance.png
ADDED
|
Git LFS Details
|
scaler.pkl
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:264e83e73ae96d9ae982f8b4a6bd3845cd958e4f7580e88f7019c285e59208c9
|
| 3 |
+
size 738
|
stage2_efficiency.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
{
|
| 2 |
-
"ms_per_report_OK_batch":
|
| 3 |
-
"ms_per_pair_batched":
|
| 4 |
"K_retrieval": 50,
|
| 5 |
"N_corpus_for_ON": 31916
|
| 6 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"ms_per_report_OK_batch": 1866.907,
|
| 3 |
+
"ms_per_pair_batched": 37.3381,
|
| 4 |
"K_retrieval": 50,
|
| 5 |
"N_corpus_for_ON": 31916
|
| 6 |
}
|
summary.json
CHANGED
|
@@ -1,23 +1,21 @@
|
|
| 1 |
{
|
| 2 |
"winner_classifier": "MLP",
|
| 3 |
"best_params": {
|
| 4 |
-
"activation": "
|
| 5 |
-
"alpha": 0.
|
| 6 |
"hidden_layer_sizes": [
|
| 7 |
-
|
| 8 |
100,
|
| 9 |
50
|
| 10 |
],
|
| 11 |
"learning_rate": "constant",
|
| 12 |
"solver": "adam"
|
| 13 |
},
|
| 14 |
-
"n_features":
|
| 15 |
"features": [
|
| 16 |
"cosine_tfidf_c",
|
| 17 |
"cosine_tfidf_w",
|
| 18 |
"bm25_score",
|
| 19 |
-
"cosine_lda",
|
| 20 |
-
"cosine_lsa",
|
| 21 |
"same_component",
|
| 22 |
"same_priority",
|
| 23 |
"same_version",
|
|
@@ -26,14 +24,14 @@
|
|
| 26 |
"log_time_diff"
|
| 27 |
],
|
| 28 |
"test": {
|
| 29 |
-
"F1": 0.
|
| 30 |
-
"Precision": 0.
|
| 31 |
-
"Recall": 0.
|
| 32 |
-
"Accuracy": 0.
|
| 33 |
},
|
| 34 |
"efficiency": {
|
| 35 |
-
"ms_per_report_OK_batch":
|
| 36 |
-
"ms_per_pair_batched":
|
| 37 |
"K_retrieval": 50,
|
| 38 |
"N_corpus_for_ON": 31916
|
| 39 |
},
|
|
|
|
| 1 |
{
|
| 2 |
"winner_classifier": "MLP",
|
| 3 |
"best_params": {
|
| 4 |
+
"activation": "tanh",
|
| 5 |
+
"alpha": 0.001,
|
| 6 |
"hidden_layer_sizes": [
|
| 7 |
+
50,
|
| 8 |
100,
|
| 9 |
50
|
| 10 |
],
|
| 11 |
"learning_rate": "constant",
|
| 12 |
"solver": "adam"
|
| 13 |
},
|
| 14 |
+
"n_features": 9,
|
| 15 |
"features": [
|
| 16 |
"cosine_tfidf_c",
|
| 17 |
"cosine_tfidf_w",
|
| 18 |
"bm25_score",
|
|
|
|
|
|
|
| 19 |
"same_component",
|
| 20 |
"same_priority",
|
| 21 |
"same_version",
|
|
|
|
| 24 |
"log_time_diff"
|
| 25 |
],
|
| 26 |
"test": {
|
| 27 |
+
"F1": 0.985632183908046,
|
| 28 |
+
"Precision": 0.9956458635703919,
|
| 29 |
+
"Recall": 0.9758179231863442,
|
| 30 |
+
"Accuracy": 0.9945945945945946
|
| 31 |
},
|
| 32 |
"efficiency": {
|
| 33 |
+
"ms_per_report_OK_batch": 1866.907,
|
| 34 |
+
"ms_per_pair_batched": 37.3381,
|
| 35 |
"K_retrieval": 50,
|
| 36 |
"N_corpus_for_ON": 31916
|
| 37 |
},
|