Page
1
V ivian A ranha Hands-On AI Development Build and Deploy Real-World AI, Machine Learning, Deep Learning, and NLP Applications Vivian Aranha THINGS YOU WILL LEARN • Set up Python for hands-on AI and machine learning projects • Use core syntax, data types, control fl ow, functions, and libraries for AI work • Clean, transform, analyze, and visualize data with NumPy, pandas, Matplotlib, and Seaborn • Apply EDA to fi nd patt erns, missing values, relationships, and features • Build prediction and classifi cation models using scikit-learn workfl ows • Understand neural network basics and practical deep learning concepts • Create an NLP sentiment analysis model from text data • Deploy a trained AI model as a web service Many beginners learn Python syntax or AI theory but struggle to build projects they can explain, demonstrate, and add to a portfolio. This book closes that gap by turning AI fundamentals into practical Python projects that move from fi rst code to working AI deployment. You will begin with Python setup and the foundations needed for AI development, including variables, data types, functions, control fl ow, and libraries. You will then use NumPy and pandas to load, clean, transform, and inspect datasets, before applying EDA with Matplotlib and Seaborn to uncover patt erns, relationships, and missing values. With these foundations in place, you will build machine learning models using scikit-learn. You will work through prediction and classifi cation workfl ows, prepare features, train models, evaluate results, and understand how choices aff ect accuracy and usefulness. The book introduces neural networks in a beginner-friendly way, showing how layers, training, and performance connect in applied AI work. You will create an NLP sentiment analysis project, turning text into features and classifying opinions. Finally, you will package a trained model as a web service used beyond a notebook. By the end, you will have a practical AI portfolio and a strong foundation for machine learning, data science, and applied AI development. www.packtpub.com H ands-O n A I D evelopm entwwwwwwwww iiiitttthhhhh PPPyyyyttthhhhhoooonn Hands-On AI Development with Python Get a free PDF of this book packtpub.com/unlock/9781808088537
Page
2
Hands-On AI Development with Python Build and Deploy Real-World AI, Machine Learning, Deep Learning, and NLP Applications Vivian Aranha
Page
3
Hands-On AI Development with Python Copyright © 2026 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Portfolio Director: Sunith Shetty Relationship Lead: Deepesh Patel Project Manager: Yash Basil Content Engineer: Mamta Wardhani Technical Editor: Shweta Amale Indexer: Manju Arasan Production Designer: Shantanu Zagade Growth Lead: Shruthi Shetty First published: September 2026 Production reference: 1170926 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul's Square Birmingham B3 1RB, UK. ISBN 978-1-80808-853-7 www.packtpub.com
Page
4
Contributors About the author Vivian Aranha is an AI educator, technology leader, and founder of School of AI, with over 20 years of industry experience. He earned a Bachelor's degree in Information Technology in 2004 and a Master's degree in Computer Science in 2006. His career spans web technologies, mobile app development for iOS and Android, blockchain solutions, and AI systems and applications. Vivian has worked with Fortune 500 organizations, including The Washington Post, Delta Air Lines, and IBM. An instructor since 2009, he has trained professionals worldwide and now teaches AI globally. His courses have attracted over 2.5 million enrollments, with more than 500,000 students learning through School of AI, Udemy, Skool, and Maven.
Page
5
About the reviewer Bala Kannaiyan is a data engineering leader and pioneer in AI and cloud modernization, with over two decades of IT experience across data management, cloud architecture, and advanced analytics. As a senior leader at a US cloud technology giant, he drives Fortune 500 and Government organizations through large-scale modernization. A Bachelor of Engineering graduate of the prestigious Anna University, he holds numerous certifications in Snowflake, Azure, Databricks, Oracle, and Scrum, has authored BPB's Snowflake SnowPro Core Certification Guide, and has reviewed Packt's Snowflake: The Ultimate Guide to Snowpark. A mentor at regional user groups and a non-profit volunteer, he expands access to education. He enjoys traveling and gardening.
Page
6
Table of Contents Preface xvii Free benefits with your book ................................................................................................. xxii Chapter 1: Python for AI and Data Science Foundations 1 Technical requirements ............................................................................................................. 2 Introduction to Python and installation .................................................................................... 3 Installing Jupyter Notebook ...................................................................................................... 6 Writing your first program in Jupyter Notebook • 7 Python basics ............................................................................................................................ 7 Variables and data types • 8 Operators • 8 Control flow • 9 If-else statements • 9 For loop • 10 While loop • 10 Functions • 11 Working with lists .................................................................................................................... 12 Working with dictionaries ....................................................................................................... 13 Introduction to NumPy ........................................................................................................... 14 Creating arrays using NumPy • 14 Array operations • 15 Matrix operations • 15 Introduction to pandas ........................................................................................................... 16 Creating a CSV file • 17 Loading and inspecting data with pandas • 18 Data manipulation in pandas • 19 Hands-on project: Basic data manipulation and file handling .................................................. 21 Introduction to exploratory data analysis ............................................................................... 22 Loading and inspecting data • 22 Inspecting data structures • 24
Page
7
Handling missing data • 25 Identifying missing data • 26 Techniques to handle missing data • 27 Data transformation and feature engineering ......................................................................... 29 Feature scaling • 29 Categorical data encoding • 30 Visualizing data with matplotlib and seaborn ........................................................................ 30 Matplotlib basics • 30 Advanced data visualization with seaborn • 34 Descriptive statistics • 35 Hands-on project: Exploratory data analysis of a real dataset ................................................. 36 Summary ................................................................................................................................ 39 Chapter 2: Machine Learning and Classification Models 41 Technical requirements ........................................................................................................... 42 Machine learning and its types ............................................................................................... 43 Supervised learning and dataset preparation .......................................................................... 43 Splitting data into training and test sets • 45 Building a linear regression model • 45 Making predictions • 46 Evaluating model performance • 46 Feature scaling and regularization .......................................................................................... 47 Hands-on project: Predicting house prices using linear regression ......................................... 48 Importing libraries • 49 Loading and inspecting the California housing dataset • 50 Perform exploratory data analysis • 51 Preparing features and target variables • 53 Creating the train-test split • 53 Training the linear regression model • 54 Making predictions and evaluating the model • 54 Visualizing actual vs. predicted values • 55 Displaying model coefficients • 56 Understanding classification models in ML ............................................................................ 57 What is classification? • 57 Logistic regression for classification • 57 Table of Contents vi
Page
8
Building a logistic regression classifier .................................................................................... 58 Evaluating the classification model • 58 Confusion matrix • 59 Accuracy • 59 Precision and recall • 59 F1 score • 60 Visualizing the decision boundary • 60 Hands-on project: Spam detection using logistic regression ................................................... 62 Importing libraries • 62 Loading and inspecting data • 63 Preparing the features and target • 63 Creating the train-test split • 63 Training the logistic regression model • 64 Making predictions • 64 Evaluating the model • 64 Visualizing the confusion matrix • 65 Summary ................................................................................................................................ 66 Chapter 3: Neural Networks and Natural Language Processing 67 Technical requirements ........................................................................................................... 68 What is a neural network? ....................................................................................................... 69 Introduction to deep learning frameworks • 70 MNIST data overview .............................................................................................................. 70 Building a simple neural network for MNIST classification ...................................................... 71 Step 1: Data preprocessing • 72 Step 2: Defining the neural network architecture • 73 Step 3: Compiling the neural network model • 74 Step 4: Training the neural network • 74 Evaluating the neural network ................................................................................................ 75 Model evaluation • 75 Making predictions • 75 Understanding activation functions: ReLU and softmax ......................................................... 75 Hands-on project: Handwritten digit classification using neural networks ............................ 78 Introduction to natural language processing ......................................................................... 80 Sentiment analysis: understanding text classification ............................................................ 81 vii Table of Contents
Page
9
Text preprocessing • 81 Tokenization • 81 Stemming and lemmatization • 81 Vectorization • 82 Using pre-trained models for NLP ........................................................................................... 83 Building a sentiment analysis model with TensorFlow ........................................................... 85 Model evaluation and confusion matrix .................................................................................. 87 Hands-on project: Sentiment analysis using pre-trained NLP models .................................... 88 Sentiment analysis with TensorFlow and the IMDB dataset • 89 Summary ............................................................................................................................... 90 Chapter 4: Deploying an AI Model as a Web Service 91 Technical requirements ........................................................................................................... 92 Installing Flask ........................................................................................................................ 93 Creating a basic Flask application ........................................................................................... 93 Creating a web interface for the model ................................................................................... 95 Building a prediction function • 96 Creating a Flask web form for input • 98 Creating the prediction route in Flask • 99 Loading the model and vectorizer • 100 Implementing the prediction logic • 100 Testing the prediction route • 101 Deploying the Flask application to Heroku ........................................................................... 102 Setting up Heroku • 102 Getting started with the Heroku CLI • 102 Preparing the application for deployment • 102 Deploying to Heroku • 103 Testing the web service and API • 105 Summary .............................................................................................................................. 107 Chapter 5: Supervised Learning and Forecasting Projects 109 Technical requirements ......................................................................................................... 109 Beginner projects ................................................................................................................... 110 Implementing a basic calculator in Python • 110 Defining arithmetic functions • 110 Table of Contents viii
Page
10
Creating the calculator function • 111 Running the calculator • 112 Building a simple chatbot using predefined responses • 113 Defining the response dictionary • 114 Matching user input to responses • 114 Running the chatbot • 115 Building a spam email detector using scikit-learn • 117 Downloading and preparing the dataset • 117 Importing libraries for spam detection • 117 Loading and splitting the dataset • 118 Training the logistic regression model • 119 Evaluating the model and visualizing results • 122 Machine learning projects ..................................................................................................... 124 Predicting house prices with linear regression • 124 Loading and preparing the data • 125 Selecting features and target • 126 Splitting the data into training and test sets • 126 Training the linear regression model • 127 Making predictions about house prices • 127 Evaluating model performance • 127 Displaying model coefficients • 127 Testing the model with new input • 128 Predicting diabetes with logistic regression • 129 Inspecting the diabetes dataset • 130 Selecting features and target variables • 131 Splitting the dataset into training and test sets • 131 Training the logistic regression model • 132 Making predictions with patient data • 132 Evaluating model performance • 132 Visualizing the confusion matrix • 133 Testing the model with a new patient record • 134 Classifying iris flower dataset using decision trees • 135 Importing libraries for decision tree classification • 135 Loading and preparing the Iris dataset • 136 Splitting features and target species • 137 ix Table of Contents
Page
11
Splitting the dataset into training and test sets • 137 Training the decision tree classifier • 137 Evaluating the model • 138 Visualizing the decision tree • 139 Predicting car prices using random forest • 140 Creating a sample car dataset • 141 Encoding categorical features • 142 Splitting the dataset into training and test sets • 144 Training and evaluating the random forest model • 144 Human activity recognition using smartphones dataset with random forest • 145 Downloading and preparing the HAR dataset • 145 Importing libraries for activity recognition • 145 Preprocessing the activity dataset • 146 Splitting the dataset into training and test sets • 147 Training the random forest classifier • 147 Making predictions on the test set • 147 Evaluating the model • 147 Visualizing the activity confusion matrix • 148 Predicting employee attrition using XGBoost • 149 Preprocessing the attrition dataset • 151 Splitting features and target variable • 152 Splitting the dataset into training and testing sets • 152 Training the XGBoost classifier • 152 Making predictions and evaluating the model • 152 Visualizing the attrition confusion matrix • 153 Predicting customer churn using logistic regression • 154 Importing libraries for churn prediction • 155 Loading and inspecting the churn dataset • 155 Preprocessing and encoding categorical features • 157 Splitting the dataset into training and test sets • 157 Scaling features and training the model • 157 Evaluating the model • 158 Detecting credit card fraud using scikit-learn • 159 Importing libraries for fraud detection • 159 Loading and preparing the fraud dataset • 160 Table of Contents x
Page
12
Splitting and scaling the dataset • 160 Initializing and training the random forest classifier • 161 Evaluating the model • 161 Disease prediction using machine learning algorithms • 163 Loading and exploring the heart disease dataset • 163 Preprocessing the heart disease dataset • 164 Splitting the dataset into training and test sets • 165 Training multiple machine learning models • 165 Model selection and evaluation • 166 Visualizing the heart disease confusion matrix • 167 Predicting heart disease risk in new patient data • 168 Forecasting and prediction projects ...................................................................................... 169 Weather forecasting using historical data • 169 Importing libraries for weather forecasting • 169 Preparing the historical weather data • 169 Selecting features and target variables • 170 Splitting the data into training and test sets • 170 Training the linear regression model • 170 Making predictions with the trained model • 171 Evaluating model performance • 171 Visualizing actual and predicted temperatures • 171 Predicting temperature for new data • 172 Predicting stock prices with linear regression • 173 Creating a sample historical stock price dataset • 173 Preparing features and target variables • 174 Splitting the dataset into training and test sets • 175 Training the linear regression model • 175 Predicting closing prices on test data • 175 Evaluating model performance • 176 Visualizing actual vs. predicted stock prices • 176 Predicting stock price for a future date • 178 Summary ............................................................................................................................... 179 Chapter 6: Vision, Language, Recommendations and AI Projects 181 Technical requirements .......................................................................................................... 181 xi Table of Contents
Page
13
Deep learning and computer vision projects ......................................................................... 182 Building an image classifier using Keras and TensorFlow • 183 Importing libraries for image classification • 183 Loading and preprocessing the MNIST dataset • 184 Constructing the CNN model • 185 Compiling the model • 186 Training the model • 187 Evaluating the model • 187 Making predictions on test images • 188 Visualizing digit predictions • 188 Classifying dogs vs. cats with a convolutional neural network • 190 Importing libraries for CNN image classification • 191 Preparing the dataset paths • 191 Defining image data generators for augmentation and rescaling • 191 Defining the validation data generator • 192 Loading training and validation data • 192 Defining the CNN model architecture • 193 Compiling the model • 194 Printing the model summary • 194 Training the CNN model • 194 Plotting training and validation accuracy and loss • 195 Making predictions on new images • 196 Interpreting the classification results • 197 Building a basic neural network from scratch with NumPy • 197 Defining activation and loss functions • 198 Initializing the neural network class • 198 Implementing the forward pass • 199 Implementing the backward pass and weight updates • 200 Implementing the training loop • 201 Training with the XOR dataset • 202 Natural language processing (NLP) projects ......................................................................... 203 Sentiment analysis on text data using NLTK • 203 Importing libraries for sentiment analysis • 204 Feature extraction for sentiment analysis • 205 Loading and preprocessing the movie reviews dataset • 205 Table of Contents xii
Page
14
Shuffling the dataset • 206 Preparing the training and testing sets • 206 Training the Naive Bayes classifier • 206 Evaluating the classifier • 206 Displaying the most informative features • 207 Defining the sentiment analysis function • 207 Testing the classifier with custom movie review sentences • 208 Frequency-based text summarization with NLTK • 209 Importing NLTK and downloading resources • 209 Defining the input text • 210 Creating the frequency-based summarization function • 210 Detecting fake product reviews using NLP techniques • 213 Importing libraries for fake review detection • 213 Loading and inspecting the reviews dataset • 214 Extracting features and splitting the dataset • 214 Vectorizing the review text with TF-IDF • 215 Training and evaluating the fake review classifier • 216 Detecting emotions in text using the Natural Language Toolkit • 217 Importing libraries for emotion detection • 217 Downloading required NLTK data • 218 Importing and initializing the sentiment analyzer • 218 Creating sample text for emotion detection • 218 Writing a function for emotion detection • 218 Detecting and printing the emotion • 220 Named entity recognition (NER) with spaCy • 220 Installing spaCy and downloading the pre-trained model • 221 Importing libraries for named entity recognition • 221 Defining the sample text and processing with spaCy • 221 Extracting named entities into a DataFrame • 222 Visualizing named entities with displaCy • 224 Saving extracted entities to a CSV file • 224 Detecting fake news using Naive Bayes • 225 Importing libraries for fake news detection • 226 Loading and inspecting the news dataset • 226 Defining features and splitting the dataset • 227 xiii Table of Contents
Page
15
Vectorizing news text with TF-IDF • 227 Training the multinomial Naive Bayes classifier • 228 Evaluating the model • 228 Building a resume scanner using keyword extraction • 229 Importing libraries for resume scanning • 229 Creating the sample resume dataset • 230 Defining the job description • 230 Vectorizing resumes and computing similarity scores • 231 Filtering and displaying matching resumes • 232 Automatic essay grading using BERT • 233 Importing libraries for essay grading • 233 Loading and exploring the dataset • 234 Confirming the selected columns • 234 Preprocessing the data • 235 Creating a custom dataset class • 235 Splitting the dataset into training and validation sets • 236 Defining the essay grading model • 237 Initializing the model, optimizer, and loss function • 237 Training the essay grading model • 237 Evaluating the essay grading model • 238 Setting up the training loop • 239 Testing the essay grading model • 239 Visualizing training and validation loss • 241 Recommendation system projects ......................................................................................... 243 Building a movie recommendation system using cosine similarity • 243 Importing libraries for movie recommendation • 243 Creating the sample movie dataset • 244 Converting the dataset to a DataFrame • 244 Defining the TF-IDF vectorizer • 244 Transforming the genre column • 245 Computing the cosine similarity matrix • 245 Defining the recommendation function • 245 Testing the recommendation system • 246 Building a book recommendation system using collaborative filtering • 247 Importing libraries for book recommendation • 247 Table of Contents xiv
Page
16
Creating a sample book ratings dataset • 247 Building the user-book matrix • 248 Computing user similarity scores • 248 Defining the book recommendation function • 249 Generating book recommendations for users • 250 Predicting movie ratings using collaborative filtering • 251 Downloading and preparing the MovieLens dataset • 251 Importing libraries for rating prediction • 252 Loading and previewing the dataset • 252 Preprocessing the dataset for the surprise library • 253 Splitting the dataset into training and test sets • 253 Building and training the SVD model • 253 Evaluating the model with RMSE • 254 Predicting a specific user and movie • 254 Visualizing the distribution of movie ratings • 254 AI and game projects ............................................................................................................. 255 Building a tic-tac-toe AI with the minimax algorithm • 255 Representing the Tic-Tac-Toe board • 256 Printing the Tic-Tac-Toe board • 256 Checking for a winner • 256 Checking if the board is full • 257 Evaluating the board for the minimax algorithm • 257 Implementing the minimax algorithm • 258 Finding the best move for the AI • 259 Implementing the main game loop • 260 Building a simple personal assistant using Python speech libraries • 263 Importing libraries for the personal assistant • 264 Initializing the speech engine • 265 Creating the speak function • 265 Taking voice commands • 265 Creating the respond function • 266 Running the assistant • 268 Starting the application • 268 Summary .............................................................................................................................. 269 xv Table of Contents
Page
17
Chapter 7: Unlock the Code Bundle and the PDF Version 271 Unlock this book's free benefits in three easy steps ............................................................... 272 Other Books You May Enjoy 276 Index 279 Table of Contents xvi
Page
18
Preface Artificial intelligence has transformed from a theoretical discipline confined to research laboratories into a practical, accessible toolkit that powers intelligent systems across industries. Python has emerged as the language of choice for AI development, offering a rich ecosystem of libraries, frameworks, and tools that democratize the creation of intelligent applications. Yet the journey from understanding AI concepts to building production-ready systems remains challenging for many developers and data scientists. This book addresses that challenge head-on. It provides a comprehensive, hands-on approach to learning practical AI development with Python, starting from foundational concepts and progressing systematically to advanced applications. The strength of this book lies in its balance between theoretical understanding and practical implementation. Each concept is introduced, explained, and immediately applied through code examples and real-world projects. Throughout this journey, you will discover that artificial intelligence is not an isolated skill, but rather a convergence of programming, mathematics, data manipulation, and software engineering practices. By mastering these interconnected skills, you will be equipped to build intelligent systems that solve real problems. Key features of this book include: Hands-on projects that reinforce learning through practical implementation, from beginner to advanced levels Real-world datasets and scenarios that mirror actual AI development challenges Step-by-step guidance through complex topics, making advanced concepts accessible Integration of multiple AI domains including machine learning, deep learning, NLP, and computer vision Production-ready deployment strategies using Flask and cloud platforms Best practices and practical patterns distilled from real-world experience In writing this book, I have drawn from years of experience building and deploying AI systems in diverse domains. The projects and examples reflect actual challenges faced during real AI development, ensuring that the knowledge you gain is immediately applicable. • • • • • •
Page
19
Who this book is for This book is designed for: Software developers seeking to integrate AI capabilities into their applications Data scientists transitioning from analysis to model building and deployment Students and self-taught practitioners beginning their journey into artificial intelligence Technical professionals and engineers looking to implement intelligent systems Teams seeking to establish AI competencies within their organizations To get the most from this book, you should have basic familiarity with Python programming (variables, functions, and control flow). While some mathematical concepts are referenced, the book emphasizes practical implementation over mathematical derivation. Prior experience with machine learning is not required; the book builds knowledge progressively. What this book covers Chapter 1, Python for AI and Data Science Foundations, covers fundamental Python constructs, data structures, and essential libraries (NumPy, Pandas, Matplotlib, Seaborn). You will learn to load, clean, and visualize data, and perform exploratory data analysis on real datasets. Chapter 2, Machine Learning and Classification Models, introduces machine learning fundamentals and covers supervised learning, regression, and classification. Hands-on projects guide you through building predictive models for house prices and spam detection, with emphasis on model evaluation techniques. Chapter 3, Neural Networks and Natural Language Processing, covers neural network architecture, backpropagation, and deep learning with TensorFlow. You will build models for image classification (MNIST) and sentiment analysis using pre-trained NLP models. Chapter 4, Deploying an AI Model as a Web Service, teaches you to deploy AI models as REST APIs using Flask and cloud platforms like Heroku, making your models accessible to end users. Chapter 5, Supervised Learning and Forecasting Projects, consolidates earlier knowledge through beginner and intermediate projects: a command-line calculator, a rule-based chatbot, and a spam email detector. Chapter 6, Vision, Language, Recommendations and AI Projects, extends to advanced projects including image classification with CNNs, natural language processing applications, recommendation systems, and AI-driven games, using frameworks like PyTorch and Hugging Face Transformers. • • • • • Preface xviii
Page
20
To get the most out of this book To benefit fully from this book, follow these recommendations: Install all required libraries in advance using the pip commands provided at the beginning of each chapter Work through code examples interactively in Jupyter Notebook or your preferred IDE, rather than passively reading Modify and experiment with code examples to deepen your understanding Complete all hands-on projects, attempting to solve problems independently before reviewing solutions Access the GitHub repository to download datasets and complete code examples Download the example code files This book includes a complete downloadable code bundle containing all the example projects and files used throughout the chapters. We recommend downloading the bundle so you can follow along smoothly and experiment with the examples. Use the bundle as a practical starting point. Modify it, extend it, and apply what you learn by creating your own variations as you progress through the chapters. Get the code bundle If you bought the book directly from Packt: Go to packtpub.com Click your profile picture and select Your Orders Find this book and click Download Code If you bought this book from Amazon or any other channel partner: Go to packtpub.com/unlock or scan the following QR code: Search for this book • • • • • 1. 2. 3. 1. 2. xix Preface