projectduniya.com

Fake News Detection Using NLP and Machine Learning: Complete Python Project

Fake News Detection Using NLP and Machine Learning: Complete Python Project
Fake News Detection Using NLP and Machine Learning: Complete Python Project

Introduction

Fake news and online misinformation can spread through websites, social media platforms, messaging applications and other digital channels. Readers may find it difficult to distinguish trustworthy reporting from misleading or fabricated content, especially when information is shared without checking its original source.

A Fake News Detection System is a machine-learning project that analyses the text of a news article and predicts whether it resembles examples labelled as real or fake in a training dataset. It combines Natural Language Processing (NLP), text feature extraction and a classification algorithm.

In this tutorial, you will build a working Fake News Detection application using Python, Pandas, Scikit-learn and Streamlit. The project will train a model, evaluate its performance, save the trained pipeline and provide a simple web interface for testing news text.

Important: This application learns patterns from a labelled dataset. It does not independently verify claims, investigate sources or establish whether a particular event happened. Its predictions should never be treated as proof that an article is true or false.

1. Project Overview

The project accepts a news headline and article body as input. It combines the text, converts it into numerical features and sends those features to a trained machine-learning classifier.

Project detailDescription
Project nameFake News Detection System
Programming languagePython
DomainArtificial Intelligence and Machine Learning
NLP techniqueTF-IDF vectorization
Classification algorithmLogistic Regression
DatasetWELFake
Web interfaceStreamlit
OutputPredicted class and model probability

2. Project Objectives

  • Understand how NLP can be used for text classification.
  • Prepare a labelled news dataset for machine learning.
  • Convert news text into numerical TF-IDF features.
  • Train a Logistic Regression classification model.
  • Evaluate the model using accuracy, precision, recall and F1-score.
  • Save the trained model for later use.
  • Develop a simple web application for interactive predictions.
  • Understand the limitations and ethical considerations of automated misinformation classification.

3. Technologies and Tools Required

TechnologyPurpose
PythonMain programming language
PandasDataset loading and data preparation
Scikit-learnFeature extraction, model training and evaluation
TF-IDFConverting text into numerical features
Logistic RegressionClassifying news text
JoblibSaving and loading the trained pipeline
StreamlitCreating the web interface

4. Dataset for Fake News Detection

This project uses the WELFake dataset. It contains 72,134 news articles, including 35,028 labelled as real and 37,106 labelled as fake. The dataset combines material from four existing news datasets and provides headline, article text and label fields.

The label convention is:

  • 0: Fake news
  • 1: Real news

You can obtain the dataset from the official Zenodo record:

Download or view the WELFake dataset on Zenodo.

Dataset preparation: Download WELFake_Dataset.csv and place it in the project directory. Check the dataset’s licence and attribution requirements before redistributing it or using it in a commercial application.

Understanding the dataset columns

ColumnMeaning
Unnamed: 0Dataset row identifier, if present
titleNews headline
textFull news article text
labelTarget classification: 0 or 1

5. How the System Works

The application follows a standard supervised text-classification workflow.

Project workflow

WELFake Dataset → Data Cleaning → Train-Test Split → TF-IDF Feature Extraction → Logistic Regression → Model Evaluation → Save Model → Streamlit Prediction Interface

Step 1: Data collection

Load the labelled news articles from the CSV dataset. Each record should contain a headline, article text and corresponding label.

Step 2: Text preparation

Combine the headline and article body into one text field. Handle missing values and remove records without usable text or valid labels.

Step 3: Train-test splitting

Divide the dataset into training and testing portions. The training data teaches the classifier, while the test data provides an independent evaluation of its performance.

Step 4: TF-IDF feature extraction

TF-IDF stands for Term Frequency-Inverse Document Frequency. It assigns numerical weights to words and phrases based on their frequency in a document and their distribution across the collection of documents.

Step 5: Model training

Train a Logistic Regression classifier using the TF-IDF features and the known dataset labels.

Step 6: Prediction

When a user enters news text, the saved pipeline transforms the text and predicts the class.

6. Create the Project Directory

Create a folder named fake_news_detection and arrange the files as follows:

fake_news_detection/
│
├── WELFake_Dataset.csv
├── train_model.py
├── app.py
├── requirements.txt
└── models/
    └── fake_news_pipeline.joblib

The models directory and model file will be created automatically when the training script runs successfully.

7. Install the Required Libraries

