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/lr_model'
filename='lr_clf_test2.joblib'
model_file_path=hf_hub_download(repo_id=repo_id, filename=filename)
model=joblib.load(model_file_path)
print(model)
repo_id2='awngsz/tfidf_model' ############# <--- check tfidf model name
filename2='embed_tfidf.joblib'
model_file_path2=hf_hub_download(repo_id=repo_id2, filename=filename2)
tfidf_model=joblib.load(model_file_path2)
print(tfidf_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 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 all references to US as u.s.
df[column_name] = df[column_name].str.replace(r'US', 'u.s.', regex=True)
df[column_name] = df[column_name].str.replace(r'UN', 'u.n.', regex=True)
# Remove extra spaces including leading/trailing whitespaces
df[column_name] = df[column_name].str.strip().str.replace(r'\s+', ' ', regex=True)
# get rid of these fox news patterns we see
df[column_name] = df[column_name].str.replace(r'fox news poll:', '', regex=True)
df[column_name] = df[column_name].str.replace(r'| fox news', '', regex=True)
df[column_name] = df[column_name].str.replace(r'Fox News', '', regex=True)
df[column_name] = df[column_name].str.replace(r'fox news', '', regex=True)
df[column_name] = df[column_name].str.replace(r'news poll:', '', regex=True)
df[column_name] = df[column_name].str.replace(r'opinion:', '', regex=True)
df[column_name] = df[column_name].str.replace(r"reporter's notebook", '', 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 </pre>
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
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.