Spaces:
Runtime error
Runtime error
Commit ·
17fcd01
1
Parent(s): e6f95e3
Initial Commit
Browse filesFiles changed (21)
- app.pyAdded+93
- build/spam_ham_model.pthAdded+3
- build/tfidf_vectorizer.pklAdded+3
- model_development/__pycache__/custom_dataloader.cpython-310.pycAdded
- model_development/__pycache__/custom_dataset.cpython-310.pycAdded
- model_development/__pycache__/driver.cpython-310.pycAdded
- model_development/__pycache__/spamham_model.cpython-310.pycAdded
- model_development/__pycache__/split_dataset.cpython-310.pycAdded
- model_development/__pycache__/train_model.cpython-310.pycAdded
- model_development/__pycache__/transform_data.cpython-310.pycAdded
- model_development/__pycache__/word_tokenizer.cpython-310.pycAdded
- model_development/app.pyAdded+116
- model_development/custom_dataloader.pyAdded+17
- model_development/custom_dataset.pyAdded+28
- model_development/driver.pyAdded+10
- model_development/spamham_model.pyAdded+17
- model_development/split_dataset.pyAdded+13
- model_development/train_model.pyAdded+109
- model_development/transform_data.pyAdded+26
- model_development/word_tokenizer.pyAdded+15
- requirements.txtAdded+19
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import gradio as grimport pandas as pdfrom model_development.transform_data import Transform_Datafrom model_development.spamham_model import SpamHam_Modelimport torchfrom sklearn.feature_extraction.text import TfidfVectorizerimport joblib
css = """.gallery-item.svelte-p5q82i.svelte-p5q82i.svelte-p5q82i{ text-align:left}</style>"""
def generate_sample_sms_data(): retVal = [] data = Transform_Data("data/spam.csv") X, _ = data.process()
for item in X.to_numpy(): retVal.append([item]) return retVal
def show_selected(selected_row): if selected_row is not None: # 1. Loading the model MODEL_SAVE_PATH = 'build/spam_ham_model.pth' VECTORIZER_SAVE_PATH = 'build/tfidf_vectorizer.pkl'
model = SpamHam_Model(vocab_size = 8404, embedding_dim = 64, hidden_dim = 64, output_dim = 1) # '8404' are number of words which are part of training vocabulary. model.load_state_dict(torch.load(MODEL_SAVE_PATH, weights_only=True)) model.eval() # Set the model to evaluation mode
# 2. Loading the TfidfVectorizer vectorizer = joblib.load(VECTORIZER_SAVE_PATH) # Preprocess the input text using the same TF-IDF vectorizer text_tfidf = vectorizer.transform([selected_row[0]])
# Convert the sparse matrix to a dense NumPy array and then to a tensor text_tensor = torch.tensor(text_tfidf.toarray(), dtype=torch.float32) # Perform inference using the model with torch.no_grad(): # No need to calculate gradients during inference output = model(text_tensor) prediction = output.item()
# Since output will be between 0 and 1, apply a threshold (e.g., 0.5) for classification if prediction >= 0.5: return selected_row[0], "Ham" else: return selected_row[0], "Spam" return "None", "No row selected."
def bridge(message): if message is not None : return show_selected([message]) return "No row selected"
smslist = generate_sample_sms_data()
# Gradio interfacewith gr.Blocks(css=css) as demo: with gr.Row(): with gr.Column(scale = 2): txt_Message = gr.Textbox(label = "Try entering your custom message to evalute its classification as SPAM / HAM", placeholder = "Enter text") btnSubmit = gr.Button(value="Submit")
# Define a dataset component datasetControl = gr.Dataset( components = ['text'], samples = smslist, label = "Select an SMS from following dataset to evalute its classification as SPAM / HAM", type="values", samples_per_page=15 )
with gr.Column(scale = 1): txtSelectedMessage = gr.Label(label="Message for Classification") txtPrediction = gr.Label(label="Model predicted Classification") datasetControl.select(show_selected, datasetControl, outputs = [txtSelectedMessage,txtPrediction]) btnSubmit.click(bridge, txt_Message, outputs = [txtSelectedMessage,txtPrediction])
# Launch the appdemo.launch()
123version https://git-lfs.github.com/spec/v1oid sha256:c2833aae08632e300b726e61ae47254f79d3043ac91bb99b05b8e73475e1dee8size 2171278123version https://git-lfs.github.com/spec/v1oid sha256:99376794712e32b91d0aedfafdfae57013f2ec5b676a13980a635694f99d1b2asize 170526123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116#from driver import Driverimport torchfrom sklearn.feature_extraction.text import TfidfVectorizerimport joblib
from transform_data import Transform_Datafrom split_dataset import Split_Datasetfrom word_tokenizer import Word_Tokenizer# from feature_tensor import Feature_Tensor# from custom_dataset import Custom_Datasetfrom custom_dataloader import Custom_DataLoaderfrom train_model import Train_Modelfrom spamham_model import SpamHam_Model
class App(): if __name__ == "__main__":
data = Transform_Data("../data/spam.csv") X, Y = data.process()
tokenizer = Word_Tokenizer(X) X_feature, feature_extraction = tokenizer.tokenize() unique_words = list(feature_extraction.vocabulary_.keys()) vocabulary_size = len(unique_words)
# feature_extraction = TfidfVectorizer(min_df = 1, stop_words = "english", lowercase = True) # X_feature = feature_extraction.fit_transform(X) # unique_words = list(feature_extraction.vocabulary_.keys()) # vocabulary_size = len(unique_words) split_data = Split_Dataset(X_feature, Y) X_train, X_val, X_test, Y_train, Y_val, Y_test = split_data.split()
print(f"X_train Shape : {X_train.shape}") print(f"X_val Shape : {X_val.shape}") print(f"X_test Shape : {X_test.shape}") print("===========================================") # Hyperparameters batch_size = 5 epoch = 10 vocab_size = X_train.shape[1] #len(X_train.toarray()) #word_tokenize.get_vocabulary_size() # Example embedding_dim = 64 hidden_dim = 64 output_dim = 1 # When its 1, we would need to use Sigmoid. When its 2, can use torch.max. learning_rate = 0.001 dataloader = Custom_DataLoader() train_dataloader = dataloader.get_dataloader(X_train.toarray(), Y_train, batch_size) val_dataloader = dataloader.get_dataloader(X_val.toarray(), Y_val, batch_size) test_dataloader = dataloader.get_dataloader(X_test.toarray(), Y_test, batch_size)
# print(f"train_dataloader : {train_dataloader}") # print(f"length train_dataloader : {len(train_dataloader)}") # print(f"train_dataloader : Batch size : {train_dataloader.batch_size}") # print(f"train_dataloader : Dataset : {train_dataloader.dataset[0]}") # for batch_idx, (data, target) in enumerate(train_dataloader): # print("--------------------------------------------") # print(f"Batch {batch_idx}:") # print(f"Data shape: {data}") # print(f"Target shape: {target}") # # Print a few data points if needed # #print(f"Data sample: {data[batch_idx]}") print("===========================================")
train_model = Train_Model(epoch, vocab_size, embedding_dim, hidden_dim, output_dim, learning_rate, train_dataloader, val_dataloader, test_dataloader, feature_extraction) train_model.start() # Assuming 'SpamHamNN' is the class definition of your neural network model
# 1. Loading the model MODEL_SAVE_PATH = '../build/spam_ham_model.pth' VECTORIZER_SAVE_PATH = '../build/tfidf_vectorizer.pkl'
print(f"X train Shape : Vocab Size : {X_train.shape[1]}")
model = SpamHam_Model(vocab_size = X_train.shape[1], embedding_dim = 64, hidden_dim = 64, output_dim = 1) # Replace '8404' with the correct input size model.load_state_dict(torch.load(MODEL_SAVE_PATH, weights_only=True)) model.eval() # Set the model to evaluation mode
# 2. Loading the TfidfVectorizer vectorizer = joblib.load(VECTORIZER_SAVE_PATH)
text = "Congratulations! You've won a $1000 gift card. Click here to claim now." #text = "Good morning Shakti. Lets play tennis today." # Preprocess the input text using the same TF-IDF vectorizer text_tfidf = vectorizer.transform([text]) # Convert the sparse matrix to a dense NumPy array and then to a tensor text_tensor = torch.tensor(text_tfidf.toarray(), dtype=torch.float32) # Perform inference using the model with torch.no_grad(): # No need to calculate gradients during inference output = model(text_tensor) prediction = output.item()
# Since output will be between 0 and 1, apply a threshold (e.g., 0.5) for classification if prediction >= 0.5: print("Ham") else: print("Spam")
1234567891011121314151617from custom_dataset import Custom_Datasetimport torchfrom torch.utils.data import Dataset, DataLoader
class Custom_DataLoader():
def __init__(self): NotImplemented
def get_dataloader(self, features, labels, batch_size): # Create the dataset dataset = Custom_Dataset(features, labels)
# Create the DataLoader # Choose an appropriate batch size dataloader = DataLoader(dataset, batch_size = batch_size, shuffle = True) return dataloader12345678910111213141516171819202122232425262728import torchfrom torch.utils.data import Dataset, DataLoader
class Custom_Dataset(Dataset): def __init__(self, features, labels): # self.features = features # self.labels = labels
self.features = torch.tensor(features, dtype=torch.float32) self.labels = torch.tensor(labels, dtype=torch.float32)
def __len__(self): return len(self.features) #return self.features.shape[0]
def __getitem__(self, idx): return self.features[idx], self.labels[idx]
# # Assuming X_train_feature and Y_train are NumPy arrays# # Convert them to PyTorch tensors# X_train_tensor = torch.tensor(X_train_feature, dtype=torch.float32) # Y_train_tensor = torch.tensor(Y_train, dtype=torch.long) # Assuming labels are integers
12345678910import torch
class Driver():
# Static method. No constructor defined under the class. def get_device(): # Test whether GPU instance is present on system. cuda_available = torch.cuda.is_available() device = torch.device("cuda" if cuda_available else "cpu") return device1234567891011121314151617import torchimport torch.nn as nn
class SpamHam_Model(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim): super(SpamHam_Model, self).__init__() self.fc1 = nn.Linear(vocab_size, embedding_dim) self.fc2 = nn.Linear(embedding_dim, hidden_dim) self.fc3 = nn.Linear(hidden_dim, output_dim) self.sigmoid = nn.Sigmoid()
def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) x = self.sigmoid(self.fc3(x)) return x12345678910111213from sklearn.model_selection import train_test_split
class Split_Dataset():
def __init__(self, X, Y): self.X = X self.Y = Y def split(self): X_train_temp, X_test, Y_train_temp, Y_test = train_test_split(self.X, self.Y, test_size = 0.2, random_state = 3) X_train, X_val, Y_train, Y_val = train_test_split(X_train_temp, Y_train_temp, test_size = 0.2, random_state = 3)
return X_train, X_val, X_test, Y_train, Y_val, Y_test123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import torchimport torch.nn as nnimport torch.optim as optimimport joblib
from sklearn.metrics import accuracy_scorefrom sklearn.metrics import classification_report
from driver import Driverfrom spamham_model import SpamHam_Model
class Train_Model():
def __init__(self, epoch, vocab_size, embedding_dim, hidden_dim, output_dim, learning_rate, train_dataloader, val_dataloader, test_dataloader, vectorizer): self.epochs = epoch self.input_size = vocab_size self.embedding_dim = embedding_dim self.hidden_dim = hidden_dim self.output_dim = output_dim self.learning_rate = learning_rate self.train_dataloader = train_dataloader self.val_dataloader = val_dataloader self.test_dataloader = test_dataloader self.vectorizer = vectorizer
self.device = Driver.get_device() print(f"Drive is : {self.device}")
def start(self): self.model = SpamHam_Model(self.input_size, self.embedding_dim, self.hidden_dim, self.output_dim) self.criterion = nn.BCELoss() self.optimizer = optim.Adam(self.model.parameters(), lr=self.learning_rate)
for epoch in range(self.epochs): self.model.train() train_loss = 0.0
# Training loop for texts, labels in self.train_dataloader: self.optimizer.zero_grad() outputs = self.model(texts).squeeze() loss = self.criterion(outputs, labels) loss.backward() self.optimizer.step() train_loss += loss.item()
# Validation loop val_loss = 0.0 val_preds = [] val_labels = []
self.model.eval() with torch.no_grad(): for texts, labels in self.val_dataloader: outputs = self.model(texts).squeeze() loss = self.criterion(outputs, labels) val_loss += loss.item()
val_preds += (outputs >= 0.5).int().tolist() val_labels += labels.int().tolist()
val_accuracy = accuracy_score(val_labels, val_preds)
print(f"Epoch {epoch+1}/{self.epochs}, Train Loss: {train_loss/len(self.train_dataloader):.4f}, Val Loss: {val_loss/len(self.val_dataloader):.4f}, Val Accuracy: {val_accuracy:.4f}")
# Testing loop (outside of Epoch) self.model.eval() test_preds = [] test_labels = []
with torch.no_grad(): for texts, labels in self.test_dataloader: outputs = self.model(texts).squeeze() test_preds += (outputs >= 0.5).int().tolist() test_labels += labels.int().tolist()
test_accuracy = accuracy_score(test_labels, test_preds) print(f"Test Accuracy: {test_accuracy:.4f}") print(f"Unique labels in test_labels: {set(test_labels)}") print(f"Unique predictions in test_preds: {set(test_preds)}") print("\nClassification Report:\n", classification_report(test_labels, test_preds, target_names=["ham", "spam"], labels=[0, 1])) # Assuming 'model' is your trained PyTorch model # Assuming 'vectorizer' is your trained TfidfVectorizer
MODEL_SAVE_PATH = '../build/spam_ham_model.pth' VECTORIZER_SAVE_PATH = '../build/tfidf_vectorizer.pkl'
# 1. Saving the model torch.save(self.model.state_dict(), MODEL_SAVE_PATH) print(f"Model saved to {MODEL_SAVE_PATH}")
# 2. Saving the TfidfVectorizer joblib.dump(self.vectorizer, VECTORIZER_SAVE_PATH) print(f"Vectorizer saved to {VECTORIZER_SAVE_PATH}")1234567891011121314151617181920212223242526import pandas as pdimport numpy as np
class Transform_Data():
def __init__(self, filepath): # './data/spam.csv' self.df = None self.filepath = filepath
def process(self): # read self.df = pd.read_csv(self.filepath, encoding='latin-1')
# keep only the first two columns: Label (v1) and Message (v2) text self.df = self.df.iloc[:, [0, 1]]
# transform self.df.loc[self.df["v1"] == "spam", "v1",] = 0 self.df.loc[self.df["v1"] == "ham", "v1",] = 1
# set X = self.df["v2"] Y = np.array(self.df["v1"].to_numpy(),dtype='int32') #print(np.unique(Y)) return X, Y123456789101112131415from sklearn.feature_extraction.text import TfidfVectorizer
class Word_Tokenizer(): def __init__(self, X_features): self.X_features = X_features def tokenize(self): self.feature_extraction = TfidfVectorizer(min_df = 1, stop_words = "english", lowercase = True) X_feature = self.feature_extraction.fit_transform(self.X_features) return X_feature, self.feature_extraction
12345678910111213141516171819filelock==3.15.4fsspec==2024.6.1Jinja2==3.1.4joblib==1.4.2MarkupSafe==2.1.5mpmath==1.3.0networkx==3.3numpy==2.1.0pandas==2.2.2python-dateutil==2.9.0.post0pytz==2024.1scikit-learn==1.5.1scipy==1.14.1six==1.16.0sympy==1.13.2threadpoolctl==3.5.0torch==2.4.0typing_extensions==4.12.2tzdata==2024.1app.pyAdded+93
build/spam_ham_model.pthAdded+3
build/tfidf_vectorizer.pklAdded+3
model_development/__pycache__/custom_dataloader.cpython-310.pycAdded
model_development/__pycache__/custom_dataset.cpython-310.pycAdded
model_development/__pycache__/driver.cpython-310.pycAdded
model_development/__pycache__/spamham_model.cpython-310.pycAdded
model_development/__pycache__/split_dataset.cpython-310.pycAdded
model_development/__pycache__/train_model.cpython-310.pycAdded
model_development/__pycache__/transform_data.cpython-310.pycAdded
model_development/__pycache__/word_tokenizer.cpython-310.pycAdded
model_development/app.pyAdded+116
model_development/custom_dataloader.pyAdded+17
model_development/custom_dataset.pyAdded+28
model_development/driver.pyAdded+10
model_development/spamham_model.pyAdded+17
model_development/split_dataset.pyAdded+13
model_development/train_model.pyAdded+109
model_development/transform_data.pyAdded+26
model_development/word_tokenizer.pyAdded+15
requirements.txtAdded+19