AI and ML - II

Page 1

AI and ML - II

NEP 2020
Digital
aligned
coding platform included

COMPUTER SCIENCE

AI and ML - II

What is Intelligence?

Decision Making

Introducing AI, ML and DL

Domains of AI

Applications of AI

AI Ethics

AI Project Cycle Framework

AI Project: Problem Scoping and Goal Setting

Features of Python

Applications of Python

Python Basics

Variables

Creating a Variable

Rules of Naming a Variable

Case Styles in Python

Assignment Operator

Assignment Statement

Data Types

Type Casting

Mathematical Tools in Python

The Random Module

Arithmetic Operators

BEMDAS Rule

Decision Making

Comparison Operators

iii Contents 1 Artificial Intelligence 1
Data Exploration Modelling Evaluation Scenario-based Problems 2 Introduction to Python 21
Data Acquisition
iv Logical Operators Loops The while Loop The for versus while Loop Nested Loop The Break and Continue Statements Python Packages 3 Data Science with Python 69 Data Science Revisit AI Project Cycle Python for Data Science Case Study Statistical Learning and Data Visualisation K-Nearest Neighbour Model - Personality Prediction 4 Computer Vision 79 Computer Vision Digital Images OpenCV - Image Processing 5 Natural Language Processing 87 Natural Language Processing (NLP) Chatbots
Study
Language vs Computer Language
Processing
of Words
Language Toolkit
Case
Human
Data
Bag
Natural

Chapter 1

Artificial Intelligence

What is Intelligence?

Being intelligent means being good at learning, problem-solving, thinking, remembering, communicating, and making good choices. It also involves being creative, managing emotions well, and being a good friend to others.

Here are some examples of how smart people use their intelligence in different ways:

The ability to learn, recognise problems, and solve them is Intelligence

● Problem-solving: A person with high intelligence can solve complex problems efficiently and effectively. For example, an engineer might use their intelligence to develop innovative solutions to technical problems.

● Creativity: People with high intelligence tend to be creative and can come up with unique ideas and solutions. An artist, for instance, may use their intelligence to create thought-provoking pieces of art that challenge viewers’ perspectives.

● Innovative: People with very high intelligence can invent new things in different areas. For example, a scientist uses his intelligence to innovate new things that will help human beings in their life.

According to Howard Gardner, humans have nine types of intelligence: Visual-Spatial, Verbal-Linguistic, Logical-Mathematical, Bodily-Kinesthetic, Musical Intelligence, Interpersonal, Existential, Intra-personal, and Naturalistic Intelligence.

1

Decision Making

Decision making is the process of selecting the best option among several alternatives. It is a crucial life skill that enables an individual to make informed choices and take responsible actions.

The decision-making process involves several steps, including:

● Identify the problem or decision to be made: The first step in decision making is to identify the problem or decision to be made. It is essential to define the problem clearly and understand what needs to be accomplished.

● Gather information: Once the problem is identified, the next step is to gather information related to the problem. This includes collecting relevant data, opinions, and feedback from others.

● Evaluate the options: After gathering information, evaluate the options available to you. Consider the pros and cons of each option and how they align with your goals and values.

● Make a decision: Based on the evaluation of options, make a decision. It is essential to weigh the consequences of each option and choose the best alternative.

● Take action: After making a decision, take action. This involves implementing the decision and putting it into action.

● Evaluate the decision: Finally, evaluate the decision and its outcomes. Reflect on what worked well and what didn’t work and what you can learn from it.

To summarise, decision making is a crucial life skill that involves identifying a problem or decision, gathering information, evaluating options, making a decision, taking action, and evaluating the decision’s outcomes. It is a skill that can be developed and honed over time with practice.

For example, a student can analyse their past exam results and study habits to decide how to improve their grades and get into their preferred college.

2 AI and ML - II

AI (Artificial Intelligence) is a branch of computer science that deals with the study of the principles, concepts, and technology for building machines that enable them to think, act, and learn like humans. Machines possessing AI should be able to mimic human traits, i.e., make decisions, predict the future, learn, and improve on its own.

According to McCarthy, “AI is the science and engineering of making intelligent machines.”

Machine Learning is a subset of artificial intelligence that enables machines to improve at a task with experience (data). It enables a computer system to learn from experience using the provided data and making accurate algorithms for predictions/decisions.

Deep Learning is a subset of machine learning in which a machine is trained with vast amounts of data which help it to train itself around the data. Deep learning utilises both structured and unstructured data for training. Practical examples of deep learning are virtual assistants, vision for driverless cars, detection of money laundering, face recognition, and many more. Deep learning is an AI function that mimics the working of the human brain in processing data for use in detecting objects, recognising speech, translating languages, and making decisions.

Deep learning is the most advanced form of artificial intelligence of these three. Then comes machine learning which is intermediately intelligent and

Introducing AI, ML and DL
3 Chapter 1 • Artificial Intelligence

artificial intelligence covers all the concepts and algorithms which in some way or other mimic human intelligence.

Time to Think

How do you think Artificial Intelligence can help you as you go about your daily life?

Example: Smart home appliances, like a smart refrigerator, utilise advanced technology to automatically adjust and optimise their cooling features based on the external temperature.

Fill in your ideas below:

Artificial Intelligence

Find Out

Before moving ahead, let’s fill in the KWLH chart below to find out what you know about Artificial Intelligence.

A KWLH chart is a type of graphic organiser used to organise our thoughts and knowledge about a particular topic. KWLH stands for “Know, Want to know, Learned, How to learn”.

4 AI and ML - II

What do you know about AI?

What do you want to know about AI?

What have you learned about AI?

How have you learned this about AI?

Domains of AI

To make a machine artificially intelligent, we need to provide it with specific training in the form of datasets. The type of data used to train the AI model determines its classification into one of three domains.

Let’s explore these domains and their interrelationships.

5 Chapter 1 • Artificial Intelligence

● Data: Data is a collection of raw facts that can be transformed into useful information. It can be in the form of numbers, words, symbols, or images. An AI system requires a large and continuous stream of data to function properly, with the amount of data correlating with the system’s effectiveness. An AI system is capable of not only processing but also analysing data, identifying patterns and trends based on its programmed objectives. For example, if Disney Hotstar’s AI system aims to predict viewer numbers for a particular program, the more data available on that program, the more accurate the prediction will be. Higher viewer numbers provide more variables for analysis, leading to more accurate predictions. Therefore, the more data an AI system has, the more accurate its predictions can be.

● Computer Vision: Computer vision is a branch of artificial intelligence that allows computers and systems to extract useful information from digital images, videos, and other visual inputs, and then make decisions or provide suggestions based on that information. While AI enables computers to think, computer vision enables them to see, interpret, and comprehend. Some examples of computer vision in action include Google Lens, self-driving cars, and facial recognition locks on smartphones.

● Natural Language Processing: Natural Language Processing (NLP) is an area of artificial intelligence that involves the communication between computers and humans using natural language. This includes speech recognition, audio-to-text conversion, text-to-audio conversation, and audio data processing. Popular examples of NLP applications include Google Assistant, Cortana, Siri, Alexa, and Google Translate.

NLP has two main focuses: syntax and semantics of the language.

Integrating data, computer vision, and NLP can result in highly efficient and beneficial applications. Data in the form of visuals is beneficial for computer vision, while data in the form of speech, audio, and music can help with NLP. When data is available in audio-visual form, both computer vision and NLP can be utilised for maximum benefit.

Impact of Artificial Intelligence on Sustainable Development Goals (SDG)

In recent years, we have been warned about potential job loss and domination by robots due to artificial intelligence. However, we can also see the positive

6 AI and ML - II

impact of AI in achieving sustainability and meeting the UN’s sustainable development goals to improve our world. AI has the potential to contribute significantly to a circular economy and promote sustainable living.

AI can support the achievement of 128 targets out of 169 targets across all SDGs, but it may also inhibit 58 targets. AI enables new technology that improves efficiency and productivity, but it may also lead to increased inequalities among and within countries.

AI-based technology can directly impact these goals, as AI can be trained to reduce the work of humans and boost the world economy. It can also provide the solution for innovation in industry as it can perform daily tasks more efficiently. AI can indirectly impact some SDGs, such as, AI will produce

7 Chapter 1 • Artificial Intelligence

new forms of employment for people, providing them with salaries and ending poverty. AI can provide more accurate data on the places affected by hunger, floods, drought, etc., which can be used to help the people there. Also, AI is a high-yield technology which means it can give a huge production without taking much consumption.

Applications of AI

We may have not noticed yet, but we are surrounded by machines that work on AI. They are becoming a crucial part of our everyday life and provide us with the ease of having most tasks at the touch of a button or by the simple use of a sensor.

● Education and Training

Support of AI in 21st century classrooms has brought about tremendous transformation in the education system. Predicting performance, designing curriculums, smart assessment, helping teachers in corrections, identifying students who need more help, remote teaching-learning, educational research, developing projects, virtual reality based training, 3D learning environments are a few examples of the applications in this field. Thinkster Math, Brainly, Content Technologies, Inc. (CTI), Gradescope, Duolingo are some of the examples of educational applications that harness the power of AI to improve learning in students of all ages. ChatGPT is a boon in the field of education nowadays.

8 AI and ML - II

● Customer Support Systems

Various businesses, schools, banks, and public services, deploy extra customer support systems in the form of people, computers, equipment, and response systems. AI revolutionises customer support and response systems using natural languages processing and smart-search capabilities using chatbots. AI enabled support systems for example, Google Assistant, Amazon Alexa, etc., public addressing, and alert systems guide people in case of emergency. These key applications are used for better customer experience, improved public relations, and are useful for those who are physically challenged, with faster and more accurate guidance, etc.

● Product-Oriented Businesses

Some popular AI applications in product-driven businesses are:

■ Autonomous vehicles like driverless cars, autonomous drones to deliver pizza or medicine.

■ Smart-home devices like smart refrigerator, smartTV, smart AC, etc.

■ Smart homes and cities with AI-enabled traffic control systems, smart route search, smart citizen safety systems, disaster prevention, maintaining inner temperature, etc.

■ Robots: AI-driven autonomous intelligent robots in public areas, homes, schools, restaurants, hospitals, etc., to enhance public assistance.

● E-Commerce and Retail Businesses

Amazon, Walmart, Flipkart, Alibaba, and all popular online E-Commerce platforms have already been using and have invested heavily in AI to take

Hi How can i help you 9 Chapter 1 • Artificial Intelligence

their businesses to new heights and to enhance customer experience. They use AI for digital marketing, customer relations, product delivery, service tracking and product cataloguing, financials, logistics, human resources and advertisements, new product design, etc.

● News and Entertainment

Entertainment, gaming, and media industries use AI to improve and develop content in multiple languages easily. The major applications of the industry could be movie production, automatic multilingual subtitles, editing and recording, marketing and promotion, targeted advertisement insertions, news compilation and organisation, etc. Many news websites use AI to make their platform more intelligent in response, maintain user privacy, prevent security lapses and to analyse trends that help them come up with new ideas to enhance and grow their business.

● Public Services

There are many government and public services such as public transport that use AI systems to enhance traffic control, minimise congestion, enhance security, routing of vehicles, etc. Healthcare uses it for smart ambulances, data analytics for prevention of disease outbreaks, sampling and research, etc. Demographic trends can be traced by predicting demographic data. AI can help in addressing many social issues like poverty, hunger, unemployment, education, etc., efficiently. Environmental data analytics help to achieve enhanced living conditions in rural areas, prevention of damage to the environment, improvement of environmental care, etc., in an efficient way.

10 AI and ML - II

● Electronics Industry

The electronics industry uses silicon chips for their devices. In today’s era AI-based chips are in use that connect objects (things) to the Internet which functions in a much better way like door locks with a password or smart heating by Google, Siri, Alexa, cars with better safety features, etc. These objects are known as the Internet of Things (IoT). Robotics is the primary emerging field in this industry.

Research and Development

AI has tremendous potential to impact research and development in all fields such as public health, automobiles, environment and ecology, life sciences, education, defence, social crises like poverty, hunger, crime, etc. All the domains of AI help greatly in research and development, especially in data because AI systems are capable of continuously processing bulk input data very fast and generate useful patterns and predictions equivalent to the human brain.