Open a terminal inside the project directory and create a virtual environment.

python -m venv venv

Activate it on Windows:

venv\Scripts\activate

On macOS or Linux:

source venv/bin/activate

Create a file named requirements.txt and add:

pandas
scikit-learn
joblib
streamlit

Install the dependencies:

pip install -r requirements.txt

8. Build the Machine Learning Training Script

Create train_model.py. This script loads the dataset, prepares the text, splits the data, trains the model, prints evaluation metrics and saves the complete machine-learning pipeline.

import os
import pandas as pd
import joblib

from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    accuracy_score,
    classification_report,
    confusion_matrix
)


DATASET_PATH = "WELFake_Dataset.csv"
MODEL_DIR = "models"
MODEL_PATH = os.path.join(
    MODEL_DIR,
    "fake_news_pipeline.joblib"
)


def load_dataset(path):
    if not os.path.exists(path):
        raise FileNotFoundError(
            f"Dataset not found: {path}"
        )

    df = pd.read_csv(path)

    required_columns = {"title", "text", "label"}

    if not required_columns.issubset(df.columns):
        raise ValueError(
            "Dataset must contain title, text and label columns."
        )

    return df


def prepare_data(df):
    df = df.copy()

    df["title"] = df["title"].fillna("")
    df["text"] = df["text"].fillna("")

    df["content"] = (
        df["title"].astype(str) + " " +
        df["text"].astype(str)
    ).str.strip()

    df["label"] = pd.to_numeric(
        df["label"],
        errors="coerce"
    )

    df = df.dropna(subset=["label"])

    df = df[df["label"].isin([0, 1])]

    df = df[df["content"].str.len() > 0]

    X = df["content"]
    y = df["label"].astype(int)

    if y.nunique() != 2:
        raise ValueError(
            "The dataset must contain both classes: 0 and 1."
        )

    return X, y


def train():
    print("Loading dataset...")

    df = load_dataset(DATASET_PATH)

    print("Preparing text data...")

    X, y = prepare_data(df)

    print("Total usable records:", len(X))
    print("Class distribution:")
    print(y.value_counts())

    X_train, X_test, y_train, y_test = train_test_split(
        X,
        y,
        test_size=0.20,
        random_state=42,
        stratify=y
    )

    pipeline = Pipeline([
        (
            "tfidf",
            TfidfVectorizer(
                stop_words="english",
                max_features=50000,
                ngram_range=(1, 2),
                min_df=2,
                max_df=0.95,
                sublinear_tf=True
            )
        ),
        (
            "classifier",
            LogisticRegression(
                max_iter=1000,
                class_weight="balanced"
            )
        )
    ])

    print("Training model...")

    pipeline.fit(X_train, y_train)

    print("Evaluating model...")

    predictions = pipeline.predict(X_test)

    accuracy = accuracy_score(
        y_test,
        predictions
    )

    print("\nAccuracy:", round(accuracy, 4))

    print("\nClassification Report:")
    print(
        classification_report(
            y_test,
            predictions,
            target_names=["Fake", "Real"],
            zero_division=0
        )
    )

    print("\nConfusion Matrix:")
    print(confusion_matrix(y_test, predictions))

    os.makedirs(MODEL_DIR, exist_ok=True)

    joblib.dump(pipeline, MODEL_PATH)

    print("\nModel saved successfully:")
    print(MODEL_PATH)


if __name__ == "__main__":
    train()

Understanding the training code

  • read_csv() loads the dataset into a Pandas DataFrame.
  • fillna() replaces missing headline and article text with empty strings.
  • train_test_split() separates training and testing records while preserving the class proportions through stratification.
  • TfidfVectorizer() converts text into numerical features using single words and two-word phrases.
  • LogisticRegression() learns a classification boundary from the training examples.
  • classification_report() displays precision, recall and F1-score for both classes.
  • joblib.dump() saves the complete pipeline so the application can reuse the same text-processing and classification steps.
Why save the complete pipeline? The vectorizer must be fitted on training data only. Saving it together with the classifier ensures that new text is transformed using the same learned vocabulary and TF-IDF weights.

9. Train the Model

Run the following command from the project directory:

python train_model.py

The script will load the dataset, prepare the text, train the classifier and display the evaluation results. If training completes successfully, the model will be saved in the models folder.

Your actual accuracy and classification report will depend on the dataset file, its contents, preprocessing and software versions. Do not copy an accuracy figure from another project and present it as the result of your own experiment.

