Spaces:
No application file
No application file
Upload 2 files
Browse filesFiles changed (2)
- model.pyAdded+71
- preprocess.pyAdded+97
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071import torchimport torch.nn as nnfrom transformers import AutoModelfrom peft import LoraConfig, get_peft_modelfrom typing import Any, List, Iterable
class Model(nn.Module): """ Hybrid RoBERTa + engineered features classifier with LoRA fine-tuning. LoRA config: r=8, alpha=16, targeting query and value projection matrices. """
def __init__(self, n_extra=9, n_classes=2) -> None: super().__init__() # 1. Load the raw RoBERTa backbone self.backbone = AutoModel.from_pretrained("roberta-base") # 2. Apply LoRA lora_cfg = LoraConfig( r=8, lora_alpha=16, target_modules=['query', 'value'], # RoBERTa naming lora_dropout=0.1, bias='none', ) self.backbone = get_peft_model(self.backbone, lora_cfg) hidden_size = 768 # Standard for roberta-base
# 3. Classification Head self.classifier = nn.Sequential( nn.Linear(hidden_size + n_extra, 256), nn.ReLU(), nn.Dropout(0.1), nn.Linear(256, n_classes) )
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.to(self.device)
def forward(self, input_ids, attention_mask, extra): # Accessing the PEFT-wrapped backbone outputs = self.backbone(input_ids=input_ids, attention_mask=attention_mask) # Pulling the [CLS] token (first token) cls_token = outputs.last_hidden_state[:, 0, :] # Concatenate RoBERTa features with our 9 engineered features combined = torch.cat((cls_token, extra), dim=1) return self.classifier(combined)
def predict(self, batch: Iterable[Any]) -> List[Any]: self.eval() predictions = []
with torch.no_grad(): for item in batch: # Move tensors to the correct device ids = item['input_ids'].unsqueeze(0).to(self.device) mask = item['attention_mask'].unsqueeze(0).to(self.device) extra = item['extra'].unsqueeze(0).to(self.device)
logits = self.forward(input_ids=ids, attention_mask=mask, extra=extra) # Get the index of the highest logit (0 or 1) pred = torch.argmax(logits, dim=1).item() predictions.append(pred)
return predictions12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import reimport torchimport pandas as pdimport spacyimport textstatimport numpy as npfrom sklearn.preprocessing import StandardScalerfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzerfrom textblob import TextBlobfrom transformers import RobertaTokenizerFastfrom typing import Any, List, Tuplefrom collections import Counter
# Initialize assetsanalyzer = SentimentIntensityAnalyzer()nlp = spacy.load("en_core_web_sm")tokenizer = RobertaTokenizerFast.from_pretrained("roberta-base")
def prepare_data(path: str) -> Tuple[List[Any], List[int]]: df = pd.read_csv(path)
url_col = 'url' if 'url' in df.columns else 'URL' col = 'headline' if 'headline' in df.columns else 'Headline'
# Fox News = 1, NBC = 0 (matches notebook label assignment) y = df[url_col].apply(lambda x: 1 if 'foxnews' in str(x).lower() else 0).tolist()
raw_headlines = df[col].fillna("").astype(str).tolist()
extra_features_list = [] for text in raw_headlines: # Step 1: partial clean (matches notebook process_data) cleaned = re.sub(r'[^a-zA-Z0-9\s!?.]', '', str(text))
# Sentiment on partially-cleaned (not yet lowered) text vader = analyzer.polarity_scores(cleaned)['compound'] blob = TextBlob(cleaned) pol = blob.sentiment.polarity sub = blob.sentiment.subjectivity
# Step 2: lowercase for readability + POS (matches notebook) cleaned_lower = cleaned.lower()
flesch_grade = textstat.flesch_kincaid_grade(cleaned_lower) dale_chall = textstat.dale_chall_readability_score(cleaned_lower)
doc = nlp(cleaned_lower) pos_counts = Counter([token.pos_ for token in doc]) total = max(len(doc), 1)
adj_ratio = pos_counts['ADJ'] / total noun_ratio = pos_counts['NOUN'] / total verb_ratio = pos_counts['VERB'] / total propn_ratio = pos_counts['PROPN'] / total
extra_features_list.append([ vader, pol, sub, flesch_grade, dale_chall, adj_ratio, noun_ratio, verb_ratio, propn_ratio ])
extra_features_array = np.array(extra_features_list)
# Apply StandardScaler transformation using hardcoded train statistics # MEANS and SCALES from your training data MEANS = np.array([-0.1334619224845996, 0.03029492746171712, 0.2651717153521648, 9.980616597099122, 13.645249615780298, 0.0889533621243282, 0.3505696658815537, 0.1632638895974067, 0.1800343226802681]) SCALES = np.array([0.44220484926020476, 0.24816946974516618, 0.30067967610801016, 3.4913473626034275, 2.6611917566411334, 0.08265346734243517, 0.14167055766862657, 0.08353813921243011, 0.15736948474872678]) # Standardize features scaler = StandardScaler() scaler.mean_ = MEANS scaler.scale_ = SCALES extra_features_scaled = scaler.transform(extra_features_array)
# Tokenize raw headlines encoded = tokenizer( raw_headlines, padding='max_length', truncation=True, max_length=64, return_tensors='pt' )
X = [] for i in range(len(df)): X.append({ 'input_ids': encoded['input_ids'][i], 'attention_mask': encoded['attention_mask'][i], 'extra': torch.tensor(extra_features_scaled[i], dtype=torch.float) })
return X, ymodel.pyAdded+71
preprocess.pyAdded+97