The other applications of AI that we use in our daily lives include Chatbot, for example. Google Assistant, Siri, and Alexa, and Social Media apps like Facebook, Twitter, Instagram, use AI to customise what you see on your feeds. This includes Google Search, Speech Recognition, Biometrics, Online Shopping, Banking, and Transportation like self-driven cars, etc.

AI Ethics

Ethics is a set of moral principles that help us distinguish between right and wrong. AI ethics, on the other hand, is a set of guidelines that advise on the design and outcomes of artificial intelligence.

11 Chapter 1 • Artificial Intelligence

Artificial intelligence is fast, vast, and has a significant impact on industries and society. Like anything fast, vast, and powerful, it has the potential to cause both benefit and harm. When the outcome or predictions of AI cause benefit, it is considered good AI; if it causes harm, it is considered unethical AI.

The principles for ethically aligned AI design are as follows:

1. Human Rights: AI systems should respect, promote, and protect human rights.

2. Well-being: AI developers should prioritise human well-being when designing AI systems.

3. Data Rights: People should have control over their own data, and individual identities should be protected.

4. Effectiveness: AI systems should be robust and not vulnerable to hacking or crashing.

5. Transparency: AI systems’ processing and decision-making processes should be transparent and open to investigation.

6. Accountability: AI systems should be governed by rational guidelines that hold developers and users accountable for their actions.

7. Misuse Awareness: Provisions should be in place to prevent AI systems from being misused.

8. Competence: AI developers should possess the necessary knowledge and skills to develop effective AI systems.

AI Project Cycle Framework

The AI project cycle provides us with an appropriate framework which can lead us towards the goal.

The stages involved in the AI project cycle are as follows:

1. Problem Scoping: This is the initial stage that defines the goals to be achieved and helps understand the problems that need to be addressed with the help of an AI system.

12 AI and ML - II

2. Data Acquisition: Acquiring and compiling the relevant data that will be used to train the AI system.

3. Data Exploration: Exploring and interpreting the acquired data to derive useful information from it and then organising it uniformly in a proper format and layout for better understanding.

4. Modelling: Using and presenting the data to various AI systems in such a way that they perform predictions that meet the goals set in problem scoping.

5. Evaluation: Evaluating and analysing the predictions of AI systems and then deciding on the best-suited AI system to be deployed.

AI Project: Problem Scoping and Goal Setting

Problem scoping is the initial stage in an AI project cycle where the goals to be achieved and the problems to be addressed with the help of an AI system are defined. It involves investigating and analysing the business processes or scenarios where AI can be implemented to solve problems, and compiling data from various sources such as interviews and documents.

The goal is to identify the key elements related to the problem and use the 4Ws framework (Who, What, Where, and Why) to define the scope of the problem that the AI system will address.

Who is affected by the problem you want to solve with AI?

Identify the people or groups of people who are affected by the problem. For example, if you are trying to solve a traffic problem, you might ask, “Who is affected by the traffic problem?”

What is causing the problem you want to solve with AI?

Identify what the problem is and what is causing it. For example, if you are trying to solve a traffic problem, you might ask, “What is causing the traffic problem?”

Where is the problem happening that you want to solve with AI?

Identify where the problem is happening. For example, if you are trying to solve a traffic problem, you might ask, “Where is the traffic problem happening?”

13 Chapter 1 • Artificial Intelligence

Why is it important to solve the problem with AI?

Identify and understand why the problem is important to solve. Identify the benefits of solving the problem. For example, if you are trying to solve a traffic problem, you might ask, “Why is it important to solve the traffic problem?”

Data Acquisition

Data acquisition is the process of collecting and organising relevant information that is used to train an AI system. There are two aspects to this: data sources and data acquisition processes.

● Data Sources refers to where the information comes from. Depending on the problem being solved, data could come from various sources, such as a company’s database, customer feedback, business documents, website content, live data, raw or flat files, and software applications.

● Data Acquisition processes refer to the methods used to collect and organise the data. For well-organised data such as tables and spreadsheets, queries can be applied to generate datasets. Some software applications allow for data to be exported in various formats. However, more effort and sophisticated methods are needed for unorganised data such as images, audio, and video. Other methods to acquire data include online surveys, feedback and review forms, live data via webcams and sensors, web scraping, and scanning symbols like barcodes and QR codes.

Data Exploration

When we gather data from various sources, we cannot use it right away to train AI algorithms. We need to explore the data to clean it up and make it useful. This is done in the third stage of the AI project cycle, called Data Exploration. Data exploration helps us understand the data and determine if it is suitable for training AI algorithms. Structured data is easier to explore and refine, but

14 AI and ML - II

unstructured data requires more expertise. Sometimes, the data we collect may have missing values. To prevent bias in AI systems after training, we need to treat these missing values. We can either remove the records or analyse the data to predict or estimate the missing values.

Data exploration also leads to data visualisation, where we can identify patterns, trends, and relationships among the data values. After exploration, techniques like Data wrangling, munging, or scrubbing can be used to convert raw and unstructured data into structured data suitable for training and testing AI models.

Find Out

What visual representations of data are you aware of? Draw and name them in the spaces given below.

Visual Representations Of Data

Bar Chart

15 Chapter 1 • Artificial Intelligence

Modelling

At the previous stage, we dealt with datasets represented in various forms that cannot be understood by machines. To enable machines to work with this data, the relationship between the parameters needs to be mathematically described. AI models fall into two broad categories:

1. Rule-based Approach: This approach is best suited for systems that operate in a restricted application area and require a set of rules to follow to accomplish a task. The rules are coded in the system as if-else-elseif branches, which help the computer in making decisions. Rule-based machines do not gain learning experience as the intelligence of these machines is only simulated and defined by humans.

2. Learning-based Approach: This approach addresses the limitations of the rule-based approach by feeding data to the machine to find possible patterns and trends to make predictions. It is often referred to as black boxes as it is not entirely clear how these systems take decisions.

There are various AI models used in various scenarios, including decision trees, regression, bagging, random forests, and neural networks.

Evaluation

After completing the modelling stage, the next step is the evaluation stage where the trained model undergoes rigorous testing to determine its efficiency and performance. This is done by testing the model with specific data and calculating certain parameters such as accuracy, precision, recall, and F1 score.

Points to Remember

● Artificial Intelligence (AI) refers to the ability of machines to think and learn.

● AI is an interdisciplinary field that aims to create intelligent machines.

● There are three main domains of AI: data, computer vision, and natural language processing.

16 AI and ML - II

● AI is widely used in daily life through applications like Google Assistant and Alexa.

● AI ethics provides guidelines for designing and implementing ethical AI systems.

● The AI project cycle consists of five stages: problem scoping, data acquisition, data exploration, modelling, and evaluation.

Scenario-based Problems

Activity 1: During Smeera’s trip to Mumbai, she encountered a man who had seven sisters. Each of these sisters owned seven sacks, and within each sack, there were seven kittens. How many individuals, including Smeera, are travelling to Mumbai in this scenario?

Activity 2: Amit, currently in Grade 10, must choose a stream (Medical / Commerce / Humanities) before advancing to Grade 11 in the next session. To make an informed decision, he needs to weigh the benefits of each option. Given his interests in biology, painting, and technology, help him choose the most suitable option by answering the following questions:

● What are the available streams?

● What are the advantages of each stream?

● How do Amit’s interests and skills align with each option?

● Based on his interests and potential, which stream would be the best fit for Amit?

17 Chapter 1 • Artificial Intelligence

Practice Questions

A. Tick the Correct Option

1. is necessary to make decisions.

Information

Intelligence

Both a and b

Programming

2. According to , AI is the science and engineering of making intelligent machines.

John McCarthy Howard Gardner

Charles Babbage

3. is a way of achieving AI.

Machine Learning

Decision Making

None of these

Both a and b

None of these

4. is a set of guidelines that advise on design and outcomes of AI.

Programs

Intelligence

Ethics

Information

5. Data Acquisition is the stage of the AI Project Cycle.

Second

Fourth Third Fifth

B. Find the Truth

1. There are four stages of the AI Project Cycle.

2. There are 17 Sustainable Development goals.

3. Modelling is the second stage of the AI Project Cycle.

4. 4Ws in problem scoping are what, why, when, and where.

5. Google assistant, Alexa, and Siri are examples of applications of AI.

18 AI and ML - II

C. Very-Short-Answer Questions

1. Define intelligence.

2. How does decision making help us? Explain with an example.

3. How is intelligence related to learning?

4. Name two applications of AI that you use in your daily life.

5. Is a desktop computer artificially intelligent? Give reason to justify your answer.

D. Short-Answer Questions

1. Define artificial intelligence with an example.

2. How are human intelligence and artificial intelligence different from each other?

3. Explain machine learning and deep learning.

4. Describe the impact of AI on Sustainable Development Goals.

5. Name any four types of intelligence according to Howard Gardner.

E. Long-Answer Questions

1. Explain the AI Project Cycle.

2. List the names of three domains of AI and explain any two of them.

Mini Project

Visit the link: https://sdgs.un.org/goals and prepare a chart on your findings and learning.

19 Chapter 1 • Artificial Intelligence

Introduction to Python

Guido van Rossum developed Python at the National Research Institute for Mathematics and Computer Science in the Netherlands in the 1990s.

Python is a high-level, interpreted, interactive, object-oriented programming language. It is the easiest of the existing programming languages and super reliable.

Python is not named after a real Python, but rather after Guido’s favourite comedy show, Monty Python’s Flying Circus.

Features of Python

1. Easy to Read: Python code is easy to read, just like English.

2. Quick to Learn: Python has few keywords, a simple structure, and a clearly defined syntax. This makes learning Python easy and quick.

3. Easy to Maintain: Python’s source code is fairly easy to maintain.

4. Interactive Execution Mode: Python offers script and interactive modes for running programmes. The code can be interactively tested and debugged in the interactive mode.

A three-step loop process defines how Python is run in the interactive window:

● The Python interpreter first reads the code entered at the prompt.

● Then it evaluates the code.

● Finally, it prints the outcome and awaits new input.

Chapter 2
21

5. Dynamic Typing: Python defines data type dynamically for the objects according to the value assigned. Also, it supports dynamic data type checking.

6. Portable: Python is a portable language because it can be used on a variety of hardware platforms.

7. Rich Standard Library: Python has a rich, portable and cross-platform standard library.

8. Large Database Support: Python provides interfaces to all major commercial databases.

9. GUI Application Creation: Python also supports the creation of GUI applications.

10. Scalable: Python provides better structure and support for larger programs than shell scripting. This makes it scalable.

Applications of Python

Python is a versatile programming language that can be used for a wide range of applications, including:

1. Web Development: Python is used extensively in web development for building dynamic websites and web applications using popular web frameworks like Django and Flask.

2. Data Science: Python has become one of the most popular programming languages for data science and machine learning, with libraries like Pandas, Numpy, Matplotlib, and Scikit-learn being used for data analysis, visualisation, and machine learning.

3. Artificial Intelligence and Machine Learning: Python is widely used in developing AI and machine learning applications due to its easy-to-learn syntax and availability of powerful libraries like TensorFlow, Keras, and PyTorch.

The acronym REPL stands for read-evaluate-print loop.
22 AI and ML - II

4. Scientific Computing: Python is a popular choice for scientific computing due to its ability to handle complex numerical calculations and data analyses using libraries like SciPy, NumPy, and Pandas.

5. Desktop Applications: Python can be used for developing desktop applications with the help of GUI frameworks like PyQt and Tkinter.

6. Game Development: Python is used in game development with popular libraries like Pygame and PyOpenGL.

7. Networking and Cybersecurity: Python can be used for developing network automation and security tools using libraries like Paramiko, Nmap, and Scapy.

8. Automation and Scripting: Python is a great language for automating tasks and writing scripts due to its simple syntax and availability of libraries like Selenium and Beautiful Soup.

Overall, Python’s versatility, ease of use, and large community support make it an excellent choice for a wide range of applications.

Python Basics

Execution of a Python Code

The Python interpreter runs the code line by line and displays the results until an error occurs. It changes the HLL-written source code into bytecode, an intermediate language, which is then converted back into machine language and executed.

23 Chapter 2 • Introduction to Python

Syntax

Every language has its own set of rules for writing. All programming languages also have rules for writing programs in them. These rules are called syntaxes.

Python also has some rules that we need to follow while writing a program.

One of Python’s rules is that it is a case-sensitive language, which means that num, Num, and nUm all refer to different things.

Syntax Error

