Computer Science  ·  Level 6
Artificial Intelligence Concepts
Chapter 4: Artificial Intelligence programs using python
📚 3 Topics
⚑ What you will be able to do

By the end of this chapter, you will be able to:

  • confidently use Sci-Kit Learn in Python to build and test machine learning models the right way
  • accurately implement the K-Nearest Neighbours algorithm to solve real problems
  • effectively apply the Naïve Bayes algorithm in your machine learning projects following proper steps

Mastering these skills will help you create smart, reliable AI programs that can make a real difference in today’s technology-driven world.

Artificial Intelligence (AI) has become an integral part of the Kenyan technology landscape, driving innovations in sectors such as finance, healthcare, agriculture, and public service. Proficiency in AI programming, especially using Python, equips computer science professionals with the tools to build intelligent systems that improve decision-making and automate complex tasks. This chapter explores key AI programming frameworks and algorithms, focusing on practical implementation with Python, a language widely adopted by Kenyan developers for its simplicity and extensive AI libraries.

4.1 Sci-Kit Learn

Sci-Kit Learn is a cornerstone Python library for machine learning, providing accessible tools for data mining and data analysis. Its relevance to Kenyan computer science professionals lies in its ability to simplify the development of predictive models that can be deployed in real-world applications such as fraud detection in banking or crop disease prediction in agriculture.

4.1.1 Overview of Sci-Kit Learn and Its Ecosystem

Sci-Kit Learn offers a comprehensive suite of supervised and unsupervised learning algorithms, preprocessing utilities, model selection tools, and evaluation metrics. It integrates well with other Python libraries like NumPy and Pandas, which are essential for data manipulation in Kenyan data science projects. The library's consistent API design facilitates experimentation and rapid prototyping, enabling developers to focus on refining models rather than on complex coding.

4.1.2 Key Features and Modules of Sci-Kit Learn

The library includes modules for classification, regression, clustering, dimensionality reduction, and model validation. Classification algorithms such as Support Vector Machines and Random Forests are widely used in fraud detection systems at financial institutions like Equity Bank. The pipeline module allows chaining of data transforms and estimators, which is crucial for maintaining clean and reproducible workflows in AI projects at universities and research institutions.

4.1.3 Installation and Setup in a Kenyan Development Environment

Installing Sci-Kit Learn involves using Python’s package manager pip, which is straightforward on Windows, Linux, and macOS environments common in Kenyan ICT hubs such as Nairobi and Eldoret. Setting up virtual environments ensures project dependencies do not conflict, a practice encouraged in software development firms and startups across Kenya. Integration with Jupyter notebooks supports interactive development and visualization, enhancing learning and collaboration.

4.1.4 Example Use Case: Building a Simple Classification Model

In a county hospital, machine learning can assist in diagnosing diseases based on patient data. Using Sci-Kit Learn, developers can prepare datasets, split them into training and testing sets, train a classification model such as Logistic Regression, and evaluate its accuracy. This workflow demonstrates the practical utility of Sci-Kit Learn and reinforces best practices in handling healthcare data securely and ethically.

The rest of this chapter
🔒

Create a free account to open more of this chapter.

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒4.2 Machine Learning with K-Nearest Neighbours Development Using Python

K-Nearest Neighbours (K-NN) is a fundamental machine learning algorithm valued for its simplicity and effectiveness in classification and regression problems. In Kenya, K-NN is applicable in areas such as customer segmentation in retail and credit scoring by m…

🔒4.3 Machine Learning with Naïve Bayes Algorithm

In Kenya’s growing technology sector, machine learning algorithms like Naïve Bayes play a crucial role in automating decision-making processes. Kenyan software developers working in fintech or health informatics frequently use Naïve Bayes to classify data such…

Chapter Summary

