Create example_classify_script_for_csv.py
Browse files
example_classify_script_for_csv.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CUDA_VISIBLE_DEVICES=0,1,2,3 python classify_generics.py
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
from transformers import RobertaForSequenceClassification, RobertaTokenizer
|
| 5 |
+
|
| 6 |
+
import random
|
| 7 |
+
random.seed(101)
|
| 8 |
+
|
| 9 |
+
## PARAMETERS ##
|
| 10 |
+
|
| 11 |
+
input_csv = "data/input.csv"
|
| 12 |
+
text_column = "text_column_name"
|
| 13 |
+
output_csv = ""
|
| 14 |
+
output_csv = f"{input_csv}_scored_for_generics.csv" if not output_csv else output_csv
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
model_path = "ilyocoris/generics-classifier-mgen"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
## LOAD DATA & MODEL ##
|
| 21 |
+
|
| 22 |
+
data = pd.read_csv(input_csv)
|
| 23 |
+
data = data.to_dict(orient="records")
|
| 24 |
+
|
| 25 |
+
def load_roberta_classifier(model_name, checkpoint=None, base_model="roberta-large"):
|
| 26 |
+
# model_path = f"data/training_runs/{model_name}/models/checkpoint-{checkpoint}" if checkpoint else f"data/models/{model_name}"
|
| 27 |
+
model_path = f"{model_name}/checkpoint-{checkpoint}" if checkpoint else model_name
|
| 28 |
+
model = RobertaForSequenceClassification.from_pretrained(
|
| 29 |
+
model_path,
|
| 30 |
+
device_map="auto",
|
| 31 |
+
num_labels=1
|
| 32 |
+
)
|
| 33 |
+
tokenizer = RobertaTokenizer.from_pretrained(base_model)
|
| 34 |
+
return model, tokenizer
|
| 35 |
+
|
| 36 |
+
def classify_batch(batch_sentences, model, tokenizer):
|
| 37 |
+
inputs = tokenizer(batch_sentences, return_tensors="pt", padding=True, truncation=True)
|
| 38 |
+
inputs = {k: v.cuda() for k, v in inputs.items()}
|
| 39 |
+
outputs = model(**inputs)
|
| 40 |
+
return outputs.logits.squeeze().cpu().detach().numpy()
|
| 41 |
+
|
| 42 |
+
model, tokenizer = load_roberta_classifier(model_path)
|
| 43 |
+
|
| 44 |
+
## RUN CLASSIFIER ##
|
| 45 |
+
|
| 46 |
+
scores = []
|
| 47 |
+
batch_size = 16
|
| 48 |
+
for i in tqdm(range(0, len(data), batch_size)):
|
| 49 |
+
batch = data[i:i+batch_size]
|
| 50 |
+
sentences = [d[text_column] for d in batch]
|
| 51 |
+
scores.extend(classify_batch(sentences, model, tokenizer).tolist())
|
| 52 |
+
|
| 53 |
+
df = pd.DataFrame(data)
|
| 54 |
+
df["score"] = scores
|
| 55 |
+
df.to_csv(f"{output_csv}", index=False)
|