CoolFace
Modelpublic

awngsz/lr_model

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
Model Card

Model Card for Model ID

<!-- Provide a quick summary of what the model is/does. --> This is the baseline model for the news source classification project.

Please run the following evaluation pipeline code:

START #

Imports

<pre>from huggingfacehub import hfhubdownload 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 readimage 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</pre>

Load model from Huggingface (Please load test data into test_df below)

<pre>repoid='awngsz/lrmodel' filename='lrclftest2.joblib'

modelfilepath=hfhubdownload(repoid=repoid, filename=filename) <br> model=joblib.load(modelfilepath) print(model)

repoid2='awngsz/tfidfmodel' ############# <--- check tfidf model name filename2='embed_tfidf.joblib'

modelfilepath2=hfhubdownload(repoid=repoid2, filename=filename2) <br> tfidfmodel=joblib.load(modelfilepath2) print(tfidfmodel)

#Load test dataset (assuming the name is the same as the one in the Ed post) <br> testdf = pd.readcsv(file_path)

#Copying the naming convention from the sample dataset in the edpost <br> Xtest = testdf['title'] ytest = testdf['labels'] </pre>

Clean the data

<pre> def cleanheadlines(df, columnname): """ Cleans a specified column in a DataFrame by:

  • —Removing HTML tags
  • —Removing <script> elements
  • —Removing extra spaces, trailing/leading whitespaces
  • —Removing special characters
  • —Removing repeating special characters
  • —Removing tabs
  • —Removing newline characters
  • —Removing specific punctuation: periods, commas, and parentheses
  • —Normalizing double quotes ("") to single quotes ('')

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 HTML tags df[columnname] = df[columnname].str.replace(r'<[^<]+?>', '', regex=True)

# Remove scripts df[columnname] = df[columnname].str.replace(r'<script.*?</script>', '', regex=True)

# Remove special characters df[columnname] = df[columnname].str.strip().str.replace(r'[&*|~`^=_+{}[\]<>\\]', ' ', regex=True)

# Remove repeating special characters df[columnname] = df[columnname].str.strip().str.replace(r'([?!])\1+', r'\1', regex=True)

# Remove tabs df[columnname] = df[columnname].str.replace(r'\t', ' ', regex=True)

# Remove newline characters df[columnname] = df[columnname].str.replace(r'\n', ' ', regex=True)

# Normalize all references to US as u.s. df[columnname] = df[columnname].str.replace(r'US', 'u.s.', regex=True) df[columnname] = df[columnname].str.replace(r'UN', 'u.n.', regex=True)

# Remove extra spaces including leading/trailing whitespaces df[columnname] = df[columnname].str.strip().str.replace(r'\s+', ' ', regex=True)

# get rid of these fox news patterns we see df[columnname] = df[columnname].str.replace(r'fox news poll:', '', regex=True)

df[columnname] = df[columnname].str.replace(r'| fox news', '', regex=True)

df[columnname] = df[columnname].str.replace(r'Fox News', '', regex=True) df[columnname] = df[columnname].str.replace(r'fox news', '', regex=True)

df[columnname] = df[columnname].str.replace(r'news poll:', '', regex=True)

df[columnname] = df[columnname].str.replace(r'opinion:', '', regex=True)

df[columnname] = df[columnname].str.replace(r"reporter's notebook", '', regex=True)

# Normalize double quotes to single quotes # df[columnname] = df[columnname].str.replace(r'"', "'", regex=True)

# Punctuation # df[columnname] = df[columnname].str.replace(r'[.,()]', '', regex=True)

return df </pre>

<pre> def normalizeheadlines(df, columnname): """ 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[columnname] = df[columnname].str.lower()

# Remove stopwords from headline stopwords = set(stopwords.words('english')) df[columnname] = df[columnname].apply(lambda x: ' '.join([word for word in x.split() if word not in (stopwords)]))

# Lemmatize words to base form lemmatizer = nltk.stem.WordNetLemmatizer() df[columnname] = df[columnname].apply(lambda x: ' '.join([lemmatizer.lemmatize(word) for word in x.split()]))

return df </pre>

