Keshavp08 commited on
Commit
7df8bd8
·
1 Parent(s): 5369efc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -100
app.py CHANGED
@@ -1,103 +1,88 @@
1
- # Import required libraries
 
2
  import pandas as pd
3
- import numpy as np
4
  import torch
5
- from sklearn.model_selection import train_test_split
6
- from transformers import BertTokenizer, BertForSequenceClassification, AdamW
7
- from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
8
-
9
- # Load training dataset
10
- train_data = pd.read_csv('train.csv')
11
- train_tweets = train_data['comment_text'].values
12
- train_labels = train_data[['toxic', 'severe_toxic', 'threat', 'obscene', 'insult', 'identity_hate']].values
13
-
14
- # Split dataset into training and validation sets
15
- train_tweets, val_tweets, train_labels, val_labels = train_test_split(train_tweets, train_labels, test_size=0.2, random_state=42)
16
-
17
- # Load pre-trained BERT tokenizer
18
- tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
19
-
20
- # Tokenize input tweets
21
- train_tokens = tokenizer.batch_encode_plus(train_tweets.tolist(), max_length=512, pad_to_max_length=True, truncation=True)
22
- val_tokens = tokenizer.batch_encode_plus(val_tweets.tolist(), max_length=512, pad_to_max_length=True, truncation=True)
23
-
24
- # Convert tokenized inputs to PyTorch tensors
25
- train_seq = torch.tensor(train_tokens['input_ids'])
26
- train_mask = torch.tensor(train_tokens['attention_mask'])
27
- train_y = torch.tensor(train_labels, dtype=torch.float32)
28
-
29
- val_seq = torch.tensor(val_tokens['input_ids'])
30
- val_mask = torch.tensor(val_tokens['attention_mask'])
31
- val_y = torch.tensor(val_labels, dtype=torch.float32)
32
-
33
- # Create PyTorch DataLoader objects
34
- batch_size = 32
35
- train_data = TensorDataset(train_seq, train_mask, train_y)
36
- train_sampler = RandomSampler(train_data)
37
- train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)
38
-
39
- val_data = TensorDataset(val_seq, val_mask, val_y)
40
- val_sampler = SequentialSampler(val_data)
41
- val_dataloader = DataLoader(val_data, sampler=val_sampler, batch_size=batch_size)
42
-
43
- # Load pre-trained BERT model and add a classification head
44
- model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=6)
45
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
46
- model.to(device)
47
-
48
- # Set optimizer and learning rate
49
- optimizer = AdamW(model.parameters(), lr=2e-5)
50
-
51
- # Fine-tune the model on the training set
52
- epochs = 2
53
- for epoch in range(epochs):
54
- model.train()
55
- total_loss = 0
56
- for batch in train_dataloader:
57
- batch_seq = batch[0].to(device)
58
- batch_mask = batch[1].to(device)
59
- batch_y = batch[2].to(device)
60
- model.zero_grad()
61
- outputs = model(batch_seq, attention_mask=batch_mask, labels=batch_y)
62
- loss = outputs[0]
63
- total_loss += loss.item()
64
- loss.backward()
65
- torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
66
- optimizer.step()
67
- avg_train_loss = total_loss / len(train_dataloader)
68
- print("Epoch:", epoch+1, "Training Loss:", avg_train_loss)
69
-
70
- # Evaluate model performance on validation
71
- # Evaluate model performance on validation
72
- model.eval()
73
- total_val_accuracy = 0
74
- total_val_f1 = 0
75
  with torch.no_grad():
