Model Card for Model ID
This is the baseline model for the news source classification project.
Please run the following evaluation pipeline code:
START
Imports
from huggingface_hub import hf_hub_download import joblib !huggingface-cli login import pandas as pd import torch from transformers import AutoTokenizer, AutoModel import torchvision from torchvision import transforms, utils import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms from PIL import Image from skimage import io, transform from torchvision.io import read_image from torch.utils.data import Dataset, DataLoader from sklearn.metrics import accuracy_score import numpy as np import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import nltk from nltk.corpus import stopwords nltk.download('stopwords') nltk.download('wordnet') import re from transformers import DistilBertTokenizer, DistilBertModel
Load model from Huggingface (Please load test data into test_df below)
repo_id='awngsz/baseline_model' filename='CIS5190_Proj2_AWNGSZ.joblib' model_file_path=hf_hub_download(repo_id=repo_id, filename=filename)
model=joblib.load(model_file_path) print(model) #Load test dataset (assuming the name is the same as the one in the Ed post)
test_df = pd.read_csv(file_path) #Copying the naming convention from the sample dataset in the edpost
X_test = test_df['title'] y_test = test_df['labels']
Clean the data
def clean_headlines(df, column_name): """ Cleans a specified column in a DataFrame by: - Removing HTML tags - Removing ', '', regex=True) # Remove extra spaces including leading/trailing whitespaces df[column_name] = df[column_name].str.strip().str.replace(r'\s+', ' ', regex=True) # Remove special characters df[column_name] = df[column_name].str.strip().str.replace(r'[&*|~`^=_+{}[\]<>\\]', ' ', regex=True) # Remove repeating special characters df[column_name] = df[column_name].str.strip().str.replace(r'([?!])\1+', r'\1', regex=True) # Remove tabs df[column_name] = df[column_name].str.replace(r'\t', ' ', regex=True) # Remove newline characters df[column_name] = df[column_name].str.replace(r'\n', ' ', regex=True) # Normalize double quotes to single quotes # df[column_name] = df[column_name].str.replace(r'"', "'", regex=True) # Punctuation # df[column_name] = df[column_name].str.replace(r'[.,()]', '', regex=True) return df
def normalize_headlines(df, column_name): """ Normalizes a given headline by: - converting it to lowercase - removing stopwords - applying stemming or lemmatization to reduce words to their base forms Args: df (pd.DataFrame): The DataFrame containing the column to clean column_name (str): The name of the column to clean Returns: pd.DataFrame: A DataFrame with the cleaned column """ # Convert headlines to lowercase df[column_name] = df[column_name].str.lower() # Remove stopwords from headline stop_words = set(stopwords.words('english')) df[column_name] = df[column_name].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop_words)])) # Lemmatize words to base form lemmatizer = nltk.stem.WordNetLemmatizer() df[column_name] = df[column_name].apply(lambda x: ' '.join([lemmatizer.lemmatize(word) for word in x.split()])) return df
def handle_missing_data(df, column_name): """ Handles missing or incomplete data in a given column of a DataFrame, including: - Replacing NULL values with "Unknown Headline" - Augmenting the data by creating headlines with synonyms of words in other headlines Args: df (pd.DataFrame): The DataFrame containing the column to clean column_name (str): The name of the column to clean Returns: pd.DataFrame: A DataFrame with the cleaned column """ # Remove NULL headlines df = df.dropna(subset=[column_name]) # Set a minimum word count threshold min_word_count = 3 # Filter out titles with fewer words df = df[df[column_name].str.split().apply(len) >= min_word_count].reset_index(drop=True) return df
def consistency_checks(df, column_name): """ Ensures all headlines follow a consistent format by: - Removing duplicate headlines Args: df (pd.DataFrame): The DataFrame containing the column to clean column_name (str): The name of the column to clean Returns: pd.DataFrame: A DataFrame with the cleaned column """ # Remove duplicate headlines df = df.drop_duplicates(subset=[column_name]) # Filter headlines with too few or too many words #df = df[df['title'].str.split().apply(len).between(3, 20)] return df
X_test = clean_headlines(X_test, 'title') X_test = normalize_headlines(X_test, 'title') X_test = X_test.dropna(subset = ['title']) X_test = handle_missing_data(X_test, 'title') X_test = consistency_checks(X_test, 'title')
Load the embedding model from Huggingface. Transformer: DistilBERT
def get_embeddings(text_all, tokenizer, model, device, max_len=128): ''' Generate embeddings using a transformer model on GPU if available. Args: - text_all: List of input texts - tokenizer: Tokenizer for the model - model: Transformer model - device: torch.device to run the computations - max_len: Maximum token length for the input Returns: - embeddings: List of embeddings for each input text ''' embeddings = [] count = 0 print('Start embeddings:') for text in text_all: count += 1 if count % (len(text_all) // 10) == 0: print(f'{count / len(text_all) * 100:.1f}% done ...') # Tokenize the input text model_input_token = tokenizer( text, add_special_tokens=True, max_length=max_len, padding='max_length', truncation=True, return_tensors='pt' ).to(device) # Move input tensors to GPU # Generate embeddings without gradient computation with torch.no_grad(): model_output = model(**model_input_token) cls_embedding = model_output.last_hidden_state[:, 0, :] # Use CLS token embedding cls_embedding = cls_embedding.squeeze().cpu().numpy() # Move back to CPU for numpy embeddings.append(cls_embedding) return embeddings
Check for GPU availability
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print(f'Using device: {device}') # Load the tokenizer and model for 'all-mpnet-base-v2' print("Loading model and tokenizer...") # Load model and tokenizer tokenizer_news = AutoTokenizer.from_pretrained('distilbert-base-uncased') model_news = AutoModel.from_pretrained('distilbert-base-uncased').to(device) # Set the model to evaluation mode model_news.eval() ############################################# DBERT UNCASED Embedding ############################################# ############################################# Embedding ############################################# print("Computing DBERT embeddings for training data...") X_test_embeddings_DBERT = get_embeddings(X_test, tokenizer_news, model_news, device, max_len=128) print("DBERT embeddings for training data computed!") prediction = model.predict(X_test_embeddings_DBERT)
Accuracy
label_map = {'NBC': 1, 'FoxNews': 0} def compute_category_accuracy(y_true, y_pred, label): n_correct = np.sum((y_true == label) & (y_pred == label)) n_total = np.sum(y_true == label) cat_accuracy = n_correct / n_total return cat_accuracy #Print accuracy print(f'Test accuracy: {accuracy_score(y_test, prediction) * 100:.2f}%') print(f'Test accuracy for NBC: {compute_category_accuracy(y_test, prediction, label_map["NBC"]) * 100:.2f}%') print(f'Test accuracy for FoxNews: {compute_category_accuracy(y_test, prediction, label_map["FoxNews"]) * 100:.2f}%')
END
Model Details
Model Description
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
- Developed by: [More Information Needed]
- Funded by [optional]: [More Information Needed]
- Shared by [optional]: [More Information Needed]
- Model type: [More Information Needed]
- Language(s) (NLP): [More Information Needed]
- License: [More Information Needed]
- Finetuned from model [optional]: [More Information Needed]
Model Sources [optional]
- Repository: [More Information Needed]
- Paper [optional]: [More Information Needed]
- Demo [optional]: [More Information Needed]
Uses
Direct Use
[More Information Needed]
Downstream Use [optional]
[More Information Needed]
Out-of-Scope Use
[More Information Needed]
Bias, Risks, and Limitations
[More Information Needed]
Recommendations
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
How to Get Started with the Model
Use the code below to get started with the model.
[More Information Needed]
Training Details
Training Data
[More Information Needed]
Training Procedure
Preprocessing [optional]
[More Information Needed]
Training Hyperparameters
- Training regime: [More Information Needed]
Speeds, Sizes, Times [optional]
[More Information Needed]
Evaluation
Testing Data, Factors & Metrics
Testing Data
[More Information Needed]
Factors
[More Information Needed]
Metrics
[More Information Needed]
Results
[More Information Needed]
Summary
Model Examination [optional]
[More Information Needed]
Environmental Impact
Carbon emissions can be estimated using the Machine Learning Impact calculator presented in Lacoste et al. (2019).
- Hardware Type: [More Information Needed]
- Hours used: [More Information Needed]
- Cloud Provider: [More Information Needed]
- Compute Region: [More Information Needed]
- Carbon Emitted: [More Information Needed]
Technical Specifications [optional]
Model Architecture and Objective
[More Information Needed]
Compute Infrastructure
[More Information Needed]
Hardware
[More Information Needed]
Software
[More Information Needed]
Citation [optional]
BibTeX:
[More Information Needed]
APA:
[More Information Needed]
Glossary [optional]
[More Information Needed]
More Information [optional]
[More Information Needed]
Model Card Authors [optional]
[More Information Needed]
Model Card Contact
[More Information Needed]
- Downloads last month
- 6