May i know why SVM, NN and logistic regression are not good once a set of 3K labelled data is available ? How can i make the prediction more accurate with LLMs
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Why Traditional ML (SVM, NN, Logistic Regression) Can Be Less Ideal with 3K Labeled Examples
Issue
Why It Matters for 3K Examples
How LLMs Address It
Feature Engineering Bottleneck
You need to manually design features (e.g., method name length, presence of keywords, parameter counts). This is time‑consuming and often misses subtle semantic cues.
LLMs are pre‑trained on massive code corpora, so they already “know” the semantics of method names, parameter types, return types, and data‑flow patterns. You can feed the raw method signature (or even the full method body) directly to the model.
Limited Contextual Understanding
Traditional models treat each method in isolation. They can’t see how a method interacts with other parts of the codebase (e.g., which external libraries it calls, whether it’s part of a larger data‑flow chain).
LLMs can ingest the surrounding code context (e.g., the class, imports, or even the whole file) and understand the broader data‑flow. This is crucial for source/sink detection, where the context often determines the label.
Generalization to New APIs / Libraries
With only 3K examples you may not have seen every possible API. When a new library appears, the model may misclassify because it lacks the relevant patterns.
LLMs have seen billions of lines of code, including many libraries you may never have in your training set. They can generalize from similar patterns (e.g., “readFile” → source, “writeLog” → sink).
Cold‑Start for Rare Classes
If one of the three classes (source, sink, neither) is under‑represented, traditional classifiers may over‑fit to the majority class, leading to poor recall for the minority.
LLMs can be prompted with few‑shot examples that explicitly balance the classes, improving recall for rare categories.
Interpretability & Debugging
It’s hard to understand why a traditional model mis‑labels a method, especially when the decision is based on a high‑dimensional feature vector.
LLMs can be asked to explain their reasoning (chain‑of‑thought prompting). This makes debugging easier and lets you iteratively improve prompts.
Scalability of Feature Vectors
As you add more features (e.g., cyclomatic complexity, call‑graph distance), the feature vector grows, potentially hurting performance and interpretability.
LLMs operate on the textual representation, so you can keep the input simple (method signature + optional context) without bloating the feature space.
How to Make Predictions More Accurate with LLMs
Below are proven strategies, ranked by expected impact. You can adopt one or combine several for a hybrid approach.
1. Fine‑Tune a Code‑Pretrained LLM(Best overall accuracy)
Fine‑tuning a model that already understands code gives you the highest accuracy with a modest amount of labeled data.
python
from transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments
# Choose a code‑pretrained model
model_name = "microsoft/codebert-base" # or graphcodebert, codet5, etc.
model = AutoModelForSequenceClassification.from_pretrained(
model_name,
num_labels=3 # source, sink, neither
)
# Prepare your data (method signatures + optional context)
train_dataset = ... # tokenized signatures + labels
val_dataset = ... # tokenized signatures + labels
training_args = TrainingArguments(
output_dir="./source_sink_classifier",
num_train_epochs=5,
per_device_train_batch_size=16,
evaluation_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1_macro",
learning_rate=2e-5,
weight_decay=0.01,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=val_dataset,
compute_metrics=compute_metrics,
)
trainer.train()
Why it works
Leverages billions of code tokens → strong semantic understanding.
3K examples are enough for fine‑tuning (typical F1 > 90% on source‑sink tasks).
You can later use the fine‑tuned model for zero‑shot or few‑shot inference on new codebases.
Tips
Use method signatures (name + parameters + return type) as the primary input.
Optionally prepend a short context (e.g., “This method is called from processUserInput”).
Experiment with prompt templates that include a brief description of the task.
2. Retrieval‑Augmented Generation (RAG) with Your 3K Labeled Set
When you have a curated labeled set, you can turn it into a knowledge base that the LLM queries at inference time.
python
from sentence_transformers import SentenceTransformer
import faiss
# 1. Embed all labeled examples
embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
embeds = embedder.encode([m.signature for m in labeled_methods])
# 2. Build a FAISS index for fast nearest‑neighbor search
index = faiss.IndexFlatL2(embeds.shape[1])
index.add(embeds)
def classify_with_retrieval(new_method, k=5):
query_emb = embedder.encode([new_method.signature])
_, indices = index.search(query_emb, k)
# Build a few‑shot prompt from the k nearest labeled examples
examples = [labeled_methods[i] for i in indices[0]]
prompt = f"""
Below are {k} similar methods and their labels:
{format_examples(examples)}
Now classify this method:
Method: {new_method.signature}
Answer: SOURCE / SINK / NEITHER
"""
return llm.predict(prompt)
Why it works
Dynamically selects the most relevant examples, giving the LLM a personalized context.
No fine‑tuning required; works with any API‑based LLM (GPT‑4, Claude, etc.).
Particularly useful when your labeled set is domain‑specific (e.g., a proprietary framework).
Ask the LLM to reason step‑by‑step, then aggregate multiple reasoning paths.
python
def cot_classify(method, n_samples=5):
prompt = f"""
Analyze the following method and classify it as SOURCE, SINK, or NEITHER.
Provide a short chain‑of‑thought before giving the final answer.
Method: {method.signature}
"""
# Sample multiple reasoning paths (temperature > 0)
responses = [llm.predict(prompt, temperature=0.7) for _ in range(n_samples)]
# Extract the final label from each response
labels = [extract_label(r) for r in responses]
# Majority vote (self‑consistency)
return most_common(labels), confidence(labels)
Why it works
LLMs often make better decisions when they explain their reasoning.
Sampling multiple paths and taking a majority vote reduces variance and improves robustness.
4. Ensemble Multiple LLM Strategies
Combine the strengths of different approaches (fine‑tuned model, retrieval, CoT) to get a robust final prediction.
python
def ensemble_predict(method, labeled_data):
preds = []
# 1. Fine‑tuned CodeBERT
preds.append(finetuned_codebert.predict(method))
# 2. Retrieval‑augmented GPT‑4
preds.append(retrieval_gpt4(method, labeled_data, k=5))
# 3. Zero‑shot GPT‑4 with CoT
preds.append(cot_gpt4(method))
# 4. Traditional ML using LLM‑extracted features (optional)
features = extract_llm_features(method)
preds.append(xgboost_classifier.predict(features))
# Weighted voting (weights tuned on a validation set)
weights = [0.4, 0.3, 0.15, 0.15] # Example; adjust based on validation
return weighted_vote(preds, weights)
Why it works
Diversifies the decision process, mitigating individual model biases.
You can allocate higher weight to the model that performs best on your validation set.
5. Active Learning Loop
With 3K examples you can still improve efficiency by focusing on the hardest cases.
python
def active_learning(initial_labeled, unlabeled_pool):
# 1. Train an initial model
model = train_model(initial_labeled)
while budget_remaining:
# 2. Predict on unlabeled pool
probs = model.predict(unlabeled_pool, return_confidence=True)
# 3. Select uncertain examples (low confidence or conflicting predictions)
uncertain = select_uncertain(probs, n=50)
# 4. Get LLM predictions on those examples
llm_labels = [llm_predict(m) for