USAMA IRFAN

Senior Full-Stack & AI Engineer

Skip to main content
USAMA+IRFAN®
Back to Blog
Jun 5, 2025·17 min read

How to Build an AI-Powered Blog Post Generator in Python

How to Build an AI-Powered Blog Post Generator in Python

Introduction

Hello, fellow developers! In today's fast-paced digital world, creating high-quality content consistently can be a challenge. What if you could harness the power of artificial intelligence to automate parts of your writing workflow? In this hands-on tutorial, we'll build an AI-powered blog post generator in Python that can:

  • Fetch trending topics from developer communities (e.g., Dev.to, Reddit).

  • Generate coherent, engaging blog content using a pre-trained language model (GPT-3.5/4).

  • Customize and format the generated content (templates, code snippets, metadata).

  • Save or publish the final blog post (Markdown, HTML, or even directly to a blogging platform).

By the end of this tutorial, you’ll have a Python project that can automatically suggest a topic and spin up a first draft of a blog post—complete with titles, headings, paragraphs, and even code examples. You’ll also learn best practices around prompt engineering, simple fine-tuning strategies, and templating for blog-style outputs.


1. Prerequisites & Project Setup

Before diving into code, let’s make sure our environment and dependencies are in place.

1.1. System Requirements

  • Python 3.8+ installed on your machine.

  • A text editor or IDE (VS Code, PyCharm, Sublime Text, etc.).

  • An OpenAI API key (for the GPT-3.5/4 calls).

  • (Optional) Accounts or API keys for any target blogging platform (e.g., Dev.to, Medium, or a self-hosted blog via WordPress API).

1.2. Create a Virtual Environment

  • Open a terminal (or Command Prompt on Windows).

  • Navigate to (or create) your project folder, e.g.:

    mkdir ai_blog_generator
    cd ai_blog_generator
  • Create a virtual environment and activate it:

    # Unix / macOS python3 -m venv venv source venv/bin/activate # Windows (PowerShell) python -m venv venv .\venv\Scripts\Activate.ps1

  • Upgrade pip:

    pip install --upgrade pip

1.3. Install Required Python Packages

We’ll need several libraries:

  • requests and beautifulsoup4 for simple web scraping (fetching trending topics).

  • openai for interacting with the OpenAI API.

  • jinja2 for templating our blog post (title, metadata, structure).

  • python‐dotenv for loading environment variables (e.g., the OpenAI key).

  • (Optional) markdownify or markdown libraries if you want to convert HTML to Markdown / vice versa.

Install them via pip:

pip install requests beautifulsoup4 openai jinja2 python-dotenv markdownify


2. Retrieving Blog Post Topics

The first step is to obtain a list of trending or relevant topics automatically, so our generator isn’t working blind. We’ll demonstrate two approaches:

  • Scraping Dev.to for top “hot” tags or recent articles.

  • Using Reddit’s JSON API (e.g., /r/programming) for top posts.

Note: If a website provides an official API (like Reddit), it’s preferred. If not, simple scraping with BeautifulSoup can suffice for non-intrusive data retrieval.

2.1. Scraping Dev.to for Trending Topics

Dev.to does not require an API key for retrieving its homepage content. We can fetch the homepage, parse the HTML, and extract article titles or tags. Below is a basic example:

# file: fetch_topics.py

import requests
from bs4 import BeautifulSoup
from typing import List

DEVTO_URL = "https://dev.to/"

def get_devto_trending_titles(limit: int = 10) -> List[str]:
    """
    Fetch the trending article titles from Dev.to homepage.
    Returns up to `limit` titles.
    """
    response = requests.get(DEVTO_URL)
    response.raise_for_status()
    soup = BeautifulSoup(response.text, "html.parser")

    # Dev.to articles are listed under <h2> tags with class 'crayons-story__title'
    title_elements = soup.select("h2.crayons-story__title a")
    titles = []
    for elem in title_elements[:limit]:
        title_text = elem.get_text(strip=True)
        titles.append(title_text)
    return titles

