Jiahuita commited on
Commit
445733e
1 Parent(s): cd58baf

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +333 -195
README.md CHANGED
@@ -1,199 +1,337 @@
1
  ---
 
 
 
 
 
 
2
  library_name: transformers
3
- tags: []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  ---
5
 
6
- # Model Card for Model ID
7
-
8
- <!-- Provide a quick summary of what the model is/does. -->
9
-
10
-
11
-
12
- ## Model Details
13
-
14
- ### Model Description
15
-
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- 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. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.