Spaces:
Sleeping
Sleeping
Merge branch 'aditizyy:main' into main
Browse files- README.md +3 -3
- deepset/roberta-base-squad2 +175 -0
- sentence-transformers/all-mpnet-base-v2 +84 -0
README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
Generate personalized MCQs, short answer, and true/false questions using Hugging Face Transformers and a Streamlit UI.
|
| 4 |
|
| 5 |
## π‘ Features
|
| 6 |
-
-
|
| 7 |
- Streamlit-based frontend
|
| 8 |
- Cosine Similarity, BLEU-1, ROUGE -1 AND ROUGE-L Evaluation
|
| 9 |
- Fine-tuned FLAN-T5 integration
|
|
@@ -45,7 +45,7 @@ custom-quiz-generator/
|
|
| 45 |
βββ outputs/ # Stores generated questions/outputs
|
| 46 |
βββ valhalla/ # T5-based fine-tuned models
|
| 47 |
βββ requirements.txt # Project dependencies
|
| 48 |
-
βββ
|
| 49 |
βββ README.md # Project documentation
|
| 50 |
βββ .gitignore # Git ignore rules
|
| 51 |
-
```
|
|
|
|
| 3 |
Generate personalized MCQs, short answer, and true/false questions using Hugging Face Transformers and a Streamlit UI.
|
| 4 |
|
| 5 |
## π‘ Features
|
| 6 |
+
- Question generator (MCQ, short answer, true/false)
|
| 7 |
- Streamlit-based frontend
|
| 8 |
- Cosine Similarity, BLEU-1, ROUGE -1 AND ROUGE-L Evaluation
|
| 9 |
- Fine-tuned FLAN-T5 integration
|
|
|
|
| 45 |
βββ outputs/ # Stores generated questions/outputs
|
| 46 |
βββ valhalla/ # T5-based fine-tuned models
|
| 47 |
βββ requirements.txt # Project dependencies
|
| 48 |
+
βββ FineTuneAndEvaluationscores.ipynb # Evaluation notebook
|
| 49 |
βββ README.md # Project documentation
|
| 50 |
βββ .gitignore # Git ignore rules
|
| 51 |
+
```
|
deepset/roberta-base-squad2
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
Automatically generated by Colab.
|
| 4 |
+
Original file is located at
|
| 5 |
+
https://colab.research.google.com/drive/1MWc3B3JSbW5VvEuftDi2WoCjUWN1CtVj
|
| 6 |
+
"""
|
| 7 |
+
pip install transformers datasets evaluate accelerate
|
| 8 |
+
data_files = {
|
| 9 |
+
"train": "./train.json", # If saved in current working directory
|
| 10 |
+
"validation": "./validation.json"
|
| 11 |
+
}
|
| 12 |
+
from google.colab import files
|
| 13 |
+
uploaded = files.upload() # Select and upload your train.json and validation.json files
|
| 14 |
+
from google.colab import files
|
| 15 |
+
uploaded = files.upload() # Select and upload your train.json and validation.json files
|
| 16 |
+
import json
|
| 17 |
+
import pandas as pd
|
| 18 |
+
from datasets import Dataset, DatasetDict
|
| 19 |
+
with open("train.json", "r") as f:
|
| 20 |
+
train_data = json.load(f)
|
| 21 |
+
with open("validation.json", "r") as f:
|
| 22 |
+
validation_data = json.load(f)
|
| 23 |
+
train_list = train_data.get("data", [])
|
| 24 |
+
validation_list = validation_data.get("data", [])
|
| 25 |
+
train_df = pd.DataFrame(train_list)
|
| 26 |
+
validation_df = pd.DataFrame(validation_list)
|
| 27 |
+
train_dataset = Dataset.from_pandas(train_df)
|
| 28 |
+
validation_dataset = Dataset.from_pandas(validation_df)
|
| 29 |
+
dataset = DatasetDict({
|
| 30 |
+
"train": train_dataset,
|
| 31 |
+
"validation": validation_dataset
|
| 32 |
+
})
|
| 33 |
+
print(dataset)
|
| 34 |
+
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
|
| 35 |
+
model_checkpoint = "deepset/roberta-base-squad2"
|
| 36 |
+
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
|
| 37 |
+
model = AutoModelForQuestionAnswering.from_pretrained(model_checkpoint)
|
| 38 |
+
def prepare_features(examples):
|
| 39 |
+
tokenized_examples = {
|
| 40 |
+
"input_ids": [],
|
| 41 |
+
"attention_mask": [],
|
| 42 |
+
"offset_mapping": [],
|
| 43 |
+
"overflow_to_sample_mapping": [],
|
| 44 |
+
"start_positions": [],
|
| 45 |
+
"end_positions": [],
|
| 46 |
+
"example_id": [], # Add example_id to link back to original examples
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
for example_index, paragraphs in enumerate(examples["paragraphs"]):
|
| 50 |
+
for para in paragraphs:
|
| 51 |
+
context = para["context"]
|
| 52 |
+
for qa in para["qas"]:
|
| 53 |
+
question = qa["question"]
|
| 54 |
+
answers = qa["answers"] # This is a list of answer dictionaries
|
| 55 |
+
tokenized = tokenizer(
|
| 56 |
+
question,
|
| 57 |
+
context,
|
| 58 |
+
truncation="only_second",
|
| 59 |
+
max_length=384,
|
| 60 |
+
stride=128,
|
| 61 |
+
return_overflowing_tokens=True,
|
| 62 |
+
return_offsets_mapping=True,
|
| 63 |
+
padding="max_length"
|
| 64 |
+
)
|
| 65 |
+
sample_mapping = tokenized.pop("overflow_to_sample_mapping")
|
| 66 |
+
offset_mapping = tokenized.pop("offset_mapping")
|
| 67 |
+
for i, offsets in enumerate(offset_mapping):
|
| 68 |
+
input_ids = tokenized["input_ids"][i]
|
| 69 |
+
cls_index = input_ids.index(tokenizer.cls_token_id)
|
| 70 |
+
sequence_ids = tokenized.sequence_ids(i)
|
| 71 |
+
start_position = cls_index
|
| 72 |
+
end_position = cls_index
|
| 73 |
+
if len(answers) > 0:
|
| 74 |
+
first_answer = answers[0] # Get the first answer dictionary
|
| 75 |
+
start_char = first_answer["answer_start"]
|
| 76 |
+
end_char = start_char + len(first_answer["text"])
|
| 77 |
+
token_start_index = 0
|
| 78 |
+
while sequence_ids[token_start_index] != (1 if tokenizer.is_fast else 0):
|
| 79 |
+
token_start_index += 1
|
| 80 |
+
token_end_index = len(input_ids) - 1
|
| 81 |
+
while sequence_ids[token_end_index] != (1 if tokenizer.is_fast else 0):
|
| 82 |
+
token_end_index -= 1
|
| 83 |
+
if offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char:
|
| 84 |
+
# Move the token_start_index and token_end_index to the two ends of the answer
|
| 85 |
+
while token_start_index < len(offsets) and offsets[token_start_index][0] <= start_char:
|
| 86 |
+
token_start_index += 1
|
| 87 |
+
start_position = token_start_index - 1
|
| 88 |
+
|
| 89 |
+
while token_end_index >= 0 and offsets[token_end_index][1] >= end_char:
|
| 90 |
+
token_end_index -= 1
|
| 91 |
+
end_position = token_end_index + 1
|
| 92 |
+
|
| 93 |
+
tokenized_examples["input_ids"].append(input_ids)
|
| 94 |
+
tokenized_examples["attention_mask"].append(tokenized["attention_mask"][i])
|
| 95 |
+
tokenized_examples["offset_mapping"].append(offsets)
|
| 96 |
+
tokenized_examples["overflow_to_sample_mapping"].append(example_index) # Map back to the original example index in the batch
|
| 97 |
+
tokenized_examples["start_positions"].append(start_position)
|
| 98 |
+
tokenized_examples["end_positions"].append(end_position)
|
| 99 |
+
tokenized_examples["example_id"].append(qa.get("id", f"{examples.get('title', ['no_title'])[example_index]}_{len(tokenized_examples['input_ids'])}"))
|
| 100 |
+
tokenized_dataset = dataset.map(
|
| 101 |
+
prepare_features,
|
| 102 |
+
batched=True,
|
| 103 |
+
remove_columns=dataset["train"].column_names # Remove original columns after processing
|
| 104 |
+
)
|
| 105 |
+
print(tokenized_dataset)
|
| 106 |
+
from transformers import TrainingArguments, Trainer
|
| 107 |
+
training_args = TrainingArguments(
|
| 108 |
+
output_dir="./finetuned-roberta-squad2",
|
| 109 |
+
eval_strategy="epoch", # Corrected argument name
|
| 110 |
+
save_strategy="epoch", # Match save strategy to evaluation strategy
|
| 111 |
+
learning_rate=2e-5,
|
| 112 |
+
num_train_epochs=3,
|
| 113 |
+
weight_decay=0.01,
|
| 114 |
+
per_device_train_batch_size=8,
|
| 115 |
+
per_device_eval_batch_size=8,
|
| 116 |
+
save_total_limit=1,
|
| 117 |
+
load_best_model_at_end=True,
|
| 118 |
+
)
|
| 119 |
+
trainer = Trainer(
|
| 120 |
+
model=model,
|
| 121 |
+
args=training_args,
|
| 122 |
+
train_dataset=tokenized_dataset["train"],
|
| 123 |
+
eval_dataset=tokenized_dataset["validation"],
|
| 124 |
+
tokenizer=tokenizer
|
| 125 |
+
)
|
| 126 |
+
trainer.train()
|
| 127 |
+
trainer.save_model("./finetuned-roberta-squad2")
|
| 128 |
+
tokenizer.save_pretrained("./finetuned-roberta-squad2")
|
| 129 |
+
# EVALUATION
|
| 130 |
+
!pip install bert-score -q
|
| 131 |
+
from transformers import pipeline
|
| 132 |
+
qa_pipeline = pipeline("question-answering", model="./finetuned-roberta-squad2", tokenizer=tokenizer)
|
| 133 |
+
examples = dataset["validation"]
|
| 134 |
+
predictions = []
|
| 135 |
+
references = []
|
| 136 |
+
for example in examples:
|
| 137 |
+
for para in example["paragraphs"]:
|
| 138 |
+
context = para["context"]
|
| 139 |
+
for qa in para["qas"]:
|
| 140 |
+
question = qa["question"]
|
| 141 |
+
answers = qa["answers"] # This is a list of answer dictionaries
|
| 142 |
+
result = qa_pipeline({
|
| 143 |
+
"context": context,
|
| 144 |
+
"question": question
|
| 145 |
+
})
|
| 146 |
+
predictions.append(result["answer"])
|
| 147 |
+
if len(answers) > 0:
|
| 148 |
+
references.append(answers[0]["text"])
|
| 149 |
+
else:
|
| 150 |
+
references.append("") # Append empty string for unanswerable questions
|
| 151 |
+
from bert_score import score
|
| 152 |
+
P, R, F1 = score(predictions, references, lang="en", model_type="roberta-base")
|
| 153 |
+
print(f"πΉ BERTScore Precision: {P.mean().item():.4f}")
|
| 154 |
+
print(f"πΉ BERTScore Recall: {R.mean().item():.4f}")
|
| 155 |
+
print(f"πΉ BERTScore F1: {F1.mean().item():.4f}")
|
| 156 |
+
from transformers import AutoModel, AutoTokenizer
|
| 157 |
+
import torch
|
| 158 |
+
import torch.nn.functional as F
|
| 159 |
+
# Use sentence transformer or same QA model encoder
|
| 160 |
+
embed_model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
| 161 |
+
embed_tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
| 162 |
+
def get_embedding(text):
|
| 163 |
+
inputs = embed_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 164 |
+
with torch.no_grad():
|
| 165 |
+
outputs = embed_model(**inputs)
|
| 166 |
+
return outputs.last_hidden_state.mean(dim=1)
|
| 167 |
+
# Compute cosine similarities
|
| 168 |
+
cosine_scores = []
|
| 169 |
+
for pred, ref in zip(predictions, references):
|
| 170 |
+
pred_emb = get_embedding(pred)
|
| 171 |
+
ref_emb = get_embedding(ref)
|
| 172 |
+
cosine_sim = F.cosine_similarity(pred_emb, ref_emb).item()
|
| 173 |
+
cosine_scores.append(cosine_sim)
|
| 174 |
+
avg_cosine = sum(cosine_scores) / len(cosine_scores)
|
| 175 |
+
print(f"πΉ Average Cosine Similarity: {avg_cosine:.4f}")
|
sentence-transformers/all-mpnet-base-v2
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Untitled8.ipynb
|
| 3 |
+
Automatically generated by Colab.
|
| 4 |
+
Original file is located at
|
| 5 |
+
https://colab.research.google.com/drive/1JMKmuuP0equrOr6l6oQVQbpbBnGTGvcc
|
| 6 |
+
"""
|
| 7 |
+
!pip install sentence-transformers
|
| 8 |
+
from google.colab import files
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import random
|
| 11 |
+
uploaded = files.upload()
|
| 12 |
+
file_name = list(uploaded.keys())[0]
|
| 13 |
+
df = pd.read_csv(file_name)
|
| 14 |
+
|
| 15 |
+
# Preview
|
| 16 |
+
print("π Preview of training data:")
|
| 17 |
+
print(df.head())
|
| 18 |
+
print(f"\nβ
Loaded {len(df)} training pairs.")
|
| 19 |
+
from sentence_transformers import InputExample
|
| 20 |
+
train_examples = [
|
| 21 |
+
InputExample(texts=[row["text1"], row["text2"]], label=float(row["score"]))
|
| 22 |
+
for _, row in df.iterrows()
|
| 23 |
+
]
|
| 24 |
+
from sentence_transformers import SentenceTransformer, losses
|
| 25 |
+
from torch.utils.data import DataLoader
|
| 26 |
+
model = SentenceTransformer("sentence-transformers/all-mpnet-base-v2")
|
| 27 |
+
train_dataloader = DataLoader(train_examples, shuffle=True, batch_size=16)
|
| 28 |
+
train_loss = losses.CosineSimilarityLoss(model)
|
| 29 |
+
model.fit(
|
| 30 |
+
train_objectives=[(train_dataloader, train_loss)],
|
| 31 |
+
epochs=1, # Increase to 3β5 for better results
|
| 32 |
+
warmup_steps=10, # Usually 10% of steps per epoch
|
| 33 |
+
output_path="fine-tuned-mpnet-model"
|
| 34 |
+
)
|
| 35 |
+
from sentence_transformers import SentenceTransformer
|
| 36 |
+
model = SentenceTransformer("fine-tuned-mpnet-model")
|
| 37 |
+
sentence = "This is a test sentence."
|
| 38 |
+
embedding = model.encode(sentence)
|
| 39 |
+
print(embedding.shape)
|
| 40 |
+
fine_tuned_model = SentenceTransformer("fine-tuned-mpnet-model")
|
| 41 |
+
|
| 42 |
+
# Example usage
|
| 43 |
+
embedding = fine_tuned_model.encode("This is a test sentence.")
|
| 44 |
+
print("π’ Embedding shape:", embedding.shape)
|
| 45 |
+
import os
|
| 46 |
+
print(os.listdir("fine-tuned-mpnet-model"))
|
| 47 |
+
from sentence_transformers import SentenceTransformer
|
| 48 |
+
from sentence_transformers.util import cos_sim
|
| 49 |
+
# Load base and fine-tuned models
|
| 50 |
+
base_model = SentenceTransformer("sentence-transformers/all-mpnet-base-v2")
|
| 51 |
+
ft_model = SentenceTransformer("fine-tuned-mpnet-model")
|
| 52 |
+
from sentence_transformers import SentenceTransformer
|
| 53 |
+
from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
|
| 54 |
+
from torch.utils.data import DataLoader
|
| 55 |
+
fine_tuned_model = SentenceTransformer("fine-tuned-mpnet-model")
|
| 56 |
+
sentence = "This is a test sentence."
|
| 57 |
+
embedding = fine_tuned_model.encode(sentence)
|
| 58 |
+
print("π’ Embedding shape:", embedding.shape)
|
| 59 |
+
|
| 60 |
+
"""You can now use the `fine_tuned_model` to generate embeddings for any text data. For example, you can use these embeddings for tasks like semantic search, clustering, or classification."""
|
| 61 |
+
|
| 62 |
+
from tqdm import tqdm
|
| 63 |
+
import numpy as np
|
| 64 |
+
from sentence_transformers.util import cos_sim
|
| 65 |
+
from sklearn.metrics import mean_squared_error
|
| 66 |
+
from scipy.stats import spearmanr
|
| 67 |
+
def evaluate_model(model, name):
|
| 68 |
+
embeddings1 = model.encode(sentences1, convert_to_tensor=True)
|
| 69 |
+
embeddings2 = model.encode(sentences2, convert_to_tensor=True)
|
| 70 |
+
similarities = cos_sim(embeddings1, embeddings2).diagonal().cpu().numpy()
|
| 71 |
+
mse = mean_squared_error(true_scores, similarities)
|
| 72 |
+
spearman_corr, _ = spearmanr(true_scores, similarities)
|
| 73 |
+
print(f"\nπ Evaluation: {name}")
|
| 74 |
+
print(f"π CosineSim vs Human Scores: ")
|
| 75 |
+
print(f" β’ MSE: {mse:.4f}")
|
| 76 |
+
print(f" β’ Spearman R: {spearman_corr:.4f}")
|
| 77 |
+
return similarities
|
| 78 |
+
# Extract sentences and scores from the DataFrame
|
| 79 |
+
sentences1 = df['text1'].tolist()
|
| 80 |
+
sentences2 = df['text2'].tolist()
|
| 81 |
+
true_scores = df['score'].tolist()
|
| 82 |
+
# Evaluate both models
|
| 83 |
+
_ = evaluate_model(base_model, "Base MPNET")
|
| 84 |
+
_ = evaluate_model(ft_model, "Fine-Tuned MPNET")
|