if __name__ == "__main__":
    trending = get_devto_trending_titles(limit=5)
    print("Dev.to Trending Topics:")
    for idx, t in enumerate(trending, 1):
        print(f"{idx}. {t}")

Explanation:

  • We send a GET request to Dev.to’s homepage.

  • Use BeautifulSoup to parse the HTML.

  • Select the first few <h2 class="crayons-story__title"> elements, then extract the text from their <a> children.

  • Return a list of titles (strings).

You can run this script:

python fetch_topics.py

And you might see output like:

Dev.to Trending Topics:
1. “5 Tricks Every JavaScript Developer Should Know”
2. “Getting Started with FastAPI and Docker”
3. “Why I Switched from React to SolidJS”
4. “Build Your First TensorFlow Model from Scratch”
5. “Understanding Async/Await in Python”

We can treat these titles as seed topics for our blog generator.

2.2. Using Reddit’s API (e.g., /r/programming)

Reddit provides a JSON endpoint for each subreddit. Here’s how to grab the top 5 posts’ titles from /r/programming:

# file: fetch_reddit_topics.py

import requests
from typing import List

REDDIT_URL = "https://www.reddit.com/r/programming/top/.json?limit=5&t=day"
HEADERS = {"User-Agent": "AI-Blog-Generator/1.0"}

def get_reddit_top_titles(limit: int = 5) -> List[str]:
    """
    Fetch top post titles from /r/programming in the past day.
    """
    url = f"https://www.reddit.com/r/programming/top/.json?limit={limit}&t=day"
    response = requests.get(url, headers=HEADERS)
    response.raise_for_status()
    data = response.json()
    titles = [post["data"]["title"] for post in data["data"]["children"]]
    return titles

if __name__ == "__main__":
    top_titles = get_reddit_top_titles(limit=5)
    print("Reddit /r/programming Top Titles:")
    for idx, t in enumerate(top_titles, 1):
        print(f"{idx}. {t}")

Tip: Always set a custom User-Agent header when accessing Reddit, or your requests may be blocked. Also, it’s polite to cache results or limit frequency.

Now we have two functions (get_devto_trending_titles and get_reddit_top_titles) to generate a combined pool of topic ideas. In our main generator, we can merge them and randomly choose one—or choose by recency or popularity.


3. Generating Blog Content with OpenAI

With a topic in hand (e.g., “Build Your First TensorFlow Model from Scratch”), we’ll now leverage a GPT-3.5/4 model to produce the actual blog post content.

3.1. Setting Up OpenAI Credentials

  • Create a file named .env in your project root:

    OPENAI_API_KEY=sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

  • In code, load the API key using python-dotenv:

    # file: ai_generator.py
    
    import os
    from dotenv import load_dotenv
    import openai
    
    load_dotenv()  # loads variables from .env into the environment
    
    openai.api_key = os.getenv("OPENAI_API_KEY")
    if not openai.api_key:
        raise ValueError("OpenAI API key not found. Please set OPENAI_API_KEY in .env")

3.2. Crafting Effective Prompts

A well-designed prompt is essential for getting good results. At minimum, we want:

  • Title

  • Outline (bullet points for sections)

  • Draft Content (paragraphs under each section)

Below is a helper function that sends a prompt to OpenAI and returns the generated text. We’ll break it into two steps: (a) ask for an outline, (b) ask for content based on that outline.

# file: ai_generator.py (continued)

def generate_outline(topic: str, model: str = "gpt-3.5-turbo", max_tokens: int = 300) -> str:
    """
    Generate a detailed outline for a blog post about `topic`.
    Returns the outline as a newline-separated string.
    """
    prompt = (
        f"I want to write a detailed technical blog post about: \"{topic}\".\n\n"
        "Please provide a structured outline with at least 5 sections, "
        "including an introduction, headings Subheading 1, Subheading 2, ..., a conclusion, "
        "and any relevant code examples or resources.\n\n"
        "Use bullet points or numbered lists for the outline."
    )

    response = openai.ChatCompletion.create(
        model=model,
        messages=[{"role": "system", "content": "You are a helpful assistant for writing technical blog posts."},
                  {"role": "user", "content": prompt}],
        temperature=0.7,
        max_tokens=max_tokens,
        top_p=1.0,
        frequency_penalty=0,
        presence_penalty=0,
    )

    outline = response.choices[0].message.content.strip()
    return outline