This chapter explored the implementation of artificial intelligence programs using Python, beginning with an introduction to Sci-Kit Learn as a powerful library for building machine learning models. It then examined the K-Nearest Neighbours algorithm, detailing the mathematical principles that underpin its operation and demonstrating how it can be used to make accurate predictions based on data proximity. The discussion progressed to the Naïve Bayes algorithm, where the chapter unpacked the probabilistic mathematics that support its classification capabilities. Practical methods for applying Naïve Bayes to predictive tasks were also covered, emphasizing how Python facilitates these processes. Throughout the chapter, the focus remained on understanding both the theoretical foundations and practical applications of these algorithms within Python's programming environment. This comprehensive approach equips learners with the skills necessary to develop effective AI solutions using established machine learning techniques.

Self-Assessment

🔒 PDFDownload this self-assessment, with answers

A. Written Assessment

  1. What is the primary purpose of the Sci-Kit Learn library in Python for AI development? (2 marks)
  2. Explain the role of distance metrics in the K-Nearest Neighbours algorithm. (3 marks)
🔒20 more in this section.

Chapter Examination Questions

🔒 PDFDownload these examination questions, with worked answers

SECTION A (40 Marks) - Answer ALL Questions

  1. Explain how Sci-Kit Learn simplifies the implementation of machine learning algorithms in Python for a software developer working at a Kenyan financial institution such as KCB Bank. (4 marks)
  2. Describe the key steps involved in training a K-Nearest Neighbours (K-NN) model using Python for a dataset of customer transactions. (4 marks)
🔒18 more in this section.

Chapter Practical Activities

Practical 1: Installation and Basic Usage of Sci-Kit Learn Library in Python

Computer Science · Level 6
Artificial Intelligence Concepts
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Install Sci-Kit Learn library in Python and create a script that loads a sample dataset with 100 rows and 4 features, performs a train-test split (70%-30%), trains a Logistic Regression model, makes predictions, and displays the accuracy score.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Computer with internet connectivitySample dataset CSV file
Python IDE
Python 3.8 or higher installed
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Computer with internet connectivity1 per Candidate
2Python IDE (e.g., PyCharm, VS Code, or Jupyter Notebook)1 per Candidate
3Python 3.8 or higher installed1 per Candidate
4Predefined sample dataset (CSV file with features and target variable)1 per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Setup and Basic Usage of Sci-Kit Learn
Started the Python IDE correctly
(Award 2 marks if IDE is launched without errors, else 0)
2
Installed Sci-Kit Learn library using pip or conda
(Award 5 marks if installation command executed successfully and library import works, else 0)
5
Loaded the sample dataset correctly from CSV file
(Award 5 marks if dataset is loaded into a pandas DataFrame without errors, else 0)
5
Displayed the first 5 rows of the dataset
(Award 3 marks if head() method or equivalent is used and output displayed, else 0)
3
Performed train-test split with 70% training and 30% testing data
(Award 10 marks if train_test_split is correctly implemented with specified proportions, else 0)
10
Created and trained a Logistic Regression model on training data
(Award 15 marks if model is instantiated and fit() method is called correctly, else 0)
15
Made predictions on the test data
(Award 10 marks if predict() method is used on test set without errors, else 0)
10
Calculated and displayed accuracy score of the model
(Award 10 marks if accuracy_score is computed and printed correctly, else 0)
10
Included comments explaining key steps in the code
(Award 5 marks if comments are present and meaningful, else 0)
5
Executed the program without runtime errors
(Award 5 marks if program runs from start to finish without crashing, else 0)
5
Sub-Total70
PRODUCT CHECKLIST
Script file containing code with correct implementation of all steps including installation, data loading, splitting, model training, prediction, and accuracy display
(Award 20 marks if script runs correctly and produces expected outputs matching the requirements, else 0)
20
Sub-Total20
GRAND TOTAL90
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)

Practical 2: Implement K-Nearest Neighbours Algorithm Using Python

