Update README.md
Browse files
README.md
CHANGED
@@ -1,199 +1,337 @@
|
|
1 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
library_name: transformers
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
---
|
5 |
|
6 |
-
#
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
-
|
23 |
-
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
[
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
[
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
[
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
[
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
+
title: News Source Classifier
|
3 |
+
emoji: 📰
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: red
|
6 |
+
sdk: streamlit
|
7 |
+
app_file: eval_pipeline.py
|
8 |
library_name: transformers
|
9 |
+
pinned: false
|
10 |
+
language: en
|
11 |
+
license: mit
|
12 |
+
tags:
|
13 |
+
- text-classification
|
14 |
+
- news-classification
|
15 |
+
- BERT
|
16 |
+
- pytorch
|
17 |
+
- transformers
|
18 |
+
pipeline_tag: text-classification
|
19 |
+
widget:
|
20 |
+
- example_title: "Politics News Headline"
|
21 |
+
text: "Trump's campaign rival decides between voting for him or Biden"
|
22 |
+
- example_title: "International News Headline"
|
23 |
+
text: "World Food Programme Director Cindy McCain: Northern Gaza is in a 'full-blown famine'"
|
24 |
+
- example_title: "Domestic News Headline"
|
25 |
+
text: "Ohio sheriff suggests residents keep a list of homes with Harris yard signs"
|
26 |
+
model-index:
|
27 |
+
- name: News Source Classifier
|
28 |
+
results:
|
29 |
+
- task:
|
30 |
+
type: text-classification
|
31 |
+
name: Text Classification
|
32 |
+
dataset:
|
33 |
+
name: Custom FOX-NBC Dataset
|
34 |
+
type: Custom
|
35 |
+
metrics:
|
36 |
+
- name: F1 Score
|
37 |
+
type: f1
|
38 |
+
value: 0.85
|
39 |
---
|
40 |
|
41 |
+
# News Source Classifier - BERT Model
|
42 |
+
|
43 |
+
## Model Overview
|
44 |
+
This repository contains a fine-tuned BERT model that classifies news headlines between Fox News and NBC News, along with an evaluation pipeline for assessing model performance using Streamlit.
|
45 |
+
|
46 |
+
### Model Details
|
47 |
+
- **Base Model**: BERT (bert-base-uncased)
|
48 |
+
- **Task**: Binary classification (Fox News vs NBC News)
|
49 |
+
- **Model ID**: CIS519PG/News_Classifier_Demo
|
50 |
+
- **Training Data**: News headlines from Fox News and NBC News
|
51 |
+
- **Input**: News article headlines (text)
|
52 |
+
- **Output**: Binary classification with probability scores
|
53 |
+
|
54 |
+
## Evaluation Pipeline Setup
|
55 |
+
|
56 |
+
### Prerequisites
|
57 |
+
- Python 3.8+
|
58 |
+
- pip package manager
|
59 |
+
|
60 |
+
### Required Dependencies
|
61 |
+
Install the required packages using pip:
|
62 |
+
```bash
|
63 |
+
pip install streamlit pandas torch transformers scikit-learn numpy plotly tqdm
|
64 |
+
```
|
65 |
+
|
66 |
+
### Running the Evaluation Pipeline
|
67 |
+
|
68 |
+
1. Save the following provided evaluation code as `eval_pipeline.py`, also downloadable in files.
|
69 |
+
|
70 |
+
```bash
|
71 |
+
import streamlit as st
|
72 |
+
import pandas as pd
|
73 |
+
import torch
|
74 |
+
from transformers import BertTokenizer, AutoModelForSequenceClassification
|
75 |
+
from sklearn.metrics import roc_auc_score, roc_curve, confusion_matrix, classification_report, f1_score, precision_recall_fscore_support
|
76 |
+
import numpy as np
|
77 |
+
import plotly.graph_objects as go
|
78 |
+
import plotly.express as px
|
79 |
+
from tqdm import tqdm
|
80 |
+
|
81 |
+
def load_model_and_tokenizer():
|
82 |
+
try:
|
83 |
+
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
|
84 |
+
model = AutoModelForSequenceClassification.from_pretrained("CIS519PG/News_Classifier_Demo")
|
85 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
86 |
+
model = model.to(device)
|
87 |
+
model.eval()
|
88 |
+
return model, tokenizer, device
|
89 |
+
except Exception as e:
|
90 |
+
st.error(f"Error loading model or tokenizer: {str(e)}")
|
91 |
+
return None, None, None
|
92 |
+
|
93 |
+
def preprocess_data(df):
|
94 |
+
try:
|
95 |
+
processed_data = []
|
96 |
+
for _, row in df.iterrows():
|
97 |
+
outlet = row["News Outlet"].strip().upper()
|
98 |
+
if outlet == "FOX NEWS":
|
99 |
+
outlet = "FOXNEWS"
|
100 |
+
elif outlet == "NBC NEWS":
|
101 |
+
outlet = "NBC"
|
102 |
+
|
103 |
+
processed_data.append({
|
104 |
+
"title": row["title"],
|
105 |
+
"outlet": outlet
|
106 |
+
})
|
107 |
+
return processed_data
|
108 |
+
except Exception as e:
|
109 |
+
st.error(f"Error preprocessing data: {str(e)}")
|
110 |
+
return None
|
111 |
+
|
112 |
+
def evaluate_model(model, tokenizer, device, test_dataset):
|
113 |
+
label2id = {"FOXNEWS": 0, "NBC": 1}
|
114 |
+
all_logits = []
|
115 |
+
references = []
|
116 |
+
|
117 |
+
batch_size = 16
|
118 |
+
progress_bar = st.progress(0)
|
119 |
+
|
120 |
+
for i in range(0, len(test_dataset), batch_size):
|
121 |
+
progress = min(i / len(test_dataset), 1.0)
|
122 |
+
progress_bar.progress(progress)
|
123 |
+
|
124 |
+
batch = test_dataset[i:i + batch_size]
|
125 |
+
texts = [item['title'] for item in batch]
|
126 |
+
|
127 |
+
encoded = tokenizer(
|
128 |
+
texts,
|
129 |
+
padding=True,
|
130 |
+
truncation=True,
|
131 |
+
max_length=128,
|
132 |
+
return_tensors="pt"
|
133 |
+
)
|
134 |
+
|
135 |
+
inputs = {k: v.to(device) for k, v in encoded.items()}
|
136 |
+
with torch.no_grad():
|
137 |
+
outputs = model(**inputs)
|
138 |
+
logits = outputs.logits.cpu().numpy()
|
139 |
+
|
140 |
+
true_labels = [label2id[item['outlet']] for item in batch]
|
141 |
+
all_logits.extend(logits)
|
142 |
+
references.extend(true_labels)
|
143 |
+
progress_bar.progress(1.0)
|
144 |
+
probabilities = torch.softmax(torch.tensor(all_logits), dim=1).numpy()
|
145 |
+
return references, probabilities
|
146 |
+
|
147 |
+
def plot_roc_curve(references, probabilities):
|
148 |
+
fpr, tpr, _ = roc_curve(references, probabilities[:, 1])
|
149 |
+
auc_score = roc_auc_score(references, probabilities[:, 1])
|
150 |
+
fig = go.Figure()
|
151 |
+
fig.add_trace(go.Scatter(x=fpr, y=tpr, name=f'ROC Curve (AUC = {auc_score:.4f})'))
|
152 |
+
fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], name='Random Guess', line=dict(dash='dash')))
|
153 |
+
fig.update_layout(
|
154 |
+
title='ROC Curve',
|
155 |
+
xaxis_title='False Positive Rate',
|
156 |
+
yaxis_title='True Positive Rate',
|
157 |
+
showlegend=True
|
158 |
+
)
|
159 |
+
return fig, auc_score
|
160 |
+
|
161 |
+
def plot_metrics_by_threshold(references, probabilities):
|
162 |
+
thresholds = np.arange(0.0, 1.0, 0.01)
|
163 |
+
metrics = {
|
164 |
+
'threshold': thresholds,
|
165 |
+
'f1': [],
|
166 |
+
'precision': [],
|
167 |
+
'recall': []
|
168 |
+
}
|
169 |
+
best_f1 = 0
|
170 |
+
best_threshold = 0
|
171 |
+
best_metrics = {}
|
172 |
+
for threshold in thresholds:
|
173 |
+
preds = (probabilities[:, 1] > threshold).astype(int)
|
174 |
+
f1 = f1_score(references, preds)
|
175 |
+
precision, recall, _, _ = precision_recall_fscore_support(references, preds, average='binary')
|
176 |
+
metrics['f1'].append(f1)
|
177 |
+
metrics['precision'].append(precision)
|
178 |
+
metrics['recall'].append(recall)
|
179 |
+
if f1 > best_f1:
|
180 |
+
best_f1 = f1
|
181 |
+
best_threshold = threshold
|
182 |
+
cm = confusion_matrix(references, preds)
|
183 |
+
report = classification_report(references, preds, target_names=['FOXNEWS', 'NBC'], digits=4)
|
184 |
+
best_metrics = {
|
185 |
+
'threshold': threshold,
|
186 |
+
'f1_score': f1,
|
187 |
+
'confusion_matrix': cm,
|
188 |
+
'classification_report': report
|
189 |
+
}
|
190 |
+
fig = go.Figure()
|
191 |
+
fig.add_trace(go.Scatter(x=thresholds, y=metrics['f1'], name='F1 Score'))
|
192 |
+
fig.add_trace(go.Scatter(x=thresholds, y=metrics['precision'], name='Precision'))
|
193 |
+
fig.add_trace(go.Scatter(x=thresholds, y=metrics['recall'], name='Recall'))
|
194 |
+
fig.update_layout(
|
195 |
+
title='Metrics by Threshold',
|
196 |
+
xaxis_title='Threshold',
|
197 |
+
yaxis_title='Score',
|
198 |
+
showlegend=True
|
199 |
+
)
|
200 |
+
return fig, best_metrics
|
201 |
+
|
202 |
+
def plot_confusion_matrix(cm):
|
203 |
+
labels = ['FOXNEWS', 'NBC']
|
204 |
+
annotations = []
|
205 |
+
for i in range(len(labels)):
|
206 |
+
for j in range(len(labels)):
|
207 |
+
annotations.append(
|
208 |
+
dict(
|
209 |
+
text=str(cm[i, j]),
|
210 |
+
x=labels[j],
|
211 |
+
y=labels[i],
|
212 |
+
showarrow=False,
|
213 |
+
font=dict(color='white' if cm[i, j] > cm.max()/2 else 'black')
|
214 |
+
)
|
215 |
+
)
|
216 |
+
fig = go.Figure(data=go.Heatmap(
|
217 |
+
z=cm,
|
218 |
+
x=labels,
|
219 |
+
y=labels,
|
220 |
+
colorscale='Blues',
|
221 |
+
showscale=True
|
222 |
+
))
|
223 |
+
fig.update_layout(
|
224 |
+
title='Confusion Matrix',
|
225 |
+
xaxis_title='Predicted Label',
|
226 |
+
yaxis_title='True Label',
|
227 |
+
annotations=annotations
|
228 |
+
)
|
229 |
+
return fig
|
230 |
+
|
231 |
+
def main():
|
232 |
+
st.title("News Classifier Model Evaluation")
|
233 |
+
uploaded_file = st.file_uploader("Upload your test dataset (CSV)", type=['csv'])
|
234 |
+
if uploaded_file is not None:
|
235 |
+
df = pd.read_csv(uploaded_file)
|
236 |
+
st.write("Preview of uploaded data:")
|
237 |
+
st.dataframe(df.head())
|
238 |
+
model, tokenizer, device = load_model_and_tokenizer()
|
239 |
+
if model and tokenizer:
|
240 |
+
test_dataset = preprocess_data(df)
|
241 |
+
if test_dataset:
|
242 |
+
st.write(f"Total examples: {len(test_dataset)}")
|
243 |
+
with st.spinner('Evaluating model...'):
|
244 |
+
references, probabilities = evaluate_model(model, tokenizer, device, test_dataset)
|
245 |
+
roc_fig, auc_score = plot_roc_curve(references, probabilities)
|
246 |
+
st.plotly_chart(roc_fig)
|
247 |
+
st.metric("AUC-ROC Score", f"{auc_score:.4f}")
|
248 |
+
metrics_fig, best_metrics = plot_metrics_by_threshold(references, probabilities)
|
249 |
+
st.plotly_chart(metrics_fig)
|
250 |
+
st.subheader("Best Threshold Evaluation")
|
251 |
+
col1, col2 = st.columns(2)
|
252 |
+
with col1:
|
253 |
+
st.metric("Best Threshold", f"{best_metrics['threshold']:.2f}")
|
254 |
+
with col2:
|
255 |
+
st.metric("Best F1 Score", f"{best_metrics['f1_score']:.4f}")
|
256 |
+
st.subheader("Confusion Matrix")
|
257 |
+
cm_fig = plot_confusion_matrix(best_metrics['confusion_matrix'])
|
258 |
+
st.plotly_chart(cm_fig)
|
259 |
+
st.subheader("Classification Report")
|
260 |
+
st.text(best_metrics['classification_report'])
|
261 |
+
if __name__ == "__main__":
|
262 |
+
main()
|
263 |
+
```
|
264 |
+
|
265 |
+
2. Run the Streamlit application:
|
266 |
+
```bash
|
267 |
+
streamlit run eval_pipeline.py
|
268 |
+
```
|
269 |
+
|
270 |
+
3. The web interface will automatically open in your default browser
|
271 |
+
|
272 |
+
### Using the Web Interface
|
273 |
+
|
274 |
+
1. **Upload Test Data**:
|
275 |
+
- Prepare your test data in CSV format
|
276 |
+
- Required columns:
|
277 |
+
- Index column (automatic numbering)
|
278 |
+
- "title": The news headline text
|
279 |
+
- "label": Binary label (0 for Fox News, 1 for NBC News)
|
280 |
+
- "News Outlet": The source ("Fox News" or "NBC News")
|
281 |
+
|
282 |
+
2. **View Evaluation Results**:
|
283 |
+
The pipeline will display:
|
284 |
+
- Data preview
|
285 |
+
- ROC curve with AUC score
|
286 |
+
- Metrics vs threshold plot
|
287 |
+
- Best threshold and F1 score
|
288 |
+
- Confusion matrix visualization
|
289 |
+
- Detailed classification report
|
290 |
+
|
291 |
+
### Sample Data Format
|
292 |
+
```csv
|
293 |
+
,title,label,News Outlet
|
294 |
+
0,"Jack Carr's take on the late Tom Clancy, born on this day in 1947",0,Fox News
|
295 |
+
1,"Feeding America CEO asks community to help others amid today's high inflation",0,Fox News
|
296 |
+
2,"World Food Programme Director Cindy McCain: Northern Gaza is in a 'full-blown famine'",1,NBC News
|
297 |
+
3,"Ohio sheriff suggests residents keep a list of homes with Harris yard signs",1,NBC News
|
298 |
+
```
|
299 |
+
|
300 |
+
## Model Architecture
|
301 |
+
- Base model: BERT (bert-base-uncased)
|
302 |
+
- Fine-tuned for binary classification
|
303 |
+
- Uses PyTorch and Hugging Face Transformers
|
304 |
+
|
305 |
+
## Limitations and Bias
|
306 |
+
This model has been trained on news headlines from specific sources (Fox News and NBC News) and time periods, which may introduce certain biases:
|
307 |
+
- Limited to two specific news sources
|
308 |
+
- Temporal bias based on training data collection period
|
309 |
+
- May not generalize well to other news sources or formats
|
310 |
+
|
311 |
+
## Evaluation Metrics
|
312 |
+
The pipeline provides comprehensive evaluation metrics:
|
313 |
+
- AUC-ROC Score
|
314 |
+
- F1 Score
|
315 |
+
- Precision & Recall
|
316 |
+
- Confusion Matrix
|
317 |
+
- Detailed Classification Report
|
318 |
+
|
319 |
+
## Troubleshooting
|
320 |
+
|
321 |
+
Common issues and solutions:
|
322 |
+
|
323 |
+
1. **CUDA/GPU Error**:
|
324 |
+
- The pipeline automatically falls back to CPU if CUDA is not available
|
325 |
+
- No action needed from user
|
326 |
+
|
327 |
+
2. **Memory Issues**:
|
328 |
+
- Default batch size is 16
|
329 |
+
- Reduce batch size if memory constraints exist
|
330 |
+
|
331 |
+
3. **File Format Error**:
|
332 |
+
- Ensure CSV file has exact column names: "title", "label", "News Outlet"
|
333 |
+
- Verify label values are 0 or 1
|
334 |
+
- Confirm "News Outlet" values are exactly "Fox News" or "NBC News"
|
335 |
+
|
336 |
+
## License
|
337 |
+
This project is licensed under the MIT License.
|