<pre> def handlemissingdata(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 minwordcount = 3

# Filter out titles with fewer words df = df[df[columnname].str.split().apply(len) >= minwordcount].resetindex(drop=True)

return df </pre>

<pre> def consistencychecks(df, columnname): """ 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.dropduplicates(subset=[columnname])

# Filter headlines with too few or too many words #df = df[df['title'].str.split().apply(len).between(3, 20)]

return df </pre>

<pre> Xtest = cleanheadlines(Xtest, 'title') Xtest = normalizeheadlines(Xtest, 'title') Xtest = Xtest.dropna(subset = ['title']) Xtest = handlemissingdata(Xtest, 'title') Xtest = consistencychecks(X_test, 'title') </pre>

############################################# TF-IDF Embedding ############################################# ############################################# Embedding ############################################# from sklearn.feature_extraction.text import TfidfVectorizer print("Computing embeddings ...")

ytest = Xtest['labels'] Xtest = Xtest['title']

Xtesttfidf = tfidfmodel.transform(Xtest)

#XtestembeddingsDBERT = getembeddings(Xtest, tokenizernews, modelnews, device, maxlen=128) print("Embeddings computed!")

prediction = model.predict(Xtesttfidf) </pre>

Accuracy

<pre>label_map = {'NBC': 0, 'FoxNews': 1}

def computecategoryaccuracy(ytrue, ypred, label): ytrue = np.array(ytrue) ncorrect = np.sum((ytrue == label) & (ypred == label)) ntotal = np.sum(ytrue == label) cataccuracy = ncorrect / ntotal return cat_accuracy

#Print accuracy print(f'Test accuracy: {accuracyscore(ytest, 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: {computecategoryaccuracy(ytest, prediction, labelmap["FoxNews"]) * 100:.2f}%') </pre>

<!-- from huggingfacehub import hfhub_download import joblib

#Load model from Huggingface repoid='awngsz/baselinemodel' filename='CIS5190Proj2AWNGSZ.joblib'

filepath=hfhubdownload(repoid=repoid, filename=filename) model=joblib.load(filepath)

print(model)

#Load test dataset (assuming the name is the same as the one in the Ed post) testdf = pd.readcsv(file_path)

#Copying the naming convention from the sample dataset in the edpost Xtest = testdf['title'] ytest = testdf['labels']

#Load the embedding model from Huggingface ############################################# Transformer: DistilBERT ############################################# from transformers import DistilBertTokenizer, DistilBertModel

pytorch related packages

import torch 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

def getembeddings(textall, tokenizer, model, maxlen = 128): ''' return: embeddings list ''' embeddings = [] count = 0 print('Start embeddings:') for text in textall: count += 1 if count % (len(textall) // 10) == 0: print(f'{count / len(textall) * 100:.1f}% done ...')

modelinputtoken = tokenizer( text, addspecialtokens = True, maxlength = maxlen, padding = 'maxlength', truncation = True, returntensors = 'pt' )

with torch.nograd(): modeloutput = model(**modelinputtoken) clsembedding = modeloutput.lasthiddenstate[:, 0, :] clsembedding = clsembedding.squeeze().numpy() embeddings.append(cls_embedding)

return embeddings

#Load the tokenizer and model from Hugging Face tokenizerDBERT = DistilBertTokenizer.frompretrained('distilbert-base-uncased') transformermodelDBERT = DistilBertModel.from_pretrained('distilbert-base-uncased')

#Set the model to evaluation mode transformermodelDBERT.eval()

#Get the embeddings for the test data

maxlen = max(len(text) for text in Xtest)

#this may take awhile to run XtestembeddingsDBERT = getembeddings(Xtest, tokenizerDBERT, transformermodelDBERT, maxlen = maxlen)

prediction = model.predict(Xtestembeddings_DBERT)

#Accuracy from sklearn.metrics import accuracy_score

label_map = {'NBC': 1, 'FoxNews': 0}

def computecategoryaccuracy(ytrue, ypred, label): ncorrect = np.sum((ytrue == label) & (ypred == label)) ntotal = np.sum(ytrue == label) cataccuracy = ncorrect / ntotal return cat_accuracy

#Print accuracy print(f'Test accuracy: {accuracyscore(ytest, 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: {computecategoryaccuracy(ytest, prediction, labelmap["FoxNews"]) * 100:.2f}%') -->

END ######

Model Details

Model Description

<!-- Provide a longer summary of what this model is. -->

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]

<!-- Provide the basic links for the model. -->

  • —Repository: [More Information Needed]
  • —Paper [optional]: [More Information Needed]
  • —Demo [optional]: [More Information Needed]

Uses

<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->

Direct Use

<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->

[More Information Needed]

Downstream Use [optional]

<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->

[More Information Needed]

Out-of-Scope Use

<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->

[More Information Needed]

Bias, Risks, and Limitations

<!-- This section is meant to convey both technical and sociotechnical limitations. -->

[More Information Needed]

Recommendations

<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->

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

<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->

[More Information Needed]

Training Procedure

<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->

Preprocessing [optional]

[More Information Needed]

Training Hyperparameters
  • —Training regime: [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
Speeds, Sizes, Times [optional]

<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->

[More Information Needed]

Evaluation

<!-- This section describes the evaluation protocols and provides the results. -->

Testing Data, Factors & Metrics

Testing Data

<!-- This should link to a Dataset Card if possible. -->

[More Information Needed]

Factors

<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->

[More Information Needed]

Metrics

<!-- These are the evaluation metrics being used, ideally with a description of why. -->

[More Information Needed]

Results

[More Information Needed]

Summary

Model Examination [optional]

<!-- Relevant interpretability work for the model goes here -->

[More Information Needed]

Environmental Impact

<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->

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]

<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->

BibTeX:

[More Information Needed]

APA:

[More Information Needed]

Glossary [optional]

<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->

[More Information Needed]

More Information [optional]

[More Information Needed]

Model Card Authors [optional]

[More Information Needed]

Model Card Contact

[More Information Needed]