An AI-powered machine learning system for detecting fake news articles using Natural Language Processing (NLP) and Explainable AI. The system combines a TF-IDFβbased ensemble classifier with linguistic analysis and risk-factor detection to deliver transparent, interpretable predictions. Built with Python, Flask, and scikit-learn.
- Key Features
- Quick Start
- Dataset
- Project Structure
- How It Works
- Model Architecture
- Training Pipeline
- Model Performance
- API Reference
- Usage Examples
- Security
- Technologies Used
- Research Background
- Contributing
- License
- Acknowledgments
| Feature | Description |
|---|---|
| Ensemble ML Model | Soft-voting ensemble of SGD, Logistic Regression, and Random Forest for robust predictions |
| Explainable AI | Shows the top TF-IDF features that influenced each prediction |
| Linguistic Analysis | Detects sensational language, clickbait patterns, excessive caps, and exclamation marks |
| Risk Factor Detection | Identifies red flags common in fake news (ALL CAPS words, sensational vocabulary) |
| Credibility Indicators | Highlights positive signals β neutral tone, professional punctuation, appropriate complexity |
| Confidence Calibration | Sigmoid-calibrated probabilities for reliable confidence scores |
| Secure Serialization | JSON + HMAC-SHA256 signatures β no pickle files, no arbitrary code execution risk |
| Web Interface | Modern, responsive Flask-based UI with dark gradient theme |
| Desktop GUI | Tkinter-based standalone desktop application |
| REST API | Full API with single prediction, batch prediction, analysis, and health-check endpoints |
- Python 3.8 or higher
- pip package manager
git clone https://github.com/Ghulam-Mustafa-Keerio/Fake-News_Detection_System.git
cd Fake-News_Detection_Systempip install -r requirements.txt# Option A: Using the provided helper script (requires Kaggle CLI)
pip install --user kaggle
export KAGGLE_USERNAME=your_username
export KAGGLE_API_TOKEN=your_token
bash scripts/download_kaggle_dataset.sh .
# Option B: Manual download
# Download from https://www.kaggle.com/datasets/clmentbisaillon/fake-and-real-news-dataset
# Place Fake.csv and True.csv into data/fake_and_real_news/
mkdir -p data/fake_and_real_news
mv Fake.csv True.csv data/fake_and_real_news/python train_model.pypython app.py
# Open http://localhost:5000 in your browserThis project uses the Kaggle Fake and Real News Dataset by ClΓ©ment Bisaillon.
| Metric | Value |
|---|---|
| Total Articles | 44,898 |
| Fake Articles | 23,481 |
| Real Articles | 21,417 |
| Source (Real) | Reuters news agency |
| Topics | Politics, world news, government, economics |
The dataset loading pipeline (dataset_utils.py) applies the following cleaning steps to prevent source-attribution bias:
- Reuters pattern removal β Strips
"CITY (Reuters) -"prefixes from Real articles so the model learns content quality rather than source formatting - AP pattern removal β Strips
"(AP)"attributions - Correction-note removal β Removes
"Corrects paragraph Xβ¦"boilerplate - Title + text concatenation β Merges headline and body into a single feature for richer context
- Shuffling β Randomized with
random_state=42for reproducibility
data/
βββ fake_and_real_news/
βββ Fake.csv # 23,481 fake news articles
βββ True.csv # 21,417 real news articles (Reuters)
Fake-News_Detection_System/
β
βββ train_model.py # Core ML training with TF-IDF ensemble & secure save/load
βββ app.py # Flask web application (routes & API)
βββ gui.py # Desktop GUI application (Tkinter)
βββ dataset_utils.py # Dataset download, loading, and cleaning utilities
β
βββ model.json # Trained ensemble model (secure JSON + HMAC)
βββ vectorizer.json # TF-IDF vectorizer (secure JSON + HMAC)
βββ model_config.json # Model metadata (type, vocab size, version)
βββ training_metrics.json # Training accuracy, precision, recall, F1, ROC-AUC
β
βββ templates/
β βββ index.html # Main web interface (dark gradient theme)
β βββ about.html # About page
β
βββ scripts/
β βββ download_kaggle_dataset.sh # Automated Kaggle dataset download
β
βββ data/
β βββ fake_and_real_news/ # Kaggle CSV files (Fake.csv, True.csv)
β
βββ requirements.txt # Python dependencies
βββ LICENSE # MIT License
βββ README.md # This file
Raw Text
β
βββ Lowercase conversion
βββ URL removal (http/https/www patterns)
βββ HTML tag stripping
βββ Special character removal
βββ Number removal
βββ Tokenization (NLTK word_tokenize)
βββ Stopword filtering (English)
βββ Lemmatization (WordNet)
β
βββ Clean Text
The AdvancedTextPreprocessor class also detects:
- Sensational words β
shocking,miracle,bombshell,conspiracy, etc. (15 patterns) - Clickbait patterns β
"you won't believe","doctors hate","what happened next", etc. (7 regex patterns)
| Parameter | Value |
|---|---|
| Max features | 10,000 |
| N-gram range | (1, 3) β unigrams, bigrams, trigrams |
| TF scaling | Sublinear (1 + log(tf)) |
| Min document frequency | 2 |
| Max document frequency | 95% |
βββββββββββββββββββββββ
β TF-IDF Features β
βββββββββββ¬ββββββββββββ
β
βββββββββββββββββΌββββββββββββββββ
βΌ βΌ βΌ
ββββββββββββββββββ ββββββββββββ ββββββββββββββββββ
β SGD Classifier β β Logistic β β Random Forest β
β (Modified β βRegressionβ β (200 trees) β
β Huber Loss) β β β β β
βββββββββ¬βββββββββ ββββββ¬ββββββ βββββββββ¬βββββββββ
β β β
βββββββββββββββββΌββββββββββββββββ
βΌ
βββββββββββββββββββββββ
β Soft Voting β
β (Probability Avg) β
βββββββββββ¬ββββββββββββ
βΌ
βββββββββββββββββββββββ
β Sigmoid Calibration β
βββββββββββ¬ββββββββββββ
βΌ
βββββββββββββββββββββββ
β REAL / FAKE + % β
βββββββββββββββββββββββ
Each prediction returns:
- Top Features β The TF-IDF terms with the highest positive/negative weight for the prediction
- Risk Factors β Detected red flags (e.g., "Excessive exclamation marks", "High capitalization ratio", "Multiple ALL CAPS words")
- Credibility Indicators β Positive signals (e.g., "Neutral language tone", "Professional punctuation", "Appropriate sentence complexity")
- Linguistic Analysis β Quantitative metrics: word count, sentence count, caps ratio, exclamation mark count, sensational word count
| Component | Configuration | Purpose |
|---|---|---|
| Vectorizer | TF-IDF, 10,000 features, n-gram (1,3), sublinear TF | Convert text to numerical feature vectors |
| SGD Classifier | Modified Huber loss, L2 penalty | Fast linear classifier with probability estimates |
| Logistic Regression | L2 regularization, lbfgs solver |
Interpretable linear model with calibrated probabilities |
| Random Forest | 200 estimators, max depth limited | Non-linear decision boundary, feature importance |
| VotingClassifier | Soft voting (averaged probabilities) | Combine all three classifiers for robustness |
| Calibration | CalibratedClassifierCV, sigmoid method |
Produce well-calibrated probability scores |
The training process in train_model.py follows this workflow:
- Data Loading β Load 44,898 articles from the Kaggle dataset via
load_kaggle_dataset() - Text Cleaning β Strip Reuters/AP attributions, remove boilerplate patterns
- Train/Test Split β 80% training (35,918 samples), 20% testing (8,980 samples), stratified
- TF-IDF Vectorization β Fit the vectorizer on training data; transform both sets
- Ensemble Training β Train SGD, Logistic Regression, and Random Forest; combine via
VotingClassifier - Probability Calibration β Apply
CalibratedClassifierCVwith sigmoid calibration - Evaluation β Compute accuracy, precision, recall, F1, ROC-AUC on the test set
- Secure Save β Serialize to JSON with HMAC-SHA256 integrity signatures
python train_model.pyExpected output:
Step 1/4: Loading data...
Loaded 44898 articles from Kaggle dataset
Step 2/4: Initializing detector...
Step 3/4: Training model...
Training completed!
Step 4/4: Saving model (SECURE JSON format)...
Model saved securely!
Evaluation metrics on the held-out test set (8,980 articles):
| Metric | Score |
|---|---|
| Accuracy | 98.86% |
| Precision | 98.87% |
| Recall | 98.86% |
| F1 Score | 98.86% |
| ROC-AUC | 99.93% |
| Split | Samples |
|---|---|
| Training set | 35,918 |
| Test set | 8,980 |
| Vocabulary size | 10,000 |
Fake News:
Input: "BREAKING NEWS!!! You wont BELIEVE what scientists discovered!
Proof that ALIENS have been controlling world governments for DECADES!"
Output: FAKE (87.6% confidence)
Risk Factors:
β οΈ Excessive exclamation marks
β οΈ High capitalization ratio
β οΈ Multiple ALL CAPS words
Real News:
Input: "The Federal Reserve announced today that it will maintain current
interest rates, citing stable inflation levels and moderate economic growth."
Output: REAL (66.4% confidence)
Credibility Indicators:
β Appropriate sentence complexity
β Neutral language tone
β Professional punctuation
The Flask application exposes the following REST endpoints:
Serves the main web interface.
Analyze a single text and return a prediction with explainability.
Request:
curl -X POST http://localhost:5000/predict \
-H "Content-Type: application/json" \
-d '{"text": "Your news article text here"}'Response:
{
"prediction": "REAL",
"confidence": 66.4,
"probabilities": { "fake": 33.6, "real": 66.4 },
"model_type": "advanced_ensemble",
"explanation": {
"top_features": [
{ "word": "citing", "weight": 0.23 },
{ "word": "federal reserve", "weight": 0.09 }
],
"risk_factors": [],
"credibility_indicators": [
"Neutral language tone",
"Professional punctuation"
],
"linguistic_analysis": {
"word_count": 41,
"sentence_count": 2,
"caps_ratio": 4.0,
"exclamation_marks": 0,
"sensational_words": 0
}
}
}Analyze up to 100 texts in a single request.
Request:
{
"texts": ["Article 1 text...", "Article 2 text..."]
}Perform linguistic analysis only (no prediction).
Request:
{ "text": "Text to analyze" }Health check returning model status and capabilities.
Response:
{
"status": "healthy",
"model_loaded": true,
"model_type": "advanced_ensemble",
"features": ["explainability", "calibrated_confidence", "linguistic_analysis"]
}List all available model types.
from train_model import AdvancedFakeNewsDetector
# Load the trained model
detector = AdvancedFakeNewsDetector()
detector.load_model()
# Make a prediction with full explainability
result = detector.predict("Your news text here", explain=True)
print(f"Prediction: {result.label}")
print(f"Confidence: {result.confidence}%")
print(f"Fake prob: {result.probabilities['fake']}%")
print(f"Real prob: {result.probabilities['real']}%")
print(f"Top features: {result.top_features}")
print(f"Risk factors: {result.risk_factors}")
print(f"Credibility: {result.credibility_indicators}")python app.py
# Navigate to http://localhost:5000python gui.py# Train on the Kaggle dataset
python train_model.pyThis project prioritizes secure model serialization over convenience.
Pickle files can execute arbitrary Python code when loaded, creating a severe security vulnerability:
# DANGER β Pickle can run malicious code
import pickle
pickle.loads(malicious_data) # Executes attacker's code!| Risk | Mitigation |
|---|---|
| Arbitrary code execution | Eliminated β JSON cannot execute code |
| Model tampering | HMAC-SHA256 signature verified on every load |
| Opaque model files | All files are human-readable JSON |
| Supply-chain attacks | No dependency on pickle or joblib for serialization |
# SAFE β JSON cannot execute code
import json
model_data = json.load(open('model.json')) # Just data, no code execution
# Signature is verified before useModel files produced:
model.jsonβ Classifier weights and parameters + HMAC signaturevectorizer.jsonβ TF-IDF vocabulary and IDF weights + HMAC signaturemodel_config.jsonβ Model metadata (type, vocabulary size, version)training_metrics.jsonβ Performance metrics from the last training run
| Category | Technology |
|---|---|
| Language | Python 3.8+ |
| Web Framework | Flask 2.3+ |
| Machine Learning | scikit-learn 1.3+ |
| NLP | NLTK 3.8+ (tokenization, lemmatization, stopwords) |
| Feature Extraction | TF-IDF Vectorizer (10,000 features, n-gram 1β3) |
| Ensemble Learning | VotingClassifier (SGD + Logistic Regression + Random Forest) |
| Serialization | JSON + HMAC-SHA256 (secure, no pickle) |
| Data Processing | pandas 2.0+, NumPy 1.24+ |
| Desktop GUI | Tkinter |
This project applies established techniques from NLP and misinformation detection research:
- TF-IDF with Sublinear Scaling β Dampens the impact of very frequent terms with
1 + log(tf), improving feature discrimination across large corpora. - Ensemble Learning β Voting classifiers reduce variance and increase robustness compared to any single model, a well-known technique in statistical learning.
- Probability Calibration β Sigmoid (Platt scaling) calibration produces probabilities that reflect true class frequencies, critical for trustworthy confidence scores.
- Stylometric / Linguistic Analysis β Fake news tends to exhibit specific surface-level cues: excessive capitalization, exclamation marks, sensational vocabulary, and clickbait sentence structures.
- Explainable AI (XAI) β Feature-importance explanations let users evaluate predictions rather than blindly trusting a black box, aligning with responsible AI principles.
- Source-Attribution Debiasing β Removing Reuters/AP bylines from training data prevents the model from learning shortcut features unrelated to content veracity.
Contributions are welcome! To contribute:
- Fork the repository
- Create a feature branch (
git checkout -b feature/your-feature) - Commit your changes (
git commit -m "Add your feature") - Push to the branch (
git push origin feature/your-feature) - Open a Pull Request
This project is licensed under the MIT License β see the LICENSE file for details.
Copyright Β© 2026 Ghulam Mustafa
- Kaggle Fake and Real News Dataset by ClΓ©ment Bisaillon β training data
- NLTK β natural language processing toolkit
- scikit-learn β machine learning library
- Flask β lightweight web framework
- Research community studying computational approaches to misinformation detection