Syntax errors are mistakes in following the rules to write the code, such as wrong function name, missing quotes, brackets, etc.

Below are two examples of common syntax errors:

1. Missed double quotes

print(Learn Python)

SyntaxError: invalid syntax

2. Missed symbols, such as a colon, comma, or brackets

print(Learn Python

The print() Statement

SyntaxError: invalid syntax

The print() statement displays a value or information in the output.

Syntax: print(“value”)

Code OUTPUT Code OUTPUT
24 AI and ML - II

print(“Hello kitty!”)

print(25)

We can also print multiple elements in a single print statement by separating them with a comma. While printing them, each element in the output is separated by white spaces.

Syntax: print(“box1”,”box2”)

print(“Hello”,”everyone!”)

print(“You”,”are”,”welcome!”)

The sep And end Parameter

The sep and end are optional parameters in the print function in Python.

By default, the print function has whitespace as a separator between words and ends with a newline.

With sep parameter you can replace whitespace with your choice of separator to separate words and with end parameter you can add a symbol or value at the end of the statement.

Syntax: print(“box1”, “box2”, sep= “symbol”, end=”symbol”)

Code OUTPUT Code OUTPUT Code OUTPUT Code OUTPUT
Hello kitty! 25 Hello everyone! You are welcome!
25 Chapter 2 • Introduction to Python

print(“I am fine”,”well”,”alright”,”tired”, sep = “/”) print(“What are you reading”, end=”?”)

Solved Example

Write a program to print the following:

180-455-2020

1*2*3*4*5*6*7 =7! 10*20*30=6000

Answer

1. print(‘180’,’455’,’2020’,sep=’-’)

2. print(1,2,3,4,5,6,7,sep=’*’,end=’=7!’)

3. print(10,20,30,sep=’*’,end=’ = ‘) print(10*20*30)

Variables

I am fine/well/alright/ tired

What are you reading?

Code OUTPUT Code OUTPUT
5 num 26 AI and ML - II
A variable is a memory location on a computer which can hold any value and can also change over time as needed.

To understand it in an easy way, think of it like a box in which you can store a number and later you can replace that number with another number.

In simple words, variables are names given to the memory location where your value is stored. The figure below illustrates three variables with their respective values. The three variables used in the figure are “name”, “winner” and “score”. The variable “name” holds the value “Bob”, the variable “winner” holds the value “True”, and the variable “score” holds the value “35”.

Therefore, whenever the variable “name” is used in the program, it refers directly to its value, “Bob”.

Creating a Variable

In Python, variable declaration and initialisation happens with a single step of assigning a value to a variable.

Syntax: variable_name = value

1. word = “Hi” 2. number = 5 3. print(word,number)

Code OUTPUT
hi 5
Value
num 27 Chapter 2 • Introduction to Python
Variable
Variable Name

We can also initialise multiple variables in one line.

Syntax: var1, var2 = value1, value2

1. word, number = “hi”, 5

2. print(word,number)

Note: If we change the value of a variable and use it again, the old value is replaced with the new value.

Rules of Naming a Variable

There are certain rules we need to follow while naming a variable.

Some rules are:

1. The name of a variable should be meaningful.

2. Only the underscore ( _ ) symbol can be used while naming variables.

3. A variable name must start with a letter or the underscore character.

1. greeting_message = “Good Evening!”

2. _number_ = 205

3. print(greeting_message)

4. print(_number_)

1. greeting%message = “Good day!”

2. print(greeting%message)

Good Evening!

SyntaxError: cannot assign to operator

4. As Python is a case-sensitive language, variable names are also case-sensitive.

Example: old, Old and OLD are three different variables.

Code OUTPUT Code OUTPUT Code OUTPUT
hi 5
205
28 AI and ML - II

1. num = 25

2. Num = 30

3. NUM = 45

4. print(num)

5. print(Num)

6. print(NUM)

5. A variable name can have numbers within but cannot begin with a number

1. num_1 = 430

2. _num2 = 250

3. print(num_1)

4. print(_num2)

1. 1num = 100

2. print(1num)

Case Styles in Python

As we have case styles for words in English, we have some case styles for naming variables. Below are the case styles you can follow to name variables in Python:

first word lowercase Capitalise All Following Words

A variable name can be written in camel case if it contains two or more distinct words. In camel case, we write the name of the variable as the first word in lowercase and all subsequent words with the first letter capitalised without a space in between.

. Code OUTPUT Code OUTPUT Code OUTPUT
25 30 45 430 250 SyntaxError:
syntax
invalid
1. Camel Case
29 Chapter 2 • Introduction to Python
camel Case

Example: “Name of the company” can be written as “nameOfTheCompany”.

As this represents the camel’s hump, we call it Camel-Case.

1. camelCaseExample = “Hello Camel”

Snake-case is the practice of writing in which each space is replaced by an underscore ( _ ) character and the first letter of each word written in lowercase.

Example: “Name of the company” in snake-case is written as “name_ of_the_company”.

1. snake_case_example = “Hello Python”

Comments

snake_case

underscore (lower_snake)

It is always a good practice to document your work. In programming, we also document our projects to keep them organised and easily understandable by other programmers.

We use comments to add documentation to a Python program. Python ignores these lines of comments in the program during execution as they are not part of the code.

Code OUTPUT Code OUTPUT
2. print(camelCaseExample) 2. print(snake_case_example) Hello Camel Hello Python 2. Snake Case
30 AI and ML - II

Benefits of Using Comments

Comments help:

● structure the code and make it easier for humans to read.

● explain the thought process and intentions behind the code.

● find errors and debug the code.

● reuse the code in other applications as well.

After all, there is a popular saying, “Anyone can write code that a computer can understand. Good programmers write code that humans can understand.” In Python, we have two types of comments:

● Single-line Comment

● Multi-line Comment

Single-Line Comment

A single-line comment starts with a hash character ( # ) and is followed by related information.

1. #using the print command

2. print(“Learn Programming”)

3.

4. greeting = “Learn” #defining the greeting

5. name = “Python” #defining the name

6. print(greeting, name)

Multi-line Comment

Learn Programming Learn Python

A multi-line comment begins and ends with three single or double-quote characters (‘ ‘ ‘ or “ “ ‘) with related information enclosed.

Code OUTPUT
31 Chapter 2 • Introduction to Python

1. ‘‘‘

2. This is an example of

3. Multiline comments

4. ‘’’

5. “””

6. Printing hello world with sep command

7. Printing hello world with end command

8. “””

9. print(“learn”, “coding”, sep = “#”)

10. print(“Monty”, “Python”, end = “$”)

Solved Examples

Example 2.1

The side of a square is 80. Use the formula to find the area of a square and print the result. Use camel case for naming the variable.

Answer

side = 80 areaOfSquare = side * side print(“The area is: ”, areaOfSquare)

Example 2.2

The area is: 6400

Below are the average temperatures of different places and store them in different variables. The temperature has increased by 0.5 in the afternoon and displays the updated temperature of all the places in the same format shown below.

Code OUTPUT
OUTPUT
Code
learn#coding Monty$Python
32 AI and ML - II

OUTPUT

Place Temperature

Zo Hills 20

Met Town 25

Bay Area 26

Answer

Code

Zo_Hills=20

Met_Town=25

Bay_Area=26

print(“Place”,”Temperature”)

print(“Zo Hills”, Zo_Hills+1)

print(“Met_Town”,Met_Town+1)

print(“Bay_Area”,Bay_Area+1)

Assignment Operator

The ‘=’ operator is known as assignment operator, also read as ‘is set to’. It assigns the value on the right-hand side of the “=” symbol to the variable on the left-hand side.

“=” in Math vs “=” in Python

There is a difference between the “=” we use in Maths and the one we use in Python.

In mathematics, = means to equate the left-hand side with the right-hand side. It is the sign of equality.

In python, = symbol is used to set the value of the left-hand side variable to the right-hand side variable.

33 Chapter 2 • Introduction to
Python

Syntax: variable = value

# the value is stored in the variable variable = variable + value

# value is added to existing variable value and stored in the variable

1. count = 15

2. count = count + 5

3. # new value of count is set to old value of count + 5

4.

5. print(count)

Assignment Statement

A line of the program that tells Python to assign a value to a variable is called an assignment statement. The variable on the left of “=” holds/stores the value on the right.

Syntax: variable_name=value

1. name=”Rashi”

2. roll_no=28

3. print(name)

4. print(roll_no)

Solved Examples

Example 3.1

Classify the following into either Animal or Tree, and then print all the Animal variables in the first line and Plant variables in the second line.

Code OUTPUT Code OUTPUT
20 Rashi 28
34 AI and ML - II

“Cat, Banyan, Monkey, Lion, Teak, Neem”

OUTPUT

Animals - Cat, Monkey, Lion

Trees - Banyan, Teak, Neem

Answer

Code

animal_1,animal_2,animal_3 = “Cat”,”Monkey”,”Lion”

tree_1,tree_2,tree_3=”Banyan”,”Teak”,”Neem”

print(“Animals -”, animal_1,animal_2,animal_3)

print(“Trees -”, tree_1,tree_2,tree_3)

Example 3.2

A fruit shop sells 32 apples, 33 bananas, 20 strawberries, and 15 oranges. Print the percentage of fruits sold that were apples or oranges.

OUTPUT

Total fruit sold =100 47% of fruits sold were apples or oranges.

Hint:

Store the number of fruit sold in variables. Print the total number of fruits sold.

Find the percentage using the formula (apples+oranges)/total*100

35 Chapter 2 • Introduction to Python

Answer

Code

apple=32

banana=33

strawberry=20

orange=15

total_sold=apple+banana+strawberry+orange percent_apple_orange_sold=apple+orange/ total_sold*100

print(‘Total fruit sold =’,total_sold)

Data Types

Data types define what type of data a variable, a named memory location, can hold.

The default data types in Python are as follows:

String (str) Stores words and characters in a variable. “Hello”,”World”

Boolean (bool) Stores two values: True and False in a variable True and False

The type() Function

The type() function returns the data type of the value held by the variable.

Syntax: type(variable_name)

Data Type Description Example Integer (int) Stores non-decimal numbers in a variable. 5, -8, 43, 54685, -5612965 Float (float) Stores decimal point numbers in a variable. 6.8, -3.2
36 AI and ML - II

number_ = 5

word_ = “Hi”

print(type(number_))

print(type(word_))

Type Casting

<class ‘int’>

<class ‘str’>

Type casting refers to converting the data type of a variable into another.

Type Casting to Integer

The int() function is used to typecast the value of a variable into an integer.

It converts the following data type into an integer:

1. Float by removing the decimal point and everything after it.

2. String only if string represents a number.

3. Boolean by converting True to 1 and False to 0.

Syntax: int(variable_name)

1. str_to_int = int(“8”)

2. bool_to_int = int(True)

3. print(str_to_int, type(str_to_int))

4. print(bool_to_int, type(bool_to_int))

8 <class ‘int’>

1 <class ‘int’>

1. number=int(“Python”)

ValueError: invalid literal for int() with base 10: ‘Python’

Code OUTPUT Code OUTPUT Code OUTPUT
37 Chapter 2 • Introduction to Python

Type Casting to Float

The float() function is used to typecast the value of a variable into a float. It converts the following data type into float:

1. Integer by adding a decimal followed by a zero.

2. String only if the string represents a float or an integer.

Syntax: float(variable_name)

1. num=float(65)

2. flat_no=float(“101”)

3. print(num)

4. print(flat_no)

1. str=float(“Learn”)

2. print(str)

Type Casting to String

ValueError: could not convert string to float: ‘Learn’

The str() function is used to typecast the value of a variable into a string. It converts all the data types including float, integer, boolean into a string.

Syntax: str(variable_name)

1. num1 = str(25)

2. num2 = str(17.2)

3. print(num1, type(num1))

4. print(num2, type(num2))

25 <class ‘str’>

17.2 <class ‘str’>

Code OUTPUT Code OUTPUT Code OUTPUT
65.0 101
38 AI and ML - II

Type Casting to Boolean

The bool() function is used to typecast the value of a variable into boolean. It converts the following data type into boolean:

1. Integer and prints False if the value of the variable is 0, otherwise prints True

2. String and prints False if the string is empty, otherwise prints True.

Syntax: bool(variable_name)

1. a=bool(0)

2. b=bool(1)

3. c=bool(“”)

4. d=bool(“Programming”)

5. print(a,b,c,d)

Difference between String and Boolean

Strings are written by enclosing a set of characters within a pair of single or double quotes.

Strings are a series of characters that form words and sentences.

A boolean variable can take only one of the two boolean values represented by the words True or False without quotes.

Booleans are either 0 or 1. They are used to categorise something in either True or False, which also implies a Yes or a No.

Mathematical Tools in Python

Maths Library

The Python Math Library provides common math functions that can be used for complex mathematical computations. The Math library contains functions such as ceil, floor, factorial, etc.

Code OUTPUT
False True False True
String Boolean
39 Chapter 2 • Introduction to Python

We need to import the math library into our program before we can use the functions.

Here is how we import the library

Syntax: import math

Here are a few useful mathematical functions used in daily computations.

The ceil() function

The ceil comes from the word ceiling. As the name suggests ceil() function rounds UP the number to the nearest integer (i.e., the smallest integer greater than or equal to that number) and returns the value.

Syntax: ceil(value)

The floor() function

As the name suggests, the floor() function rounds a number DOWN to the nearest integer (i.e., the largest integer not greater than the number) and returns the value.

Syntax: floor(value)

1. import math

2. number = 1.666666666666667

3. ceil_ = math.ceil(number)

4. floor_ = math.floor(number)

5. print(“Number rounded UP to ceil is:”,ceil_)

6. print(“Number rounded DOWN to floor is:”,floor_)

The round() function

Number rounded UP to ceil is: 2

Number rounded DOWN to floor is: 1

The round() function returns a float value by rounding off the number to the decimal place that we give as input. The function takes in two values, the

Code OUTPUT
40 AI and ML - II

number we want to round off and the decimal places we want to round to (i.e., the number of digits after the decimal point).

The default number of decimals is 0, i.e. the function will return the nearest integer.

Syntax: round(float_value,digits_after_decimalpoint)

The Random Module

Python’s Random module is an in-built module of Python which is used to generate random numbers. The random module contains functions like random(), randint() etc.

The random() function

The random() function generates random floating numbers between 0 and 1.

Syntax: random.random()

The randint() function

The randint() function returns an integer number within the specified range. The specified range from which we want the integer is given as input in the function.

Syntax: random.randint(start,end)

Code OUTPUT Code OUTPUT
1. import random 2. print(random.random())
0.776878688688 6.99 7
1. print(round(6.98867267267,2)) 2. print(round(6.99999))
41 Chapter 2 • Introduction to
Python

1. import random

2. print(random.randint(3,50))

Solved Examples

Example 5.1

Prepare your report card:

Store your name and marks in 5 subjects in different variables, and calculate the percentage of your marks.

Now, display the following data as well.

1. Percentage of marks scored in 5 subjects.

2. Round-up the percentage using ceil function.

3. Round-down the percentage using the floor function.

4. Round the percentage to 3 decimal places. OUTPUT

Name of the student: John

Percentage of the student: 79.4 %

Percentage after using ceil(): 80 %

Percentage after using floor(): 79 %

Percentage after using round(): 79.4 %

Answer Code

1. import math

2. name=”John” #you can write any name

3. marks1=94

Code OUTPUT
25
42 AI and ML - II

4. marks2=84

5. marks3=92

6. marks4=58

7. marks5=69

8.

9. percentage=(marks1+marks2+marks3+marks4+marks5)*100/500

10.

11. print(“Name of the student:”, name)

12. print(“Percentage of the student:”,percentage,”%”)

13. print(“Percentage after using ceil():”,math. ceil(percentage),”%”)

14. print(“Percentage after using floor():”,math. floor(percentage),”%”)

15. print(“Percentage after using round():”,round(percentage,3),”%”)

Arithmetic Operators

Arithmetic operators in Python are used along with the integer or float values to perform mathematical operations on them.

There are 7 arithmetic operators in Python:

Operator Name Description Example Result + Addition Adds two values together 4+2 6 - Subtraction Subtracts one value from
7-5 2 * Multiplication Multiplies two values 5*2 10 / Division Divides one value by another 7/2 3.5 % Modulus Returns the division remainder 5%2 1 ** Exponent Returns exponent of a number 3**2 9 // Floor Division Returns floor value of the division 7//2 3
another
43 Chapter 2 • Introduction to Python

BEMDAS Rule

Whenever there is a mathematical expression in Python, it solves it in the following sequence:

1. Brackets (B)

2. Exponents (E)

3. Multiplication (M)

4. Division (D)

5. Addition (A)

6. Subtraction (S)

Python solves the mathematical expression in the order above from left to right of their occurrence.

But, whenever multiple exponent operators are used in an expression, Python solves the exponent part from right to left.

Example 9 + 7 * (8 - 4) / 2 - 3**2

= 9 + 7 * 4 / 2 - 3**2

= 9 + 7 * 4 / 2 - 9

= 9 + 28 / 2 - 9

= 9 + 14 - 9

= 23 - 9

= 14

Solved Examples

Example 6.1

(First, the brackets are solved.)

(Then, Exponent is solved.)

(Then, multiplication is solved.)

(Then, division is solved.)

(Then, addition is solved.)

(Finally, subtraction is solved.)

As a programmer, write a program to help Dave with the right answers to the questions given below using operators in Python.

44 AI and ML - II

a = 23 b = 13

a. Addition of a and b.

b. Multiplication of a and b.

c. Division of a and b.

d. Base a to the power b.

e. Modulus of a/b

OUTPUT

Addition of a and b is: 36

Multiplication of a and b is: 299

a divided by b is: 1.7692307692307692

Base a to the power b is: 504036361936467383

Remainder, when a is divided by b, is: 10

Answer Code

1. a,b=23,13

2. print(“Addition of a and b is:”,a+b)

3. print(“Multiplication of a and b is:”,a*b)

4. print(“a divided by b is:”,a/b)

5. print(“Base a to the power b is:”,a**b)

6. print(“Remainder, when a is divided by b, is:”,a%b)

Decision Making

Decision making, as the name suggests, is making decisions based on certain conditions. To write these conditions we need to use comparison and logical operators.

45 Chapter 2 • Introduction to Python

Comparison Operators

Comparison operators compare the value on the left-hand side with the value on the right-hand side and return either True or False as a result of the comparison.

These operators are also known as relational operators.

Below are the six comparison operators in Python.

Operator Name

Purpose Example

== Equal to Returns True if both operands are equal x==y

!= Not Equal to Returns True if operands are not equal x!=y

> Greater than Returns True if left operand is greater than the right x>y

< Less than Returns True if left operand is less than the right x<y

>= Greater than or equal to Returns True if left operand is greater than or equal to the right x>=y

<= Less than or equal to Returns True if left operand is less than or equal to the right x<=y

# Using the equality operator print(2==2.0)

print(3==5)

# Using the inequality operator print(3!=5)

print(2!=2)

# Using the greater than operator print(1>3)

print(10>8)

# Using the less than operator print(10<12) print(10<9)

Code OUTPUT
True False True False False True True False True False True False 46 AI and ML - II

# Using the greater than or equal to operator

print(16>=16)

print(14>=15)

# Using the less than or equal to operator

print(16<=18)

print(15<=10)

Solved Examples

Johnny has to check whether the number of balls in box A is equal to, less than or greater than the number of balls in box B. Box A contains 453 balls and box B contains 454 balls. Using conditional statements, print whether the situations are True or False.

OUTPUT

Are the balls in box A equal to the balls in box B? False

Are the balls in box A less than the balls in box B?

Are the balls in box A greater than the balls in box B?

Answer

box_A=453

box_B=454

cond1=box_A==box_B

print(“Are the balls in box A equal to the balls in box B?\n”,cond1)

cond2=box_A<box_B

print(“Are the balls in box A less than the balls in box B?\n”,cond2)

cond3=box_A>box_B

print(“Are the balls in box A greater than the balls in box B?\n”,cond3)

Example 1.1
True
False
Code
47 Chapter 2 • Introduction to Python

Example 1.2

Joe’s mother gives him Rs. 350 and asks him to get some groceries from a nearby shop. He plans to buy tomatoes for Rs. 50, onions for Rs. 60, and a jar of Peanut Butter for Rs. 100.

a. With the help of a conditional statement, print True or False to help him find out if the money he has will be enough to buy the planned items or not.

b. Joe plans to buy 2 more jars of Peanut butter with the remaining money. Help him decide if he has enough money for doing so.

OUTPUT

The total amount of money with Joe is: 350

The total bill will be: 210 Is the money adequate to buy groceries?

The remaining amount left with Joe is: 140 Can Joe buy 2 more jars of Peanut butter?

Answer

price_tomato=50

price_onion=60

price_butter=100

total_money=350

print(“The total money with Joe is: “,total_ money)

total_bill=price_tomato+price_onion+price_ butter

print(“The total bill will be: “,total_bill)

cond=total_money>total_bill

print(“Is the money adequate to buy groceries?\n”,cond)

remaining_money = total_money - total_bill

print(“The remaining amount left with Joe is: “,remaining_money)

cond2=remaining_money>(price_butter*2)

print(“Can Joe buy 2 more jars of Peanut butter?\n”,cond2)

True
Code
False
48 AI and ML - II

Logical Operators

Logical operators are used to compare two or more conditions. These conditions can be formed using the comparison operators. We get a boolean value (True or False) as output after comparing these conditions.

The logical operators include “and” and “or”.

The and Operator

The and operator compares two conditional statements and returns True only if BOTH are true, else returns False in all other cases.

Syntax: Statement1 and Statement2

The following is the truth table for the AND operator:

The or Operator

The or operator compares two conditional statements and returns True if any one of the statements is true. It returns False if both conditional statements are false.

Syntax: Statement1 or Statement2

Condition_1 Condition_2 Condition_1 and Condition_2 TRUE TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE Code OUTPUT print(4<9 and 10==10) print(8>3 and 10==12) True False
49 Chapter 2 • Introduction to Python

print(7+5>8 or 12!=8)

print(12>17 or 12==5.0)

Multiple and/or Operators

We can form complex conditional statements in Python using multiple and/or operators. In such cases where we have multiple and/or conditional statements, and has precedence over or. (i.e. the conditions with and are solved first and then the conditions with or are solved)

Syntax:

Statement1 or Statement2 and Statement3

#First we solve the AND operator, and then the OR

print(4>7 or 5==5 and 7>5)

4 > 7 or 5 == 5 and 7 > 5 False

Condition_1 Condition_2 Condition_1 or Condition_2 TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE Code OUTPUT Code OUTPUT
and True
or True True True False True #Solve and first #Solve or
or True
False
50 AI and ML - II

Solved Examples

Example 2.1

David needs to select students for his upcoming project based on two criteria. The students should have 60% in their academics, and they should have a score of 7 in their analytical tests.

Now, Ray has a score of 65% in his academics and 8.5 in analytical tests. Joe has a score of 55% in his academics and 8 in analytical tests. So display True or False based on the condition each for Ray and Joe whether they pass David’s criteria or not.

OUTPUT

Ray’s scores:

Academics: 65%

Analytical test: 8.5

Does Ray meet David’s criteria? True

Joe’s scores:

Academics: 55%

Analytical test: 8

Does Ray meet David’s criteria?

ray_academics=65

ray_analytical=8.5

print(f”Ray’s scores:\nAcademics: {ray_academics}%\

nAnalytical test: {ray_analytical}”)

ray_condition = ray_academics>=60 and ray_analytical>=7

print(“Does Ray meet David’s criteria?\n”,ray_condition)

joe_academics=55

joe_analytical=8

print(f”Joe’s scores:\nAcademics: {joe_academics}%\

nAnalytical test: {joe_analytical}”)

joe_condition = joe_academics>=60 and joe_analytical>=7

print(“Does Ray meet David’s criteria?\n”,joe_condition)

False Answer Code
51 Chapter 2 • Introduction to Python

Ben is the captain of the school’s football team. He needs defensive players who are tall and strong and offensive wingers who are short and agile.

For defence, he needs players taller than 6 feet and with a weight of more than 68 kg.

For offence, he needs players shorter than 5.5 feet and with a weight of less than 57 kg.

Take your height and weight as float inputs, and with the help of Comparison and Logical operators, print True or False for the combined condition.

OUTPUT

Enter your height in feet: 5

Enter your weight in Kg: 55

Do you qualify for the football team according to any of Ben’s criteria?

Answer

Code

height=float(input(“Enter your height in feet: “))

weight=float(input(“Enter your weight in Kg: “))

condition = (height>6 and weight>68) or (height<5.5 and weight<57)

print(“Do you qualify for the football time according to any of Ben’s criteria?\n “,condition)

Loops

While programming, we will often come across situations where we need to use a piece of code over and over again. However, writing the same line of code multiple times does not make sense. This is where loops come in handy.

True
Example 2.2 52 AI and ML - II

Loops help us repeat a set of instructions again and again until a particular condition remains True. As soon as the condition becomes False, the loop stops.

Process of a Loop

Python provides mainly two types of loops, the while loop and the for loop. But the steps remain loosely the same as below.

A looping process has mainly 4 steps:

1. Creating a condition variable and storing an initial value in it

2. Providing a test condition that runs the loop (This should be carefully stated in order to run the loop for a desired number of times)

3. A set of instructions inside the loop

4. Updating the value of the condition variable

Infinite Loop

In some cases, the body of the loop gets executed over and over as the test condition never becomes false, and the execution never stops. Such a loop is called an Infinite loop.

The while Loop

The simplest looping statement is the while statement. It allows a programmer to repeat a set of instructions when the condition is evaluated as True, hence it is also known as a conditional loop.

53 Chapter 2 • Introduction to Python

It verifies the condition before executing the loop. The code inside the while loop is repeated as long as the given condition remains True.

A while loop can be written using:

a. The while keyword

b. A condition which is either True or False

c. A block of code, which is nothing but the set of instructions that is supposed to be repeated

Syntax: while condition:

Statement 1

Statement 2 ... … (Incrementing the value if required)

Proper indentation needs to be provided for the block of code present inside the while loop. It is also called the body of the loop.

count = 1

while count < 6:

Code OUTPUT
print(count) count += 1 1 2 3 4 5 54 AI and ML - II

Explanation

Here, count is the condition variable, which starts with 1, and when Python checks the condition (count < 6), it comes out to be True. So, the loop starts. In line 3, the value of count is displayed. Then in line 4, it is increased by 1 (count = count + 1 = 1 + 1 = 2). After that, Python checks the condition again. As 2 < 6 is True, the loop runs again. This continues till the value of count is less than 6. When count becomes 6, the condition becomes False, and the loop stops.

The for Loop

The for loop is another looping statement. It is also known as a counting loop because we can use it to count up to a number or go through a sequence of values.

We use a variable to create the for loop called the loop variable.

The two ways to create a for loop:

a. With the range() function

b. Without using the range() function.

Using range() Function

Using range() function, we can specify a starting number and an ending number. So, the for loop will start from the starting number and continue up to (ending number - 1), increasing the number by 1 after each loop.

55 Chapter 2 • Introduction to Python

Syntax: for loop_variable in range(start, end, steps): <statements>

#the loop runs from start to end-1

start Optional. An integer number specifying at which position to start. If the start number is not specified, Python takes 0 by default.

stop Required. An integer number specifying at which position to stop (not included).

step Optional. An integer number specifying by what value to increase the value of loop variable. By default Python increases the value by 1.

Explanation

Here, the starting number is 0 and the ending number is 5. So, the for loop starts counting from 0 and continues until one less than ending number, which is 4. And after each loop, the value of i increases by 1.

Without Using The range() Function

Without using the range function, a for loop can iterate over letters in a string, values in a list or a dictionary as well.

Syntax: for loop_variable in string_variable: <statements>

Code OUTPUT for count in range(0, 5): print(count) 0 1 2 3 4
56 AI and ML - II

word = ‘adventure’ for letter in word: print(letter)

Explanation

Here the loop starts with the first letter, i.e., letter = ‘a’. And in each loop, the value of the variable changes to the next letter in the string. So in the second loop, letter = ‘d’, in the third loop, letter = ‘v’, and so on. It continues up to the last letter in the string.

The for versus while Loop

The for Loop

In a for loop, we initialise, test and update the loop variable during writing a loop in one single line, whereas the while loop requires more lines.

For loop is also called a counting loop since it counts up to a number. for i in range(start, stop, increment):

//step1

//step2

The while Loop

In a while loop, the condition is tested first and the loop gets executed when the condition is met. In case, if we forget to update the loop variable, there are chances we may end up in an infinite loop which doesn’t happen in the case of for loop.

While loop is also called a conditional loop because it has a condition.

Code OUTPUT
a d v e n t u r e 57 Chapter 2 • Introduction to Python

while(i<=10): //step1 //step2

Nested Loop

A nested loop is a loop inside another loop. The first loop we start off with is called the outer loop. All the loops that are written inside the outer loop are called inner loops. The outer loop can contain more than one inner loop. The inner or outer loop can be any type, such as a while loop or a for loop.

The entire “inner loop” gets executed every time the “outer loop” runs.

If the outer loop runs 5 times, and the inner loop runs 10 times. Then for the 1st iteration of the outer loop, the inner loop will run 10 times, for the 2nd iteration of the outer loop, the inner loop will run 10 times, and so on.

So in total, the inner loop will run 5 (outer loop count) * 10 (inner loop count) = 50.

Nested for Loop

rows = 6 for num in range(rows): for i in range(num):

print(num, end=” “) # print number

print(“ “)

A while Loop Inside A for Loop

for i in range(1,6): j=0 while j<i: print(i,end=” “) j=j+1 print(“ “)

i=1
Code OUTPUT Code OUTPUT
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
58 AI and ML - II

Nested while Loop

i=1

while i<6: j=0 while j<i: print(i,end=” “) j=j+1

A for Loop Inside A while Loop

while i<6: for j in range(0,i): print(i,end=”

The Break and Continue Statements

Loops run the same set of code for a defined number of times or until the test condition becomes False, but sometimes we might wish to stop the loop even before the test condition becomes False or skip an iteration. In those cases, we can use the break and continue statements.

The break Statement

The break keyword is used to break out / get out of the loop and execute the next statement.

Syntax:

while expression: if condition: break

#breaks out of the loop

#executes statement outside the loop

Code OUTPUT Code OUTPUT
i=i+1 print(“ “) i=1
i=i+1 print(“ “) 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
“)
59 Chapter 2 • Introduction to Python

word = input(‘Enter a word: ‘) for letter in word:

if letter in ‘aeiou’:

print(‘Vowel(s) found!’) break

Explanation

Here, the loop runs for all the letters in the word entered by a user. Inside the loop, Python checks the condition if the letter is a vowel or not (i.e. a, e, i, o, u). If the condition becomes True, Python runs the break statement in line 5, which forces it to stop the loop.

The continue Statement

The continue keyword is used to skip the execution of statements ahead in the loop. Python skips the statements after the continue keyword in the current iteration/cycle of the loop and does not stop the loop.

Syntax:

while expression:

Statement_1

if condition: continue

#skips next set of statements and starts with next loop iteration Statement_2

for num in range(10,21):

if num == 12 or num== 15 or num==19:

#When num = 10, it’s False continue

Code OUTPUT Code OUTPUT
print(num) Enter a word: Success Vowel(s) found! 10 11 13 14 16 17 18 20 60 AI and ML - II

Explanation

Here, the for loop starts counting from 1. In each loop, it increases the value of num by 1, and when num is equal to 12, 15, or 19 (i.e. the condition in line 2) is True, Python runs the continue statement, which forces it to skip the lines below it. That is why the numbers 12, 15, and 19 are not displayed in the output.

Python Packages

Python packages are like toolboxes that provide additional features and functions to the Python programming language. They are made up of modules, which are simply individual files containing code. These modules can be grouped together into a package, which is just a folder that contains related modules.

To use a package in your Python code, you need to first install it using a package manager like pip. Pip can download and install packages from online sources like PyPI, and it makes the process of installing and managing packages easy and straightforward.

Categories of Python Packages

Python packages can be broadly classified into the following categories based on their functionality:

● Scientific Computing Packages: These packages are used for numerical computations and scientific data analysis. Examples include NumPy, SciPy, Pandas, Matplotlib, and SymPy.

● Web Development Packages: These packages are used for building web applications and web APIs. Examples include Flask, Django, Pyramid, and CherryPy.

● Machine Learning and Data Science Packages: These packages are used for data analysis, machine learning, and artificial intelligence applications. Examples include Scikit-learn, TensorFlow, Keras, PyTorch, and NLTK.

● Testing and Debugging Packages: These packages are used for testing and debugging code. Examples include Pytest, Unittest, Doctest, and PDB.

● Game Development Packages: These packages are used for developing games using Python. Examples include Pygame, Arcade, and PyOpenGL.

61 Chapter 2 •
Introduction to Python

● Network Programming Packages: These packages are used for network programming and communication. Examples include Requests, Socket, Twisted, and Paramiko.

● GUI Programming Packages: These packages are used for creating graphical user interfaces (GUIs) for desktop applications. Examples include PyQt, PyGTK, and Tkinter.

These are just some examples of the many categories of Python packages available. Each package serves a specific purpose and can be used to extend the functionality of Python in unique ways.

Popular Python Packages

Here are some popular Python packages that you may find useful:

● NumPy: NumPy is a package for numerical computing in Python. It provides fast and efficient multidimensional arrays and tools for working with them.

● OpenCV: OpenCV (Open Source Computer Vision) is a popular Python package used for computer vision and image processing tasks. It provides a wide range of functions and tools for tasks such as face detection, object recognition, image segmentation, and video analysis.

● NLTK: The NLTK (Natural Language Toolkit) package is a popular Python package used for natural language processing tasks such as text analysis, tokenisation, part-of-speech tagging, and sentiment analysis. It provides a wide range of functions and tools for working with human language data.

● Pandas: Pandas is a package for data manipulation and analysis in Python. It provides data structures and tools for working with data in a variety of formats.

● Matplotlib: Matplotlib is a package for creating static, animated, and interactive visualisations in Python. It provides tools for creating a wide range of plots, charts, and graphs.

● Scikit-learn: Scikit-learn is a package for machine learning in Python. It provides tools for classification, regression, clustering, and other tasks.

62 AI and ML - II

● Flask: Flask is a package for creating web applications in Python. It provides tools for handling HTTP requests, creating HTML templates, and more.

Installing a Package

To install a Python package, you can use a package manager called pip. pip is included with Python 2.7.9+ and Python 3.4+ by default, so you don’t need to install it separately.

Here are the steps to install a Python package using pip:

● Open a command prompt or terminal window.

● Type the following command to check if pip is installed: pip --version

● If pip is not installed, you can install it by following the instructions here: https://pip.pypa.io/en/stable/installation/

● Type the following command to install the package: pip install package_name

Replace package_name with the name of the package you want to install.

For example, if you want to install the numpy package, you would type: pip install numpy

● Wait for pip to download and install the package and its dependencies.

That’s it! Once the package is installed, you can import it into your Python code and start using its functions and classes.

To update a package to the latest version, you can use the following command: pip install --upgrade package_name

Replace package_name with the name of the package you want to update.

Importing a Package

To import a package in Python, you can use the import statement followed by the name of the package.

63 Chapter 2 • Introduction to Python

For example, to import the numpy package, you would write: import numpy

This will make all the functions and classes in the numpy package available in your code.

To use a specific function or class from the package, you can specify it using the dot notation.

For example, to use the linspace function from the numpy package, you would write:

import numpy x = numpy.linspace(0, 1, num=10)

Alternatively, you can use the from keyword to import specific functions or classes from the package.

For example, to import only the linspace function from the numpy package, you would write:

from numpy import linspace x = linspace(0, 1, num=10)

This allows you to use the linspace function directly in your code without having to specify the package name. However, it’s generally considered good practice to import the entire package and use the dot notation to specify the functions or classes you need.

Points to Remember

● A variable is a memory location on a computer which can hold any value and can also change over time as needed.

● Rules of naming a variable are:

■ The name of a variable should be meaningful.

■ Only the underscore ( _ ) symbol can be used while naming variables.

■ A variable name must start with a letter or the underscore character.

■ As Python is a case-sensitive language, variable names are also case-sensitive.

■ A variable name can have numbers within but cannot begin with a number.

64 AI and ML - II

● Assignment Operator assigns the value on the right-hand side of the “=” symbol to the variable on the left-hand side.

● Data types define what type of data a variable, a named memory location, can hold.

● Type casting refers to converting the data type of a variable into another.

● The Python Math Library provides common math functions that can be used for complex mathematical computations. The Math library contains functions such as ceil, floor, factorial, etc.

● Python’s Random module is an in-built module of Python which is used to generate random numbers.

● Decision making is making decisions based on certain conditions.

● Loops help us repeat a set of instructions again and again until a particular condition remains True. As soon as the condition becomes False, the loop stops.

● For loop is also called a counting loop since it counts up to a number.

● While loop is also called a conditional loop because it has a condition.

● A nested loop is a loop inside another loop. The first loop we start off with is called the outer loop. All the loops that are written inside the outer loop are called inner loops.

● Python packages are like toolboxes that provide additional features and functions to the Python programming language.

● To use a package in your Python code, you need to first install it using a package manager like pip.

● NumPy is a package for numerical computing in Python.

● OpenCV (Open Source Computer Vision) is a popular Python package used for computer vision and image processing tasks.

● The NLTK (Natural Language Toolkit) package is a popular Python package used for natural language processing tasks such as text analysis, tokenisation, part-of-speech tagging, and sentiment analysis.

65 Chapter 2 •
Introduction to Python

Practice Questions

A. Tick the Correct Option

1. Which of the following is a valid variable name in Python?

my-variable my variable

my_variable my variable!

2. Which of the following data types is immutable?

List Tuple Dictionary Set

3. Which of the following is an example of implicit type casting? int(“123”) float(“3.14”)

“123” + 456 123 + 4.56

4. Which of the following is an example of explicit type casting? int(“123”) float(“3.14”)

“123” + 456 123 + 4.56

B. Find the Truth

1. An error is raised when you try to convert a string that cannot be converted to a number to an integer using int().

2. A sequence of statements that is executed in order is called a loop.

3. The while loop is used to execute a block of code as long as a certain condition is true.

4. A loop control statement is used to start, end and skip an iteration of a loop.

5. The continue statement is used to exit a loop completely.

C. Very-Short-Answer Questions

1. What are the two types of loops in Python?

2. How do you skip to the next iteration of a loop in Python?

66 AI and ML - II

3. What are the different data types that a variable can have in Python?

4. Can you use a conditional statement without an “else” statement?

D. Short-Answer Questions

1. What is the purpose of a conditional expression?

2. What is the numpy package used for?

3. What is the matplotlib package used for?

4. What is the NLTK package used for?

5. What is the difference between a “for” loop and a “while” loop?

E. Long-Answer Questions

1. What is typecasting in Python and why is it useful?

2. How do you break out of a loop in Python? Explain with an example.

Programming Problems

1. There are three trains. Train 1 travels 25 km per hour. Train 2 travels 50 km per hour. Train 3 travels 80 km per hour. How far do each of the trains go in 2.5 hours?

2. It is the start of the school year and you are at a notebook store. The shopkeeper asks for your help to print the bill. The rate of the notebooks is as follows:

Print the total bill of a customer who purchases 3 blank, 4 ruled, and 1 grids notebooks.

OUTPUT Train 1 travels 62.5 km Train 2 travels 125 km Train 3 travels 200 km
Notebook Total no. of copies Blank Double-ruled Ruled Grids 30 35 32 33
67 Chapter 2 • Introduction to Python

3. Create a program to calculate basic mathematical operations (addition, subtraction, division and multiplication) on any two numbers.

4. Write a program to print the largest number among three inputs.

5. Write a program to input three numbers from the user and check if three numbers are unique or not.

6. Write a program to print numbers in decreasing order from 10 using a while loop.

7. Write a program to print the first 10 even numbers in reverse order.

8. Write a program to display the following pattern of stars.

68 AI and ML - II

Data Science with Python

Data Science

Extracting meaningful insights from data is known as data science. Data, when investigated and carefully analysed, provides insights which enrich our daily lives. Data science involves mathematical techniques and algorithms to analyse data and extract insightful information and knowledge from data which is beneficial for the business or the purpose at hand. Data science methods provide strong decision-making capability.

Data Science can also be defined as a domain of study that deals with vast volumes of data using modern tools and techniques to find unseen patterns, extract meaningful information, and make decisions. Data scientists use a variety of tools and methods, such as machine learning, statistical modelling, and data visualisation, to analyse and make predictions from data. Data scientists have changed almost every industry.

Data Science applications are used in almost every industry.

● Healthcare: Data science can identify and predict diseases with the use of sophisticated medical tools and personalise healthcare recommendations.

● Transportation: Data science can optimise routes to ensure faster delivery of products and increase operational efficiency.

● Sports: Data science can accurately evaluate athletes’ performance.

● Government: Data science can prevent tax evasion and predict incarceration rates.

● E-commerce: Data science can automate digital ad placement.

● Gaming: Data science can improve online gaming experiences.

Chapter 3
69

● Social media: Data science can create algorithms to pinpoint compatible partners.

● Gaming: Data Science has taken the gaming experience to the next level.

● Image Recognition: Data Science helps to identify patterns and detect objects in an image. It may also be seen on social media platforms such as Facebook, Instagram, and Twitter. When you submit a picture of yourself with someone on your list, these applications will recognise them and tag them.

● Recommendation Systems: Social media makes recommendations based on what you like to watch, purchase, or browse on different platforms.

● Fraud Detection: Data Science is used to detect fraudulent transactions in banking and financial institutions.

● Internet Search: Google handles more than 20 petabytes of data per day that employ data science algorithms to offer the best results for our searched query in a matter of seconds. Google would not be the ‘Google’ we know today if data science did not exist.

● Speech Recognition: Data Science is behind the success of Google Assistant, Alexa, Siri etc., in our daily lives.

● Airline Route Planning: Data science helps to predict flight delays for the airline industry as well as to determine whether to land directly at the destination or to make a stop in between.

● Augmented Reality: Data science works well for the popular game Pokemon GO. The ability to wander about and look at Pokemon on walls, streets, and other non-existent surfaces. The makers of this game chose the locations of the Pokemon and gyms using data from Ingress, the previous app from the same business.

● Digital Marketing and Advertising: The immense growth in industry would not be possible without Data Science. The Data Science application in digital marketing helps organisations advertise their products to the right customers. By digital marketing, the value of the business increases as advertising enhances the visibility of the company in the market.

70 AI and ML - II

The applications of Data Science in various sectors are playing a key role in changing the world by using various Data Science methodologies. These methodologies are related to data wrangling, analysis, visualisation, and many more. These integrate with software, web applications, and mobile applications, which make them efficient.

Mini Project

Visit the link: https://rockpaperscissors-ai.vercel.app/ and try to win 5 continuous games from AI. you will get a maximum of 20 chances.

Revisit AI Project Cycle

As we know, Data Science is a combination of Python and Mathematical concepts like statistics, data analysis, probability, etc. Concepts of Data Science can be used in developing applications around AI as they give a strong base for data analysis in Python.

Let us recall the AI project cycle Framework around Data Science that can be leveraged to solve some problems around us:

The AI project cycle provides us with an appropriate framework which can lead us towards the goal.

The stages involved in the AI project cycle are as follows:

● Problem Scoping: This is the initial stage that defines the goals to be achieved and understand the problems to be addressed with the help of an AI system.

● Data Acquisition: Acquiring and compiling the relevant data that is used to train the AI system.

● Data Exploration: Exploring and interpreting the acquired data to derive useful information from it and then arrange it uniformly in a proper format and layout for better understanding.

● Modelling: Using and presenting the data to various AI systems in such a way that they should perform predictions which meet the goals set in problem scoping.

● Evaluation: Gauge and analyse the predictions of AI systems and then decide on the best-suited AI system to be deployed.

71 Chapter 3 • Data Science with Python

Python for Data Science

Python is a popular open source programming language that is widely used in data science. Its popularity can be attributed to its ease of use, flexibility, and the vast number of libraries and packages that make data analysis and visualisation tasks more manageable.

Python has a simple and straightforward syntax that makes it easy to learn and use, even for non-programmers. It is also an interpreted language, meaning that the code can be run directly without the need for compilation, making it fast and easy to test and debug.

Python’s data science libraries and packages are the most comprehensive and powerful that include NumPy, Pandas, Matplotlib, Seaborn, Scikit-learn, TensorFlow, and PyTorch. These libraries provide a broad range of functions and tools for data analysis, visualisation, and machine learning.

● NumPy: NumPy provides a powerful array manipulation capability and numerical computing functions.

● Pandas: Pandas offers data manipulation and analysis tools that make it easy to clean, transform, and analyse large datasets.

● Matplotlib and Seaborn: Matplotlib and Seaborn are libraries for creating visually appealing plots and graphs.

● Scikit-learn: Scikit-learn is a comprehensive machine-learning library that offers a range of supervised and unsupervised learning algorithms.

● TensorFlow and PyTorch: TensorFlow and PyTorch are deep-learning libraries that offer a range of tools for building and training neural networks.

Case Study

We have a dataset in a CSV file that contains information about customers and their purchases. We can use Pandas to load the CSV file into a Pandas DataFrame, which is a two-dimensional table that can easily be manipulated and analysed.

72 AI and ML - II

Here’s an example code snippet:

import pandas as pd

# Load the dataset into a DataFrame

df = pd.read_csv(‘customer_purchases.csv’)

# Display the first 5 rows of the DataFrame print(df.head())

# Calculate the average purchase amount

avg_purchase = df[‘Purchase Amount’].mean() print(f”The average purchase amount is ${avg_purchase:.2f}” )

In this code, we first import the Pandas library and load the CSV file into a DataFrame using the read_csv() function. We then use the head() function to display the first 5 rows of the DataFrame.

Finally, we calculate the average purchase amount by selecting the Purchase Amount column from the DataFrame and using the mean() function. We format the output to display the result as a currency using f-strings.

Statistical Learning and Data Visualisation

Statistics is the discipline that involves collecting, organising, presenting, interpreting, and analysing data to describe it. While datasets alone may not reveal much, applying certain statistical methods allows us to gain insight and useful revelations from the data. Let us now explore some basic statistical methods that can be applied to data:

● Mean: The average value of a sequence.

● Median: The 50th percentile value of a sequence.

● Mode: The most frequent value in the sequence.

● Standard Deviation: Measures the spread of the sequence around its average value.

● Variance: The average of the squared differences from the mean. Powerful Python libraries such as Pandas can be efficiently used for data exploration. Data exploration is done before visualisation to ensure that the data is relevant, well-formed, valid, correct, clean, and devoid of any missing values. Once the data is in the desired form, we can apply data visualisation methods to it. Data visualisation can be efficiently done using the Matplotlib package of Python. With this package, we can plot various kinds of graphs

73 Chapter 3 • Data Science with Python

such as scatter plots, histograms, box plots, bar graphs, etc., and save them as image files for future use.

K-Nearest Neighbour Model - Personality Prediction

The K-Nearest Neighbours (KNN) algorithm is a simple and easy-to-implement supervised machine learning algorithm that can solve both classification and regression problems. The KNN algorithm works on the assumption that similar things exist in close proximity. In other words, the KNN algorithm analyses the data points grouped into separate classes and predicts in which class the new value falls.

The K Nearest Neighbour algorithm classifies the given new data point into the target class by analysing the features of its neighbouring data points. Here, K refers to the number of data points nearest to the data point that needs to be classified.

Some features of the KNN model include:

● It is the simplest yet most effective classification algorithm.

● It can also be used for regression problems.

● It assumes that things with similar properties stay in close proximity.

● It is a supervised machine learning algorithm because it tries to make predictions based on known values.

● It stores all the values in the dataset in memory until the prediction is computed, making it a lazy algorithm.

● Due to its lazy characteristic, it requires a lot of memory and processing power to compute predictions.

● It is best suited for classification involving values for which there is little or no knowledge about the distribution of values.

KNN

can also predict personality traits.

For example: To use KNN for personality prediction, the algorithm would first need to be trained on a dataset. This involves selecting a value for k (the number of neighbours to consider) and calculating the distance between each person’s personality features and the features of their nearest k neighbours.

Once the algorithm has been trained, we can use it to predict the personality of a new person based on their features.

74 AI and ML - II

For example, let’s say we have a new person with the following features:

Enthusiasm: 7

Resilience: 4

Creativity: 6

Leadership: 2

Intelligence: 5

To predict this person’s personality, we would use the KNN algorithm to find the k nearest neighbours to this person based on their feature values.

Let’s say we set k to 5, and the algorithm finds the following nearest neighbours:

Person 1: Enthusiasm 8, Resilience 6, Creativity 7, Leadership 3, Intelligence 5

Person 2: Enthusiasm 6, Resilience 5, Creativity 5, Leadership 4, Intelligence 4

Person 3: Enthusiasm 7, Resilience 3, Creativity 6, Leadership 2, Intelligence 6

Person 4: Enthusiasm 6, Resilience 4, Creativity 7, Leadership 1, Intelligence 6

Person 5: Enthusiasm 7, Resilience 5, Creativity 6, Leadership 2, Intelligence 7

Based on these nearest neighbours, we can predict the personality of the new person using a variety of methods. For example, we could simply take the average personality scores of the nearest neighbours and use that as the predicted personality for the new person.

In this case, the average personality scores of the nearest neighbours would be:

Enthusiasm : (8 + 6 + 7 + 6 + 7) / 5 = 6.8

Resilience: (6 + 5 + 3 + 4 + 5) / 5 = 4.6

Creativity: (7 + 5 + 6 + 7 + 6) / 5 = 6.2

Leadership: (3 + 4 + 2 + 1 + 2) / 5 = 2.4

Intelligence: (5 + 4 + 6 + 6 + 7) / 5 = 5.6

Therefore, the KNN algorithm would predict that the new person has a personality with an enthusiasm score of 6.8, resilience score of 4.6, creativity score of 6.2, leadership score of 2.4, and intelligence score of 5.6.

75 Chapter 3 • Data Science with Python

Points to Remember

● Extracting meaningful insights from data is known as data science

● Data Science methodologies are related to data wrangling, analysis, visualisation, and many more. These integrate with software, web applications, and mobile applications, which make them efficient.

● The AI project cycle provides us with an appropriate framework which can lead us towards the goal.

● Python’s data science libraries and packages such as NumPy, Pandas, Matplotlib, Seaborn, Scikit-learn, TensorFlow, and PyTorch provide a broad range of functions and tools for data analysis, visualisation, and machine learning.

● Statistics is the discipline of collecting, organising, presenting, interpreting and analysing data.

● K Nearest Neighbour algorithm classifies the new data point into the target class by analysing the features of its neighbouring data points.

76 AI and ML - II

A. Tick the Correct Option

1. Which of the following is the main feature of Data Science?

Immense volume of data

Healthcare

Lower volume of data

No data

2. is behind the success of Google Assistant, Alexa, Siri etc., in our daily lives.

Deep learning Data Science

Machine learning

All of them

3. Which of the following is not a part of the 4Ws in problem scoping?

Who When

What Where

4. Pandas offers data and analysis tools that make it easy to clean, transform, and analyse large datasets.

Exploration Mining

Manipulation Collection

5. Which one of the following is not a social media platform?

Facebook Twitter

Instagram Amazon

B. Find the Truth

1. Mean measures the spread of the sequence around its average value.

2. Evaluation is the first stage of the AI project cycle.

3. KNN stands for K Nearest Number.

4. The graphs plotted with matplotlib can be saved as image files for future use.

5. Google handles more than 20 megabytes of data per day.

Practice Questions 77 Chapter 3 • Data Science with Python

C. Very-Short-Answer Questions

1. Name any two applications of data science.

2. Name the libraries of Python that offer a range of tools for building and training neural networks.

3. Describe problem scoping.

4. Define Standard Deviation.

5. What does K represent in the KNN algorithm?

D. Short-Answer Questions

1. KNN is a supervised machine learning algorithm. Justify.

2. How is data science useful for social media platforms like Facebook, Twitter, etc.?

3. Mention any three features of K Nearest Neighbour algorithm.

4. Explain NumPy.

5. What is the importance of data acquisition?

E. Long-Answer Questions

1. Data science methods provide strong decision-making capability. Justify this statement with an example.

2. Explain Data Visualisation. How does the matplotlib package of Python help in it?

Mini Project

Research and prepare a presentation/project report/write up on how data science has become an important part of our day-to-day life.

78 AI and ML - II

Chapter 4

Computer Vision

Computer Vision

Computer vision is a domain of artificial intelligence that enables computers and systems to derive meaningful information from digital images, videos, and other visual inputs and take actions or make recommendations based on that information. If AI enables computers to think, computer vision enables them to see, observe, and understand. Google lens, self-driving cars, and face lock in smartphones are good examples of it.

Machines with CV algorithms can be trained with a lot of visual data to process visuals at incredible speed and with accuracy. These applications are available to everyone at ease today and they are on the priority list of many industries. Let us explore some major applications of computer vision:

● Facial Recognition: It is one of the most common and popular applications of CV. It is used as security features in handheld digital communication devices, and various types of computers to unlock them. It is also useful in law enforcement in identifying faces of suspects, missing persons, and known criminals. Smart homes can use it to distinguish between a friendly guest and a stranger, tracking visitors, employees, passengers arriving and leaving and then logging the details in the system as official records for later checking or audit.

79

● Document Verification: Industries such as banking and finance, travel, property and real estate, law and legal services, vehicle registration and verification, are major areas where computer vision capabilities can be applied to extensive documentation for accurate validation of the documents and as quickly as possible. It helps in fraud detection, authenticating individuals, verifying ownership of property, identifying forfeit currency and documents, etc.

● Diagnostic Services: Devices and sensors equipped with CV-ML algorithms, help with faster, even real-time and accurate diagnosis of diseases and health conditions. Real-time blood loss monitoring in victims and during operations, locating tumours, brain haemorrhage, internal infections, cardiovascular ailments etc., can all be scanned to minimise death rate.

● Retail Industry: Cart’s sensors can easily perform object identification of the items in the cart and match the details in the database using computer vision. Computer Vision can help in taking inventory of items in stock for reorders and helping in tracking FSN status of items. Quick checkout at mall exit, locating misplaced items, checking shoplifting, minimising billing errors, identifying regular buyers and their preferences, are the major benefits to be harvested with the help of CV-ML algorithms.

● Image-Based Search: Clicking a picture of an item and locating it on the internet is a common practice today. Finding items, people and places can be highly efficient with CV-ML algorithms. They also help in product comparison for variety, finding similar products based on looks and make, classifying items on physical features and people for age-specific or gender-specific services, consolidation product catalogues, etc.

● Digital Audio-Visual Marketing: The new trending innovation in digital marketing using CV, helps users to create realistic visual content for the intended audience. Amazon, and Netflix etc., are already using CV-ML algorithms for creating 3D avatars of models, cartoon caricatures of celebrities and public figures, using augmented reality for product demos, game-based marketing for youth and kids, movie and book promos, etc.

● Education and Training: Learning based on augmented reality and virtual reality needs CV algorithms to convert all the static content into interactive immersive content for learning. Generating 3D visuals from 2D

80 AI and ML - II

image, assignment, answer-sheet verification, online classes, and virtual tour excursions use CV algorithms.

● Autonomous Vehicles Routing-and-Parking Assistance: Self-driven cars, driverless trucks, pilotless planes, and hands-free driving assistance are some examples of CV applications. This involves the process of identifying the objects finding navigational roots and at the same time monitoring the environment.

● Character, Sign and Symbol Recognition: ML enabled CV applications can recognise various science icons, and optical codes. This helps in visual communication like understanding traffic and road signs by self-driven vehicles, Google Translate, extracting text from image by pixel scanning, are some other examples of CV applications.

● Smart Homes and Cities: Dreams of sustainable smart homes and cities for all classes can be achieved with great help from CV-ML application, public services, domestic services, home security and upkeep, hospitals, office, school, traffic, energy consumption, and can use CV applications to enhance and enrich the quality of living without risking the environment and future generations.

Mini Project

Visit the link: https://quickdraw.withgoogle.com and beat AI to identify your drawing.

Digital Images

Computer vision is a domain of artificial intelligence that enables computers and systems to derive meaningful information from digital images, videos, and other visual inputs.

Pixels

Pixels, also known as Picture Elements are the smallest units of an image on a computer display. Usually round or square, they are typically arranged in 2-dimensional grids. Each pixel consists of three colours namely, Red, Green, and Blue. When these colours are combined, different colours are formed. Multiple pixels together form a complete image.

81 Chapter 4 • Computer Vision

How do computers see images?

Computers only understand data in the form of numbers. An image is an array of thousands of pixels. They are microscopic in size, and together form a smooth, final visual of the scene that our brain perceives as a single image. If a computer is able to store the information of an image then the computer is able to see that image.

Image Features

Features refer to distinctive characteristics of an image that can be used to identify objects, detect patterns, and perform various tasks related to image analysis.

Some common features include:

● Edges: Edges are abrupt changes in brightness or colour within an image. They can be used to identify boundaries between objects in an image.

● Corners: Corners are the points where two or more edges meet. They can be used to identify specific points of interest in an image, such as the corners of a building.

● Textures: It refers to repeating patterns within an image such as grain of wood. It can be used to classify images based on their content.

● Colour Histogram: They are graphical representations of distribution of colours in an image. They can be used to identify colour patterns within an image.

● SIFT Features: SIFT (Scale-Invariant Feature Transform) are invariant to changes in scale and rotation. They can be used in object recognition and image retrieval.

Thus, image features play an important role in image recognition, object detection, and scene analysis, etc.

OpenCV - Image Processing

OpenCV is an open source computer vision library that provides various tools and techniques for image and video processing. It provides a wide range of functions and algorithms for various image processing tasks, such as image filtering, object detection, image segmentation, face recognition, and image enhancement.

82 AI and ML - II

For instance, let’s flip an image. We can flip an image horizontally or vertically.

Syntax: flip_img=cv2.flip(img,0)

In the above code, the second argument is either 0 or 1. 0 is for flipping the image vertically and 1 is to flip it horizontally.

Example import cv2 img=cv2.imread(cat.png) flip_img=cv2.flip(img,0)

cv2.imshow(“OpenCV Flip”, flip_img) cv2.waitkey()

cv2.destroyAllWindows()

Points to Remember

● Computer vision enables computers and systems to derive meaningful information from digital images, videos, and other visual inputs and take actions or make recommendations based on that information.

● Pixels, also known as Picture Element, is the smallest unit of an image on a computer display.

● Image features play an important role in image recognition, object detection, and scene analysis, etc.

● OpenCV is the open source library that provides various tools and techniques for image and video processing.

83 Chapter 4 • Computer Vision

Practice Questions

A. Tick the Correct Option

1. Images need to be converted to which of the following data types for computers to recognise them?

Numbers Graphs

Pixels Channels

2. Which of the following is not an image feature?

Corners Edges

Center Texture

3. Which of the following identify specific points of interest in an image?

Corners Edges

Center Texture

4. In the code, flip_img=cv2.flip(img, 1), the image will be flipped .

Horizontally

Vertically

The code has error

None of them

5. Each pixel consists of three colours namely, Red, , and Blue.

Gray Yellow Green White

B. Find the Truth

1. CV cannot process visual data.

2. Pixel is the largest unit of an image.

3. Pixels are arranged in 3D grids.

4. Google assistant is an example of a CV application.

5. Edges are used to identify boundaries between objects in an image.

84 AI and ML - II

C. Very-Short-Answer Questions

1. Give two examples of applications of Computer Vision.

2. Define pixels.

3. Mention features of an image.

4. Explain the use of corners of an image.

5. Write the full form of SIFT.

D. Short-Answer Questions

1. What do you mean by the term ‘Computer Vision’?

2. How can Computer Vision help in Education & Training?

3. Describe the role of facial recognition application in smart homes.

4. Explain briefly how computers understand images.

5. What is the importance of image-based search?

E. Long-Answer Questions

1. Give 5 examples of applications of Computer Vision. Explain any two of them.

2. Explain Texture, and Orientation features of Image.

Mini Project

Visit: https://openai.com/blog/chatgpt and find the answers to questions given by your teacher to prepare a project file.

85 Chapter 4 • Computer Vision

Natural Language Processing

Natural Language Processing (NLP)

Natural Language Processing (NLP) is the domain of artificial intelligence (AI) that deals with the language-based interactions between a machine and a human as well as between two machines.

NLP combines computational linguistics: rule-based modelling of human language, with statistical, machine-learning, and deep-learning models. Together, these technologies enable computers to process human language in the form of text or voice data and to understand its full meaning.

NLP drives computer programs that translate text from one language to another, respond to spoken commands, and summarise large volumes of text rapidly, even in real time. Some examples of applications of NLP include:

● Voice-operated GPS Systems: With this technology, drivers can easily use a variety of in-vehicle functions such as giving voice commands to reach a location for a comfortable drive while driving and without taking their eyes off the road.

● Virtual Assistants: This is one of the most common applications of NLP. You can find it in every home in today’s era. Virtual assistants come in the form of applications only or combinations of devices loaded with applications. Google assistant is the best example for the application of virtual assistant and Alexa is the best example of the device loaded with application. Virtual assistants usually work on voice commands and can be initiated by a keyword called ‘wake word’. For Amazon’s Alexa the wake word is Alexa. Just speak a natural English sentence to Alexa and it will interpret correctly what to do. Some other virtual assistants

Chapter 5
87

are Microsoft Cortana and Apple Siri. Another virtual assistant Samsung’s Bixby is also attempting to take on the likes of Siri, Google Assistant, and Amazon Alexa.

● Speech Recognition: It is used to convert spoken words to text in applications such as mobiles, home automation, video recovery, dictating to Microsoft Word, voice biometric, voice user interface, etc.

● Customer Service Chatbots: Most companies such as TataPlay, Airtel, Idea, etc., have chatbots in their applications to provide instant service to the customer. When you send a message to them, they interpret it and respond to you with the best suitable answer.

● Spam Detection: NLP also helps to detect and prevent unwanted emails getting into a user’s inbox.

● Education and Training: NLP can be used to create new instruction material in various forms like textbooks, slides for teaching, lab guides, and ready reckoners. For example: Curipod.com, beautiful.ai, etc., can be used to create presentations using AI. ChatGPT is the latest tool of AI to improve educational skills. Another example of NLP is Grammarly which is used to improve grammar.

NLP also plays a growing role in enterprise solutions that help streamline business operations, increase employee productivity, and simplify missioncritical business processes.

Chatbots

Chatbot is an application that simulates and processes human conversation (either written or spoken), allowing humans to interact with digital devices as if they were communicating with a real person.

There are two types of chatbots:

1. Rule-based or Script Bot: This type of chat bot has all the intelligence built into it and cannot think beyond it. These chatbots are inexpensive to deploy. They are also very useful in user-specific environments where

88 AI and ML - II

limited functionalities are actually needed. For example, subject-specific or domains in specific education and training, technical assistants, troubleshooting, and service- or product-specific functions.

2. AI-based Bot: This type of bot works on machine-learning algorithms with natural language-processing capability. They actually make sense of conversations in terms of context, reference, intention, just as the human brain does. Such bot applications are useful in building public relations by providing enriched customer service. They give human-like conversational experience to the user. They work wonders, that’s why they are comparatively expensive. They provide enriched user experience as compared to script bots.

Case Study

A company wants to use artificial intelligence to improve their customer service. They decide to build a chatbot that can answer common questions and help customers troubleshoot issues with their products or services.

To build the chatbot, the company first needs to collect data about the types of questions customers ask and the best ways to answer them. They do this by analysing customer support tickets, chat logs, and other interactions with customers.

Next, they use this data to train a machine-learning model. The model uses natural language processing (NLP) to understand customer questions and generate appropriate responses. The more data the model is trained on, the better it becomes at answering questions and predicting what customers are likely to ask next.

Once the model is trained, the company can deploy the chatbot to their website or other customer-facing channels. Customers can interact with the chatbot just as they would with a human support representative, typing in their questions and receiving responses in real time.

Over time, the chatbot learns from these interactions and becomes even more effective at answering questions and resolving issues. The company can continue to collect data and use it to further improve the chatbot’s performance.

89 Chapter 5 • Natural Language Processing

In this way, artificial intelligence has helped the company to provide faster and more efficient customer service, while also reducing the workload on their human support team.

Human Language vs Computer Language

Humans communicate through language which we process all the time. Our brain keeps on processing the sounds that it hears around itself and tries to make sense out of them all the time. On the other hand, the computer understands the language of numbers. Everything that is sent to the machine has to be converted into numbers. Machines can be faster in processing than the brain but they cannot beat the brain in smartness and in the variety of the ways it processes information. Also, human language has a very large vocabulary whereas computer language has a very limited vocabulary.

The tone or emotions of the context can be understood by human language but a machine cannot understand the emotions of the context. The human brain, through its life-long training, can figure out if the sentence really makes sense even if it is grammatically incorrect but a machine would not bother about sense as long as it can work out the grammar correctly.

Data Processing

Data processing is an important step in natural language processing (NLP) that involves preparing raw text data for use in NLP models and applications. Data processing typically involves several steps, including cleaning and preprocessing the text, tokenisation, part-of-speech tagging, and named entity recognition. Here’s an example to illustrate the data processing steps in NLP:

Let’s say we have a dataset of customer reviews for a restaurant, and we want to use NLP to analyse the sentiment of the reviews. The first step in data processing is to clean and preprocess the text. This may involve removing punctuation, converting all text to lowercase, and removing stop words (common words that don’t carry much meaning, such as “the” and “a”).

After cleaning and preprocessing, the text is usually tokenised, or broken down into individual words or tokens. For example, the sentence “The food was delicious and the service was excellent” would be tokenised into the following list of words: [“the”, “food”, “was”, “delicious”, “and”, “the”, “service”, “was”, “excellent”].

90 AI and ML - II

Next, the tokens may be tagged with their part of speech (POS). Part-of-speech tagging involves assigning a tag to each token based on its grammatical function in the sentence. For example, the word “food” would be tagged as a noun (NN), “was” would be tagged as a verb (VBD), and “excellent” would be tagged as an adjective (JJ).

Finally, named entity recognition (NER) may be used to identify and classify named entities in the text, such as people, places, and organisations. For example, in the sentence “I had dinner at Red Chilly in Mumbai last night”, the named entity “Red Chilly” would be identified as a restaurant, and “Mumbai” would be identified as a location.

Once the data has been processed, it can be used in various NLP models and applications, such as sentiment analysis, topic modelling, and text classification. By processing the data in this way, we can extract useful information from raw text data and gain insights into customer feedback, trends, and opinions.

Bag of Words

In NLP, the Bag of Words model is a technique that is used for text classification, sentiment analysis, and other language processing tasks. This model represents a document as a set of words, disregarding grammar and word order. It only considers the frequency of each word in the document.

Thus, we can say, this algorithm is used to extract two main features of the dataset – vocabulary and frequency. Here, vocabulary refers to unique words identified in the dataset and frequency is the number of occurrences of each term in the dataset.

For example, we have 3 documents:

Document 1: “The quick brown fox jumped over the lazy dog”

Document 2: “The dog chased the cat up a tree”

Document 3: “The cat scratched the dog’s nose”

To create a Bag of Words model for these documents, we first need to preprocess the text by converting it to lowercase and removing stop words (common words like “the”, “a”, and “and” that don’t carry much meaning).

After preprocessing, the documents would look like this:

91 Chapter 5 • Natural Language Processing

Document 1: “quick brown fox jumped on lazy dog”

Document 2: “dog chased cat tree”

Document 3: “cat scratched dog’s nose”

Next, we create a vocabulary of all the unique words in the documents:

Document 1 quick brown fox jumped lazy dog

Document 2 dog chased cat tree

Document 3 cat scratched dog’s nose

Bag of Words algorithm is not concerned with the sequence of words hence the term bag. It is simply a dictionary and the frequency of each word in the vocabulary.

These two features help us to create document vectors for each document. They are presented in the form of a document vector table. Document vector table contains all the terms in the dataset in the table header and displays the frequency of terms in rows as one row for each document.

For example,

quick
scratched nose Document 1 1 1 1 1 1 1 0 0 0 0 0 Document 2 0 0 0 0 0 1 1 1 1 0 0 Document 3 0 0 0 0 0 1 1 0 0 1 1 VOCABULARY FREQUENCY quick 1 brown 1 fox 1 jumped 1 lazy 1 dog 3 chased 1 cat 2 tree 1 scratched 1 nose 1 92 AI and ML - II
brown fox jumped lazy dog cat chased tree

In this way, we can represent each document as a vector of word frequencies, or a “bag” of words. This allows us to compare documents and perform various natural language processing tasks.

Natural Language Toolkit

Natural Language Toolkit, or NLTK, is an open source collection of libraries, programs, and education resources for building NLP programs using Python programming language.

The NLTK includes libraries for many of the NLP tasks, plus libraries for subtasks, such as sentence parsing, word segmentation, stemming and lemmatisation (methods of trimming words down to their roots), and tokenisation (for breaking phrases, sentences, paragraphs and passages into tokens that help the computer better understand the text). It also includes libraries for implementing capabilities such as semantic reasoning, the ability to reach logical conclusions based on facts extracted from text. Chatbots also use Natural Language ToolKit (NLTK) to process the textual information.

Anaconda comes bundled with the NLTK package or you can download it by typing pip install NLTK. For instance:

import nltk nltk.download()

In this way we can download all the packages listed in NLTK package and to download specific NLTK packages we need to mention the package name. For example,

import nltk nltk.download(‘stopwords’)

Points to Remember

● Natural Language Processing (NLP) deals with the language-based interactions between a machine and a human as well as between two machines.

● Chatbot is an application that simulates and processes human conversation.

93 Chapter 5 • Natural Language Processing

● Data processing typically involves several steps, including cleaning and preprocessing the text, tokenisation, part-of-speech tagging, and named entity recognition.

● Bag of Words model is a technique that is used for text classification, sentiment analysis, and other language processing tasks.

● Natural Language Toolkit, or NLTK, is an open source collection of libraries, programs, and education resources for building NLP programs using Python programming language.

94 AI and ML - II

A. Tick the Correct Option

1. Which of the following is a common application of NLP?

Spam filtering

Image captioning

Speech recognition Object detection

2. Which of the following is a popular NLP library in Python?

TensorFlow PyTorch

Keras NLTK

3. Which of the following is not a step of data processing?

Tokenisation

Cleaning the text

Named entity recognition Frequency

4. Which of the following is the main feature of the NLTK dataset?

Vocabulary Both a and b

Frequency

None of them

5. Which of the following are methods of trimming words down to their roots?

Tokenisation

Stemming and lemmatisation

Sentence parsing

All of them

B. Find the Truth

1. NLP stands for Natural Language Program.

2. Rule-based bot cannot think on its own.

3. The computer understands the language of numbers and letters.

95 Chapter 5 • Natural Language Processing
Practice Questions

4. Data processing involves preparing raw text data.

5. Bag of Words algorithm is concerned with the sequence of words.

C. Very-Short-Answer Questions

1. Name two applications of NLP.

2. Name two types of chatbots.

3. Which type of bot applications are useful in building public relations by providing enriched customer service?

4. What do you mean by vocabulary?

5. Write the full form of NLTK.

D. Short-Answer Questions

1. What is natural language processing (NLP)?

2. What is the role of NLP in education and training?

3. How do chatbots help us?

4. Differentiate between human language and computer language.

5. Explain NLTK.

E. Long-Answer Questions

1. How can NLP be used in real-world applications such as chatbots, recommendation systems, and social media analysis?

2. Explain Bag of Words with an example.

Mini Project

Visit the link: https://curipod.com/ and create a presentation on a topic given by your teacher.

96 AI and ML - II

About this book

This book represents a 21st-century approach to learning about Artificial Intelligence, and develop problem-solving skills. To prepare students for the digital age, the curriculum is interwoven with well-thought-out concept graduation with real-life examples and practice problems.

Special features

• Illustrative approach: Concepts in coding and computer science are delivered through pictorial representations and learner-friendly approaches.

• Learning through real-life examples: Age-appropriate examples that enable learners to relate to the concept and learn about the unknown from the known.

• Extensive practice: Multiple practice scenarios to reinforce learning.

• Mini projects: Includes projects through which learners can demonstrate their learning outcomes in artificial intelligence and machine-learning science.

About Uolo

Uolo partners with K12 schools to bring technology-based learning programs. We believe pedagogy and technology must come together to deliver scalable learning experiences that generate measurable outcomes. Uolo is trusted by over 8,000 schools with more than 3 million learners across India, South East Asia, and the Middle East.

Explore more hello@uolo.com Singapore Gurugram Bengaluru © 2023 Uolo EdTech Pvt. Ltd. All rights reserved.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.