def generate_post_from_outline(topic: str, outline: str, model: str = "gpt-3.5-turbo", max_tokens: int = 1500) -> str:
    """
    Given a `topic` and its `outline` (as a string), generate the full blog post content.
    """
    prompt = (
        f"I have this outline for a technical blog post about \"{topic}\":\n\n"
        f"{outline}\n\n"
        "Please write a complete, well-structured blog post. For each section in the outline, "
        "write one or more paragraphs explaining the concept, include code examples in markdown "
        "for any relevant code segments, and add any helpful notes or tips. "
        "Ensure the content is clear, concise, and suitable for developers with intermediate knowledge."
    )

    response = openai.ChatCompletion.create(
        model=model,
        messages=[{"role": "system", "content": "You are a skilled technical writer."},
                  {"role": "user", "content": prompt}],
        temperature=0.7,
        max_tokens=max_tokens,
        top_p=1.0,
        frequency_penalty=0,
        presence_penalty=0,
    )

    post_content = response.choices[0].message.content.strip()
    return post_content


if __name__ == "__main__":
    topic = "Build Your First TensorFlow Model from Scratch"
    outline = generate_outline(topic)
    print("=== OUTLINE ===")
    print(outline)
    print("\n=== FULL POST ===")
    blog_post = generate_post_from_outline(topic, outline)
    print(blog_post)

Notes on Parameters:

  • temperature controls creativity (0.0 = deterministic, 1.0 = more random). We set it to 0.7 for balanced creativity.

  • max_tokens needs to be high enough to accommodate the outline or post. Adjust as needed (e.g., 1500–2000 for a 1000+ word post).

By splitting outline generation and full-post generation into two steps, we gain more control and can intervene (e.g., tweak the outline manually if needed).


4. Customizing & Templating Blog Posts

Once we have raw content (title, outline, paragraphs, code snippets), we typically want to wrap it in a neat template with:

  • A title at the top

  • Metadata (author, date, tags)

  • A Table of Contents (TOC) (optional)

  • Code blocks styled in Markdown

  • Footnotes or resource links

We can leverage Jinja2 templating to create a reusable blog post template for Markdown or HTML.

4.1. Designing a Jinja2 Template (Markdown)

Create a templates directory in the project root. Inside, add blog_template.md.jinja:

---
title: "{{ title }}"
date: {{ date }}
author: "{{ author }}"
tags: [{{ tags|join(", ") }}]
---

{% if summary %}
> {{ summary }}
{% endif %}