76
- for batch in val_dataloader:
77
- batch_seq = batch[0].to(device)
78
- batch_mask = batch[1].to(device)
79
- batch_y = batch[2].to(device)
80
- outputs = model(batch_seq, attention_mask=batch_mask)
81
- logits = outputs[0]
82
- preds = torch.sigmoid(logits).cpu().detach().numpy()
83
- batch_y = batch_y.cpu().detach().numpy()
84
- val_accuracy = ((preds > 0.5) == batch_y).mean()
85
- total_val_accuracy += val_accuracy
86
- val_f1 = f1_score(batch_y, preds > 0.5, average='macro')
87
- total_val_f1 += val_f1
88
-
89
- avg_val_accuracy = total_val_accuracy / len(val_dataloader)
90
- avg_val_f1 = total_val_f1 / len(val_dataloader)
91
- print("Validation Accuracy:", avg_val_accuracy)
92
- print("Validation F1 Score:", avg_val_f1)
93
-
94
- for i, label in enumerate(['toxic', 'severe_toxic', 'threat', 'obscene', 'insult', 'identity_hate']):
95
- label_accuracy = ((preds[:,i] > 0.5) == batch_y[:,i]).mean()
96
- label_f1 = f1_score(batch_y[:,i], preds[:,i] > 0.5)
97
- print(label, "Accuracy:", label_accuracy)
98
- print(label, "F1 Score:", label_f1)
99
-
100
- overall_accuracy = ((preds > 0.5) == batch_y).mean()
101
- overall_f1 = f1_score(batch_y, preds > 0.5, average='macro')
102
- print("Overall Accuracy:", overall_accuracy)
103
- print("Overall F1 Score:", overall_f1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import required packages
2
+ import streamlit as st
3
  import pandas as pd
 
4
  import torch
5
+ from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
6
+
7
+ # Define model paths
8
+ MODEL_MAP = {
9
+ 'BERT': 'bert-base-uncased',
10
+ 'RoBERTa': 'roberta-base',
11
+ 'DistilBERT': 'distilbert-base-uncased'
12
+ }
13
+
14
+ # Define label columns
15
+ LABEL_COLS = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']
16
+
17
+ # Load pre-trained model and tokenizer
18
+ @st.cache_resource
19
+ def load_model(model_name):
20
+ path = "finetuned_model.pt"
21
+ model = torch.load(path)
22
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_MAP[model_name])
23
+ return model, tokenizer
24
+
25
+ # Classify text using pre-trained model
26
+ def classify_text(model, tokenizer, text):
27
+ inputs = tokenizer.encode_plus(
28
+ text,
29
+ add_special_tokens=True,
30
+ max_length=512,
31
+ padding='max_length',
32
+ return_tensors='pt',
33
+ truncation=True
34
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  with torch.no_grad():
36
+ logits = model(inputs['input_ids'],inputs['attention_mask'])[0]
37
+ probabilities = torch.softmax(logits, dim=1)[0]
38
+ pred_class = torch.argmax(probabilities, dim=0)
39
+ return LABEL_COLS[pred_class], round(probabilities[0].tolist(),2)
40
+
41
+ # Define Streamlit app layout
42
+ def app():
43
+ st.title('Classifier App')
44
+ model_options = list(MODEL_MAP.keys())
45
+ model_name = st.sidebar.selectbox('Select model', model_options)
46
+ st.sidebar.write('You selected:', model_name)
47
+ model, tokenizer = load_model(model_name)
48
+
49
+ # Input text to classify
50
+ st.subheader('Enter your text below:')
51
+ text_input = st.text_area(label='', height=100, max_chars=500)
52
+
53
+ # Classify text and display results
54
+ if st.button('Classify'):
55
+ if not text_input:
56
+ st.write('Please enter some text')
57
+ else:
58
+ class_label, class_prob = classify_text(model, tokenizer, text_input)
59
+ st.subheader('Result')
60
+ st.write('Input Text:', text_input)
61
+ st.write('Highest Toxicity Class:', class_label)
62
+ st.write('Probability:', class_prob)
63
+
64
+ # Display classification results
65
+ st.subheader('Classification Results')
66
+ if 'classification_results' not in st.session_state:
67
+ st.session_state.classification_results = pd.DataFrame(columns=['text', 'toxicity_class', 'probability'])
68
+ if st.button('Add to Results'):
69
+ if not text_input:
70
+ st.write('Please enter some text')
71
+ else:
72
+ class_label, class_prob = classify_text(model, tokenizer, text_input)
73
+ st.session_state.classification_results = st.session_state.classification_results.append({
74
+ 'text': text_input,
75
+ 'toxicity_class': class_label,
76
+ 'probability': class_prob
77
+ }, ignore_index=True)
78
+
79
+ # Display saved classification results
80
+ if not st.session_state.classification_results.empty:
81
+ st.write(st.session_state.classification_results)
82
+
83
+
84
+
85
+
86
+
87
+
88
+