10. Evaluate the Model

Model evaluation is essential because a classifier may perform well on some examples but fail on others. Use more than one metric to understand its behaviour.

Accuracy

Accuracy measures the proportion of all test predictions that are correct.

Accuracy = Correct Predictions / Total Predictions

Precision

Precision measures how many predictions for a particular class were correct. For example, fake-news precision indicates the proportion of articles predicted as fake that were labelled fake in the test data.

Recall

Recall measures how many actual examples of a class were correctly identified by the classifier.

F1-score

The F1-score combines precision and recall using their harmonic mean. It is useful when you want to consider both false positives and false negatives.

Confusion matrix

A confusion matrix shows how many fake and real examples were correctly or incorrectly classified. It helps identify which type of mistake is more common.

Evaluation advice: A random train-test split is a useful starting point, but it does not guarantee that articles from the same source, event or time period are separated. Duplicate and near-duplicate articles can make evaluation results look better than real-world performance. For stronger research, investigate duplicates and test the model on a separate source or later time period.

11. Create the Streamlit Web Application

Now create app.py. The application will allow users to enter a headline and article text, submit the content and view the model’s prediction.

import os
import joblib
import streamlit as st


MODEL_PATH = os.path.join(
    "models",
    "fake_news_pipeline.joblib"
)


st.set_page_config(
    page_title="Fake News Detection",
    page_icon="📰",
    layout="centered"
)


@st.cache_resource
def load_model():
    if not os.path.exists(MODEL_PATH):
        return None

    return joblib.load(MODEL_PATH)


st.title("📰 Fake News Detection System")

st.write(
    "Enter a news headline and article text "
    "to receive a machine-learning classification."
)

model = load_model()

if model is None:
    st.error(
        "Trained model not found. "
        "Run python train_model.py first."
    )
    st.stop()


title = st.text_input(
    "News Headline",
    placeholder="Enter the news headline"
)

article = st.text_area(
    "News Article",
    placeholder="Paste the article content here...",
    height=250
)

if st.button("Analyze News", type="primary"):

    content = (title + " " + article).strip()

    if len(content) < 80:
        st.warning(
            "Please provide a longer headline and article "
            "so the model has more text to analyse."
        )

    else:
        prediction = int(model.predict([content])[0])

        st.subheader("Model Prediction")

        if prediction == 0:
            st.error("Prediction: FAKE")
        else:
            st.success("Prediction: REAL")

        if hasattr(model, "predict_proba"):
            probabilities = model.predict_proba([content])[0]

            classes = list(model.classes_)

            fake_probability = probabilities[
                classes.index(0)
            ]

            real_probability = probabilities[
                classes.index(1)
            ]

            st.write(
                f"Fake-class probability: "
                f"{fake_probability:.2%}"
            )

            st.write(
                f"Real-class probability: "
                f"{real_probability:.2%}"
            )

        st.info(
            "This is an automated model prediction, "
            "not independent fact verification. "
            "Check the original source and reliable "
            "independent reporting before sharing news."
        )

How the web application works

  1. Streamlit loads the saved model pipeline.
  2. The user enters a headline and article body.
  3. The application combines the two text fields.
  4. The saved TF-IDF vectorizer transforms the input.
  5. Logistic Regression predicts the class.
  6. The application displays the predicted class and, when available, the model's class probabilities.

The probability values are outputs from the classifier. They should not be interpreted as the verified probability that a news article is factually true or false.

12. Run the Complete Application

Make sure that you have already trained the model. Then run:

streamlit run app.py

Streamlit will start a local development server. Open the local address displayed in your terminal, normally:

http://localhost:8501

Enter a headline and article body, then click Analyze News. The application will display the model's prediction.

13. Sample Testing Scenarios

Use different kinds of test inputs to check how the application responds. These are testing scenarios, not guaranteed predictions.

Test 1: A detailed article from a known dataset example

Paste a complete article that is present in the dataset and check whether the prediction matches its recorded label. Remember that a training example is not an independent test.

Test 2: A short headline without article context

Enter only a few words. The application should request more text because a short headline may not contain enough information for a meaningful classification.

Test 3: An article about a topic not represented in training

Try a recent scientific, economic or local news article. Compare the output with reliable independent reporting. This helps demonstrate the model's limitations on unfamiliar material.

Want a project like this built for you?

Leave a reply

Your email address will not be published.