{# Optional Table of Contents #}
## Table of Contents
{% for section in sections %}
- [{{ section.heading }}](#{{ section.anchor }})
{% endfor %}

---

{# Main Content #}
{% for section in sections %}
## {{ section.heading }}
{{ section.content }}

{% endfor %}

Explanation of Template Variables:

  • title: The blog post’s title.

  • date: Publication date (e.g., "2025-06-06").

  • author: Author name (e.g., "Usama Irfan").

  • tags: A list of tags (e.g., ["Python", "AI", "NLP"]).

  • summary: A short blurb or summary (optional).

  • sections: A list of sections, each having:

    • heading: Section heading text (e.g., “Introduction”, “Step 1: ...”).

    • anchor: A URL-friendly anchor (e.g., “introduction”, “step-1-…”).

    • content: Markdown content for that section (including paragraphs, code fences, lists).

4.2. Rendering the Template in Python

We need a function that takes our generated content (which we might parse into sections) and renders it via Jinja2:

# file: render_template.py

import os
import datetime
from jinja2 import Environment, FileSystemLoader
from typing import List, Dict

# Ensure this script runs from the project root
TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), "templates")

env = Environment(loader=FileSystemLoader(TEMPLATE_DIR))

def slugify_heading(heading: str) -> str:
    """
    Convert a heading string into a Markdown anchor slug.
    E.g., "Step 1: Setup & Installation" -> "step-1-setup-installation"
    """
    slug = heading.strip().lower()
    # Remove characters other than letters, numbers, spaces, hyphens
    import re
    slug = re.sub(r"[^a-z0-9\s-]", "", slug)
    slug = re.sub(r"\s+", "-", slug)
    return slug

def render_blog_post(title: str,
                     author: str,
                     tags: List[str],
                     sections_raw: List[Dict[str, str]],
                     summary: str = "") -> str:
    """
    Render the final Markdown for a blog post.
    sections_raw: List of dicts with keys "heading" and "content" (unstructured text).
    This function will auto-generate an anchor for each section.
    """
    sections = []
    for sec in sections_raw:
        anchor = slugify_heading(sec["heading"])
        sections.append({
            "heading": sec["heading"],
            "anchor": anchor,
            "content": sec["content"].strip(),
        })

    template = env.get_template("blog_template.md.jinja")
    date_str = datetime.datetime.now().strftime('"%Y-%m-%d"')

    rendered = template.render(
        title=title,
        date=date_str,
        author=author,
        tags=tags,
        summary=summary,
        sections=sections,
    )
    return rendered

if __name__ == "__main__":
    # Example usage
    sample_sections = [
        {
            "heading": "Introduction",
            "content": "AI is transforming how we write..."},
        {
            "heading": "Step 1: Setup",
            "content": "First, install Python 3.8+ and create a virtual environment..."},
        {
            "heading": "Conclusion",
            "content": "With this setup, you now have a scalable AI blog generator..."},
    ]
    output_md = render_blog_post(
        title="How to Build an AI-Powered Blog Post Generator in Python",
        author="Usama Irfan",
        tags=["Python", "AI", "NLP", "Blogging"],
        sections_raw=sample_sections,
        summary="In this post, we’ll learn how to automatically generate blog content using OpenAI’s GPT models and Python.",
    )
    print(output_md)

When you run python render_template.py, you should see a complete Markdown blog post printed, with frontmatter and sections.


5. Putting It All Together: Main Script

Now let’s unify our steps into a single main.py that:

  • Fetches trending topics (using Dev.to and/or Reddit).

  • Picks one topic at random (or by most upvotes/interest).

  • Generates an outline for that topic via OpenAI.

  • Generates the full post based on the outline.

  • Parses the generated text into sections (split by Markdown headings).

  • Renders the final Markdown via Jinja2.

  • Saves the Markdown file locally (e.g., in a /posts directory).

Below is a simplified but complete example. In practice, you might add error handling, logging, caching, etc.

# file: main.py

import os
import random
import re
from datetime import datetime

from fetch_topics import get_devto_trending_titles, get_reddit_top_titles  # from our earlier scripts
from ai_generator import generate_outline, generate_post_from_outline
from render_template import render_blog_post

# Ensure the "posts" directory exists
os.makedirs("posts", exist_ok=True)

def pick_topic() -> str:
    """
    Fetch trending topics from Dev.to and Reddit, combine them, and pick one at random.
    """
    devto_titles = get_devto_trending_titles(limit=5)
    reddit_titles = get_reddit_top_titles(limit=5)
    combined = devto_titles + reddit_titles
    # Remove duplicates (case-insensitive)
    unique = list({title.lower(): title for title in combined}.values())
    chosen = random.choice(unique)
    return chosen

def split_into_sections(full_post: str) -> list[dict]:
    """
    Given a full Markdown blog post (as a string), split it into sections.
    Each section starts with a level-2 heading: "## ".
    Return a list of dicts: { "heading": str, "content": str }.
    """
    lines = full_post.splitlines()
    sections = []
    current_heading = None
    current_content_lines = []

    heading_pattern = re.compile(r"^##\s+(.*)")

    for line in lines:
        match = heading_pattern.match(line)
        if match:
            # If a previous section exists, save it
            if current_heading:
                sections.append({
                    "heading": current_heading,
                    "content": "\n".join(current_content_lines).strip()
                })
            current_heading = match.group(1).strip()
            current_content_lines = []
        else:
            if current_heading:
                current_content_lines.append(line)
            # If there's text before any "##", you can choose where to put it
    # Save the final section
    if current_heading and current_content_lines:
        sections.append({
            "heading": current_heading,
            "content": "\n".join(current_content_lines).strip()
        })
    return sections

def main():
    print("Fetching trending topics...")
    topic = pick_topic()
    print(f"Selected Topic: {topic}\n")

    print("Generating outline...")
    outline = generate_outline(topic)
    print("Outline generated:\n", outline, "\n")

    print("Generating full blog post...")
    full_post_md = generate_post_from_outline(topic, outline)
    # For debugging, you might want to save the raw post to a file:
    # with open("raw_generated_post.md", "w", encoding="utf-8") as f:
    #     f.write(full_post_md)

    print("Parsing sections from generated post...")
    sections_raw = split_into_sections(full_post_md)

    # (Optional) You could prompt the user to review/edit the outline or sections_raw before continuing.

    print("Rendering final Markdown via template...")
    today_str = datetime.now().strftime("%Y-%m-%d")
    tags = [tag.strip().lower() for tag in topic.split() if len(tag) > 3][:5]  # naive tag extraction
    # e.g., ["build", "your", "first", "tensorflow", "model"] → cleaned/simplified tags
    rendered_md = render_blog_post(
        title=topic,
        author="Usama Irfan",
        tags=tags,
        sections_raw=sections_raw,
        summary=f"A step-by-step guide to {topic.lower()}."
    )

    # Save to file, e.g. posts/2025-06-06-title-slug.md
    filename_slug = re.sub(r"[^a-z0-9\-]+", "", topic.lower().replace(" ", "-"))
    filename = f"posts/{today_str}-{filename_slug}.md"
    with open(filename, "w", encoding="utf-8") as f:
        f.write(rendered_md)

    print(f"Blog post saved to {filename}")

if __name__ == "__main__":
    main()

Key Points:

  • pick_topic() combines our two topic sources and picks one randomly (you can customize selection criteria).

  • split_into_sections() looks for Markdown level-2 headings (## ) to break up the generated content. This ensures our Jinja2 template can place each section appropriately.

  • We generate a naive list of tags by splitting the topic into words longer than 3 characters—feel free to replace with a more robust tag-extraction or sentiment analysis pipeline.

  • The final Markdown is saved under posts/YYYY-MM-DD-topic-slug.md. You can then push these files to a GitHub-backed blog (e.g., Jekyll, Hugo) or convert to HTML and publish.


6. (Optional) Publishing Directly to a Platform

If you want to automatically publish your generated post, consider integrating with a platform’s API:

  • Dev.to API:

    • You need a Dev.to API key (found in your account settings).

    • You can make a POST request to https://dev.to/api/articles with a JSON payload like:

      {
        "article": {
          "title": "Your Post Title",
          "published": true,
          "body_markdown": "Full Markdown content here...",
          "tags": ["python", "ai", "nlp"],
          "series": "AI Blog Generator",
          "main_image": "https://example.com/cover.jpg"
        }
      }

    Example in Python (add to main.py or a separate script):

    import os
    import requests
    
    DEVTO_API_KEY = os.getenv("DEVTO_API_KEY")
    
    def publish_to_devto(title: str, body_markdown: str, tags: list[str]):
        url = "https://dev.to/api/articles"
        headers = {
            "Content-Type": "application/json",
            "api-key": DEVTO_API_KEY
        }
        payload = {
            "article": {
                "title": title,
                "body_markdown": body_markdown,
                "published": True,
                "tags": tags
            }
        }
        resp = requests.post(url, json=payload, headers=headers)
        resp.raise_for_status()
        return resp.json()
    
    # In main():
    #   ...
    #   devto_response = publish_to_devto(topic, rendered_md, tags)
    #   print("Published to Dev.to! URL:", devto_response["url"])
  • Medium API:

    • You need to register an application to get a token.

    • Use the OAuth2 token to POST to https://api.medium.com/v1/users/{{userId}}/posts.

    • Payload example:

      {
        "title": "Your Post Title",
        "contentFormat": "markdown",
        "content": "Full Markdown content here...",
        "canonicalUrl": "https://yourblog.com/...",
        "publishStatus": "public",
        "tags": ["python", "ai", "nlp"]
      }

In both cases, ensure you’ve added DEVTO_API_KEY or MEDIUM_TOKEN to your .env file, then load it via dotenv.


7. (Advanced) Fine-Tuning & Customization

7.1. Fine-Tuning With Your Own Dataset

For absolute control over writing style, you can fine-tune an OpenAI GPT-3.5/4 model on a custom corpus of your past blog posts or preferred technical writing. This involves:

  • Preparing a dataset in JSONL format, where each example has:

    • prompt: e.g., "Topic: How to deploy a Flask app".

    • completion: e.g., "Here’s an introduction...\n## Step 1: ...\n".

  • Uploading the dataset via OpenAI CLI:

    openai tools fine_tunes.prepare_data -f my_blog_posts.jsonl
    openai api fine_tunes.create -t <PREPARED_FILE_ID> -m gpt-3.5-turbo
  • Once fine-tuning completes, you’ll have a model ID like ft-<timestamp>. Then modify your generation calls:

    fine_tuned_model = "ft-abc123" response = openai.ChatCompletion.create( model=fine_tuned_model, messages=[...], ... )

Note: Fine-tuning can be more expensive and takes longer to train. If you’re just starting, prompt engineering (step-wise outline + generation) is often sufficient.

7.2. Prompt Engineering Tips

  • Be explicit in your user messages: e.g., “Write a 1200-word introduction to X, including code examples and performance tips.”

  • Use system messages to set the writing style:

    messages = [
        {"role": "system", "content": "You are a seasoned software engineer and technical writer. Use clear, concise language, include code snippets in markdown format, and speak to developers with intermediate experience."},
        {"role": "user", "content": <your prompt>},
    ]
  • Iterate: If the generated content is too shallow, request “Expand Section 2 with more details on performance implications.”


8. Troubleshooting & Best Practices

  • Rate Limits & Quotas: Monitor token usage in your OpenAI dashboard. If you hit rate limits, consider increasing the timeout parameter or batching requests.

  • Error Handling: Always wrap openai.ChatCompletion.create(...) in try/except. Handle openai.error.RateLimitError, openai.error.APIConnectionError, and requests.exceptions.HTTPError for web scraping or publishing.

  • Content Validation: Before publishing, you may want to run a simple “sanity check” to ensure no disallowed content or hallucinated facts. For example, search for “XYZ library version 99.0” to catch nonsense.

  • Logging: Log each step (topic selected, outline received, completion length, final filename, publish response). This helps debug and measure ROI.


9. Example Output

Below is a truncated sample of what a generated blog post might look like (rendered Markdown).

--- title: "Build Your First TensorFlow Model from Scratch" date: "2025-06-06" author: "Usama Irfan" tags: [tensorflow, python, ai, deep-learning] --- > In this guide, we’ll walk through building and training a simple TensorFlow model from scratch, exploring data preparation, model architecture, training loops, and evaluation. ## Table of Contents - [Introduction](#introduction) - [Prerequisites](#prerequisites) - [Step 1: Install Dependencies](#step-1-install-dependencies) - [Step 2: Prepare the Dataset](#step-2-prepare-the-dataset) - [Step 3: Define the Model Architecture](#step-3-define-the-model-architecture) - [Step 4: Train the Model](#step-4-train-the-model) - [Step 5: Evaluate and Visualize Results](#step-5-evaluate-and-visualize-results) - [Conclusion](#conclusion) --- ## Introduction TensorFlow is one of the most popular deep learning frameworks. In this tutorial, we’ll build a simple neural network from scratch to classify handwritten digits in the MNIST dataset. By the end, you’ll understand how to: - Load and preprocess data - Define a sequential model - Train with `model.fit(...)` - Evaluate accuracy and loss ## Prerequisites - Python 3.8+ - Basic knowledge of Python, NumPy, and machine learning concepts - Familiarity with command-line interface (CLI) ## Step 1: Install Dependencies First, create a virtual environment: python3 -m venv venv source venv/bin/activate pip install tensorflow matplotlib

We’ll use:

  • TensorFlow 2.x for model building

  • Matplotlib for plotting training curves

Step 2: Prepare the Dataset

TensorFlow provides the MNIST dataset out of the box:

import tensorflow as tf

# Load MNIST data
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()

# Normalize pixel values to [0, 1]
train_images = train_images.astype("float32") / 255.0
test_images = test_images.astype("float32") / 255.0

# Reshape to (28, 28, 1) for convolutional layers (if desired)
# train_images = train_images[..., tf.newaxis]
# test_images = test_images[..., tf.newaxis]

Step 3: Define the Model Architecture

We’ll create a simple Sequential model:

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Flatten, Dense

model = Sequential([
    Flatten(input_shape=(28, 28)),       # Flatten 28x28 images into vectors
    Dense(128, activation="relu"),       # Hidden layer with 128 neurons
    Dense(10, activation="softmax")      # Output layer for 10 classes
])

model.compile(
    optimizer="adam",
    loss="sparse_categorical_crossentropy",
    metrics=["accuracy"]
)

model.summary()

Model Summary

Model: "sequential"

Layer (type)

Output Shape

Param #

flatten (Flatten)

(None, 784)

0

dense (Dense)

(None, 128)

100480

dense_1 (Dense)

(None, 10)

1290

Total params: 101,770 Trainable params: 101,770 Non-trainable params: 0

Step 4: Train the Model

Now let’s train for 5 epochs and store training history:

history = model.fit(
    train_images,
    train_labels,
    epochs=5,
    validation_split=0.1,
    batch_size=32
)

We can visualize training and validation accuracy/loss:

import matplotlib.pyplot as plt

plt.figure()
plt.plot(history.history["accuracy"], label="train_acc")
plt.plot(history.history["val_accuracy"], label="val_acc")
plt.title("Model Accuracy")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend()
plt.show()

Step 5: Evaluate and Visualize Results

Evaluate on the test set:

test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"Test accuracy: {test_acc:.4f}")

Display a few predictions:

import numpy as np

predictions = model.predict(test_images)
for i in range(5):
    pred_label = np.argmax(predictions[i])
    true_label = test_labels[i]
    print(f"Image {i}: Predicted={pred_label}, True={true_label}")

Add confusion matrix (optional) with scikit-learn if you want deeper insights.

Conclusion

Congratulations! You’ve built and trained a neural network in TensorFlow from scratch. Key takeaways:

  • Data Preprocessing: Normalize pixel values, reshape as needed.

  • Model Architecture: Simple dense layers can achieve ~98% accuracy on MNIST.

  • Training Loop: Use model.fit(...) with validation split to monitor overfitting.

  • Evaluation: Always evaluate on a hold-out test set and visualize results.

From here, you can:

  • Experiment with convolutional layers (Conv2D) for better accuracy.

  • Try different optimizers or learning rates.

  • Expand to other datasets (CIFAR-10, Fashion-MNIST).

Feel free to modify this generator template to tackle your own topics (e.g., “Deploying a Flask API on AWS Lambda” or “A Deep Dive into BERT for NLP”). Happy coding, and keep exploring the intersection of AI and content creation!


10. Additional Resources & Inspiration

Throughout this post, you’ve seen how AI can assist in content creation. For more inspiration, check out these community projects:

  • Generating PDF from a React Application by Luke O’Codes

  • Artificially Generating Music by Sriram Kakarala

  • Building an AI Writer in Hours by Sandeep Balachandran

  • AI Booster Project overview by Xeracon

  • Convert Image to Pencil Sketch in 10 Lines (Python) by Biplab Mishra

Feel free to explore, remix, and share your improvements. The AI landscape is evolving every day, and your next innovative blog post might just be a single script away!


About the Author Usama Irfan is a software engineer passionate about AI/ML, Azure AI integrations, and full-stack development. When not coding, you’ll find him hitting the gym, reading up on the latest Azure certifications, or planning his next freelance gig. Stay connected on LinkedIn and check out his GitHub for more AI-powered projects.

Stay curious, keep coding, and let your creativity soar!