Computer Science · Level 6
Artificial Intelligence Concepts
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Write a Python program implementing the K-Nearest Neighbours algorithm on a dataset with 2 features and a class label, classifying new data points accurately.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Computer with Python IDEDataset file (CSV format)
Python script template file
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Computer with Python IDE1 Pc per Candidate
2Python script template file1 Pc per Candidate
3Dataset file (CSV format)1 Pc per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Dataset Preparation and Display
Started the Python IDE correctly
(Award 2 marks for correct IDE startup, else 0)
2
Imported necessary libraries (numpy, pandas, matplotlib, sklearn)
(Award 3 marks if all required libraries imported, else 0)
3
Loaded the dataset correctly into a DataFrame
(Award 5 marks if DataFrame is created correctly with dataset, else 0)
5
Displayed the dataset contents on screen
(Award 5 marks for correctly displaying the dataset, else 0)
5
Sub-Total15
TASK 2: Data Visualization
Used a scatter plot to visualize the two features colored by class label
(Award 6 marks for correct scatter plot with class-based color coding, else 0)
6
Labeled the plot with appropriate title and axis labels
(Award 4 marks for clear title and axis labels, else 0)
4
Displayed the plot correctly
(Award 5 marks for displaying the plot, else 0)
5
Sub-Total15
TASK 3: K-Nearest Neighbours Implementation
Split dataset into training and testing sets (e.g. 70% train, 30% test)
(Award 10 marks for correct train-test split, else 0)
10
Created and trained KNN model using training data
(Award 15 marks for correct model instantiation and training, else 0)
15
Made predictions on the test dataset
(Award 10 marks for accurate prediction implementation, else 0)
10
Predicted the class of a new data point [feature1=5.5, feature2=3.0]
(Award 10 marks for correct prediction of the given new data point, else 0)
10
Sub-Total45
TASK 4: Results and Evaluation
Displayed the predicted results clearly on screen
(Award 5 marks for clear output display of predictions, else 0)
5
Calculated and displayed accuracy score of the model
(Award 10 marks for correct accuracy calculation and display, else 0)
10
Added a column to the DataFrame showing predicted labels and displayed it
(Award 10 marks for correctly adding and displaying predicted labels column, else 0)
10
Checked and handled any missing/null values in the dataset
(Award 5 marks for proper null value handling, else 0)
5
Sub-Total30
PRODUCT CHECKLIST
Python program runs without errors and correctly implements KNN on the dataset
(Award 20 marks if program runs error-free and meets all functional requirements, else 0)
20
Sub-Total20
GRAND TOTAL125
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)
🔒

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒K-Nearest Neighbours Distance Calculation and Classification in PythonPractical 3
🔒Predict class labels using K-Nearest Neighbours in PythonPractical 4
🔒Implement Naïve Bayes Classifier in Python for Iris DatasetPractical 5
🔒Naïve Bayes Probability Computation and Classification using PythonPractical 6
🔒Predict classification of new instances using Naïve Bayes in PythonPractical 7
🔒Implementation and Comparison of K-Nearest Neighbours and Naïve Bayes Classifiers on Iris DatasetPractical 8
🔒Data Preprocessing for Machine Learning Models using PythonPractical 9
🔒Visualize KNN and Naïve Bayes Classification Results using PythonPractical 10
Flashcards 20 cards Study deck ▾
Question
1

↻ Tap card to reveal answer
🔒

18 more in this section.

Create a free account
Test Yourself 19 questions Start quiz ▾
0%
0 / 2
🔒

17 more in this section.

Create a free account
Am I competent?

At the start of this chapter we promised you would be able to:

  • confidently use Sci-Kit Learn in Python to build and test machine learning models the right way
  • accurately implement the K-Nearest Neighbours algorithm to solve real problems
  • effectively apply the Naïve Bayes algorithm in your machine learning projects following proper steps

Tick each one you can genuinely do.

So, are you there yet?

You're competent when you can confidently do 50% or more of what this chapter promised.

Sign in to record how you're doing.