{"id":25934370,"url":"https://github.com/tahirzia-1/nlp-textclassify","last_synced_at":"2026-04-12T16:03:42.730Z","repository":{"id":279400812,"uuid":"938686010","full_name":"TahirZia-1/NLP-TextClassify","owner":"TahirZia-1","description":"A hands-on NLP project comparing classic ML models (Naïve Bayes, SVM, Logistic Regression) and ANNs for text classification using SMS Spam and 20 Newsgroups datasets.","archived":false,"fork":false,"pushed_at":"2025-02-25T10:50:54.000Z","size":0,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-25T11:37:29.295Z","etag":null,"topics":["adam-optimizer","ann","cbow","deep-learning","lemmatization","logistic-regression","naive-bayes-classifier","nlp","nlp-machine-learning","skipgram-algorithm","svm","tensorflow","tfidf","tfidf-vectorizer","tokenization","vectorization","word2vec"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TahirZia-1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-25T10:44:59.000Z","updated_at":"2025-02-25T10:56:56.000Z","dependencies_parsed_at":"2025-02-25T11:47:36.776Z","dependency_job_id":null,"html_url":"https://github.com/TahirZia-1/NLP-TextClassify","commit_stats":null,"previous_names":["tahirzia-1/nlp-textclassify"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TahirZia-1%2FNLP-TextClassify","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TahirZia-1%2FNLP-TextClassify/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TahirZia-1%2FNLP-TextClassify/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TahirZia-1%2FNLP-TextClassify/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TahirZia-1","download_url":"https://codeload.github.com/TahirZia-1/NLP-TextClassify/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241763677,"owners_count":20016162,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["adam-optimizer","ann","cbow","deep-learning","lemmatization","logistic-regression","naive-bayes-classifier","nlp","nlp-machine-learning","skipgram-algorithm","svm","tensorflow","tfidf","tfidf-vectorizer","tokenization","vectorization","word2vec"],"created_at":"2025-03-04T00:57:34.156Z","updated_at":"2026-04-12T16:03:42.665Z","avatar_url":"https://github.com/TahirZia-1.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 📝 Text Classification Report: SMS Spam Collection and 20 Newsgroups Datasets\r\n\r\n\r\n## 🌟 1. Introduction\r\n\r\nThis report presents an implementation of **text classification** on two distinct datasets: the *SMS Spam Collection* dataset and the *20 Newsgroups* dataset. The objective is to preprocess textual data, extract features using **TF-IDF** and **Word2Vec**, and evaluate the performance of multiple classification models, including ***Naive Bayes***, ***Support Vector Machines (SVM)***, ***Logistic Regression***, and a ***Neural Network*** built with TensorFlow. The models are assessed using standard metrics such as *accuracy*, *precision*, *recall*, and *F1-score*, with results visualized for comparison.\r\n\r\n- **SMS Spam Collection**: Binary-labeled text messages (*spam* or *ham*).\r\n- **20 Newsgroups**: Multi-class dataset of news articles across 20 categories.\r\n\r\nThis analysis highlights the effectiveness of different approaches for **spam detection** (binary classification) and **news categorization** (multi-class classification).\r\n\r\n---\r\n\r\n## 🛠️ 2. Methodology\r\n\r\n### 2.1 Datasets\r\n- **SMS Spam Collection**: Loaded from `spam.csv`, containing **5,572 messages** labeled as `ham` (0) or `spam` (1).\r\n- **20 Newsgroups**: Fetched via `sklearn.datasets.fetch_20newsgroups`, containing **18,846 documents** across 20 categories, with headers, footers, and quotes removed.\r\n\r\n### 2.2 Data Preprocessing\r\nA preprocessing function (`preprocess_text`) was applied to both datasets:\r\n- Converted text to *lowercase*.\r\n- Removed special characters and numbers using regex (`re.sub`).\r\n- Tokenized text with NLTK’s `word_tokenize`.\r\n- Removed stopwords and lemmatized tokens using `WordNetLemmatizer`.\r\n- Joined tokens into a cleaned string (`processed_text` column).\r\n\r\n### 2.3 Dataset Splitting\r\nDatasets were split into *training (60%)*, *validation (20%)*, and *test (20%)* sets using `prepare_dataset` with stratification:\r\n- **SMS**: Train: *3,343*, Validation: *1,114*, Test: *1,115*.\r\n- **Newsgroups**: Train: *11,307*, Validation: *3,769*, Test: *3,770*.\r\n\r\n### 2.4 Feature Extraction\r\nTwo methods were used:\r\n1. **TF-IDF Vectorization**:\r\n   - *SMS*: `TfidfVectorizer` with 5,000 max features → `(3,343, 5,000)`.\r\n   - *Newsgroups*: `TfidfVectorizer` with 10,000 max features → `(11,307, 10,000)`.\r\n2. **Word2Vec Embeddings**:\r\n   - Custom Word2Vec models trained on training corpus (`vector_size=100, window=5, min_count=1`).\r\n   - Sentence embeddings as mean of word vectors → `(3,343, 100)` for SMS, `(11,307, 100)` for Newsgroups.\r\n\r\n### 2.5 Models\r\nFour models were implemented:\r\n1. **Naive Bayes**: `MultinomialNB` (TF-IDF features).\r\n2. **SVM**: `SVC` (TF-IDF features).\r\n3. **Logistic Regression**: `LogisticRegression` (TF-IDF features).\r\n4. **Neural Network**: TensorFlow `Sequential` model:\r\n   - `Dense(256, ReLU)` → `Dropout(0.4)`.\r\n   - `Dense(128, ReLU)` → `Dropout(0.3)`.\r\n   - `Dense(64, ReLU)` → `Dropout(0.2)`.\r\n   - Output: `Dense(2, sigmoid)` (SMS); `Dense(20, softmax)` (Newsgroups).\r\n   - Trained for *100 epochs* with *Adam* optimizer.\r\n\r\n### 2.6 Evaluation Metrics\r\nA custom `evaluate_model` function computed:\r\n- *Accuracy*, *Precision*, *Recall*, *F1-Score* (weighted for multi-class).\r\n- *Sensitivity* and *Specificity* (binary classification).\r\n- *Classification Report* and *Confusion Matrix*.\r\n- *ROC-AUC* (binary classification).\r\n\r\n---\r\n\r\n## 📊 3. Results\r\n\r\n### 3.1 SMS Spam Detection\r\nPerformance on the SMS test set (*1,115 samples*):\r\n\r\n| **Model**            | **Accuracy** | **Precision** | **Recall** | **F1-Score** |\r\n|-----------------------|--------------|---------------|------------|--------------|\r\n| Naive Bayes          | 0.9614       | **0.9908**    | 0.7200     | 0.8340       |\r\n| **SVM**              | **0.9839**   | 0.9714        | **0.9670** | **0.9379**   |\r\n| Logistic Regression  | 0.9534       | 0.9712        | 0.6733     | 0.7953       |\r\n| Neural Network       | 0.9193       | 0.7000        | 0.7000     | 0.7000       |\r\n\r\n- **Best Model**: *SVM* with highest accuracy (0.9839) and balanced F1-score (0.9379).\r\n- **Observations**: Naive Bayes led in precision; SVM excelled overall. Neural Network underperformed.\r\n\r\n### 3.2 20 Newsgroups Classification\r\nPerformance on the Newsgroups test set (*3,770 samples*):\r\n\r\n| **Model**            | **Accuracy** | **Precision** | **Recall** | **F1-Score** |\r\n|-----------------------|--------------|---------------|------------|--------------|\r\n| Naive Bayes          | 0.7037       | **0.7233**    | 0.7037     | 0.6911       |\r\n| SVM                  | 0.6997       | 0.7122        | 0.6997     | 0.7008       |\r\n| **Logistic Regression** | **0.7090** | 0.7159        | **0.7090** | **0.7065**   |\r\n| Neural Network       | 0.4459       | 0.4763        | 0.4459     | 0.4349       |\r\n\r\n- **Best Model**: *Logistic Regression* with highest accuracy (0.7090), edging Naive Bayes by 0.0053.\r\n- **Observations**: Neural Network lagged significantly (0.4459); traditional models performed consistently (~0.70).\r\n\r\n### 3.3 Neural Network Training (Newsgroups)\r\n- *Training Accuracy*: 0.1271 (Epoch 1) → 0.4550 (Epoch 100).\r\n- *Validation Accuracy*: Peaked at 0.4582 (Epoch 89), final 0.4460.\r\n- *Loss*: Stabilized at ~1.65–1.68, suggesting limited generalization.\r\n\r\n---\r\n\r\n## 🎨 4. Visualizations\r\n- **Training History (Newsgroups NN)**: Accuracy/loss plots showed convergence; validation plateaued after ~50 epochs.\r\n- **Model Comparison Bar Charts**:\r\n  - *SMS*: SVM dominated.\r\n  - *Newsgroups*: Logistic Regression and Naive Bayes led; Neural Network trailed.\r\n\r\n---\r\n\r\n## 🏁 5. Conclusion\r\n\r\nThis analysis successfully implemented text classification on the *SMS Spam Collection* and *20 Newsgroups* datasets. Key findings:\r\n\r\n- **SMS Spam Detection**: *SVM* was most accurate (0.9839), excelling with TF-IDF features.\r\n- **20 Newsgroups Classification**: *Logistic Regression* led (0.7090), narrowly beating Naive Bayes (0.7037).\r\n- **Neural Network**: Underperformed (0.4459 for Newsgroups), possibly due to tuning or complexity.\r\n\r\n### 💡 Recommendations\r\n- Tune Neural Network hyperparameters or use pre-trained embeddings (*e.g., GloVe*).\r\n- Explore ensemble methods for model synergy.\r\n- Increase Word2Vec `vector_size` for richer embeddings.\r\n\r\nThis study showcases the strengths of traditional ML (*SVM*, *Logistic Regression*) versus deep learning for text classification.\r\n\r\n---\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftahirzia-1%2Fnlp-textclassify","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftahirzia-1%2Fnlp-textclassify","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftahirzia-1%2Fnlp-textclassify/lists"}