Tutorials > Getting Started with Python Programming and Artificial Intelligence

Getting Started with Python Programming and Artificial Intelligence

Published on: 28 March 2021

AI Artificial Intelligence python

Conceptualizing Artificial Intelligence

Artificial Intelligence is an approach of building computer-based systems that can think intelligently and improvise their actions, like humans.

Learning through Data

At present, the most advanced AI algorithms are based on data. The idea of using huge amounts of data is to equip the program with enough information for it to form theories and start looking for patterns. By learning from these patterns, data science algorithms can predict future theories about similar characteristics in the trained data.

Embarking Intelligence

The capability of a computer system to assess, reason, understand relationships and parallels, learn from knowledge, store, and retrieve data from memory, explain problems, grasp intricate ideas, utilize natural language fluently, classify, generalize, and adapt to new situations. Enabling these features to a software program is a way of embarking intelligence to computers.

Connecting AI to the Human World

It is evident to assume when hearing about Artificial Intelligence, like an unrelated foreign object. But, to surprise, we currently use AI in most of our daily activities. Artificial intelligence is confronted by most people from morning until night.
  • Unlocking a Phone: When you use a fingerprint scanner, retina scan or a facial ID un-locker, the backend of this information uses AI to store your data and recognize if it’s you.
  • Social media and Online Shopping: All social websites and internet advertisement agencies currently use AI to recommend products and services.
  • Send an email or message: Major technology companies like Google, Microsoft have automated text information transfer and encryption that is done using AI.
  • Commuting to work: Apple, Bing or Google Maps are all heavily equipped with AI to route you to the fastest and best possible path to your destination.
  • Banking: Transferring money, stock-brokering and predicting markets are all run by machine learning algorithms that predict the market’s outlook.

Features: Python Programming Language

In this section, we will understand Python as a Programming language for implementing Artificial Intelligence. Various programming languages like C++, C#, Java, Prolog, and Python can be used for developing applications in AI. Yet, Python is the most popular language for implementing AI and related algorithms for various reasons that we will be discussing below.

Syntactic and Semantic Readability

Python is an exceedingly efficient language, meaning, programs on Python will execute a functionality in fewer lines of code in comparison to other languages. It’s in-built semantics like tabbing, generically make it more readable and easier to debug. For example, in the code shown below, we try to find if a given number is prime or not, and the code for it is efficiently readable to anyone who is new to programming:

number_test = 103
# prime numbers are greater than 1

if number_test > 1:


	# check for factors
           number_list = range (2, number_test)

	for each_number in number_list:
	       number_of_parts = number_test / each_number
		 print (f” {each_number_test} is not a prime number")

		 print(f"{each_number} times {number_of_parts} is {number_test}") 
	 	 break

	else:
	print(f"{test_number} is a prime number") 
else:
print(f"{test_number} is not a prime number")

Extensive In-Built Library Support for Artificial Intelligence

A prominent reason for Python’s popularity in the AI and ML space is the availability of numerous in-built functions and dedicated libraries for implementing algorithms. For instance, NumPy, SciPy, Matplotlib, NLTK, SimpleAI are some crucial inbuilt libraries that belong to Python. Here is brief about the common AI libraries that Python supports:
 
  • i. TensorFlow: Developed by Google, this library is popular among Machine Learning algorithms and doing hefty computations that generally require Neural Networks.
  • ii. Scikit-Learn: Scikit-learn is a Python library correlated with NumPy and SciPy. It is deemed to be one of the best and most used libraries for working with complex quantities of structured and unstructured data.
  • iii. NumPy: NumPy is a library purposely used for computing scientific/mathematical information.
  • iv. Pandas: For implementing high-level data structures and respective analysis. It allows blending and filtering of data and gathering it from several other external sources like CSV or TSV files, webpages, Excel, etc.
  • v. Theano: Theano is a functional archive that essentially calculates and processes mathematical expressions containing multi-dimensional arrays.
  • vi. Keras: This library abridges the enactment of neural networks. It also has the finest functionalities for computing models, evaluating large datasets, or visualizing graphs.
  • vii. NLTK: NLTK or Natural Language Toolkit is an open-source Python library built for Natural Language Processing, text analysis, and text mining.

Open-Source and Strong Developer Community

Over the years of open-source contributions and innovations, Python has become a strong programming language with a wide community. This is advantageous when new features are rolled out, or when developers encounter issues with the language, as public forums and community pages are very active to resolve errors and issues.

Running Python Code

Python distribution is platform independent and can run on multiple platforms including all the major operating systems. All that is needed is to download the binary code applicable for any respective platform and install Python. Even while transferring code from one platform of development to other packages such as PyInstaller resolve any dependencies and make sure code runs perfectly. Let us walk through some steps for installing Python on the local machine for Windows, Linux, and Mac machines. Go to www.python.org/downloads/.

Python Installation for Windows

  • i. Just below the main heading that says Python Releases for Windows at the top, kindly click on the link for any of the latest Python releases – Python 3.x.x.
  • ii. On scrolling to the bottom, based on the OS configuration, select from the Windows x86 or x64 executable installer.
  • iii. Open the installer and click on “Run”.

Python Installation for Ubuntu Linux

Use the Graphical Linux installation to put in python on Linux. Follow the steps below:
  • i. Open the Ubuntu Software Center folder.
  • ii. Select Developer Tools (or Development) from the All-Software drop-down list box.
  • iii. Double-click the Python 3.x.x entry and Click Install.

Python Installation for Mac

  • i. Before proceeding for installation of Python, you will need to GCC. It can be achieved by downloading XCode, or the smaller OSX-GCC-Installer package.
  • ii. Even though Mac OS comes with preinstalled Unix utilities, a package manager is missing. Homebrew, for Mac fills this void.
  • iii. On completing the installation of Homebrew, put Homebrew directory to your PATH environment. For doing this, add the below statement at the base of profile file.
    export PATH="/usr/local/opt/python/libexec/bin:$PATH"
  • iv. Now, we can install Python 3:
    $brew install python

Python Code for Artificial Intelligence

Apart from using the above-mentioned ways of Python installation and use, the most used and easily available tools for writing AI and ML code in Python are the Jupyter Notebook and Google Collab. In this section, we walk through how to use each of these for writing Python code.

Jupyter Notebooks

The Jupyter Notebook is an open-source web-based application that allows making and sharing of documents that contain live code, equations, visualizations, and narrative text. Uses of the Jupyter environment include cleaning and transformation of data, simulation of numerical data, statistical modeling and programming, data visualization, machine learning, and far more.

Google Colab

Colaboratory, or “Colab” for brief , may be a product from Google Research. Colab allows anybody to write down and execute arbitrary python code through the browser, and is particularly compatible to machine learning, data analysis and education.

Mathematics for Programming AI with Python

Mathematics is the language with which God has written the universe.”Galileo Galilei.

The ideas behind creating intelligent machines started evolving when computer scientists explored mathematical concepts in the realm of computing. The opportunity to simulate human behavior is done with the help of mathematical concepts. Artificial Intelligence and arithmetic are the 2 branches of an equivalent tree. Therefore, to take this crusade of learning Python Programming and focusing on Artificial Intelligence, we will be starting with concepts of Mathematics in the programming world. This portion will be useful in the upcoming projects and case studies since most of AI is primarily understanding mathematical constructs. Let’s get started. After all AI is not magic it’s just mathematics.

Diving Deep into Numbers through Python

Before completing this chapter, let’s look at one of the most important Python Modules that will extensively be used in programming for Artificial Intelligence, the Python Math Module. For fundamental mathematical computations in Python, mathematical operators, like subtraction (-), addition (+), division (/), and multiplication (*) are usable. But more advanced operations, such as logarithmic, exponential, trigonometric, or power functions, do not come built in. The math module in Python is designed to deal with these complex mathematical operations. It always comes packaged with the standard release of Python.

Math Module Constants

A range of predefined constants come with the module and these constants can provide several advantages while doing computations or preprocessing of data. It helps avoiding to manually hardcode them to the application, and additionally, they deliver uniformity throughout the program. Below mentioned are a few constants and their uses:
  • Pi: An irrational number that can’t be expressed as a simple fraction. Pi does have an infinite number of decimal places, although it can be approximated as 22/7, or 3.141.
  • Tau: Tau (τ) is defined as the ratio of a circle’s circumference to its radius. The value is regarded as 2π, or approximately 6.28. Like pi, tau is also an irrational number since it is multiplication of another irrational number.
  • Euler’s number: The Euler’s number (e) constant is important when dealing with logarithmic functions since it is the base of the natural logarithm and is frequently used to analyze rates of growth/decay. Euler’s number is also an irrational number containing infinite decimal places.
  • Infinity: Infinity cannot be characterized with a number. It is rather an abstract concept signifying something that never ends. Infinity can travel in both positive and negative directions. It is generally used in algorithms to compare a provided value to another absolute maximum or minimum value.
  • Not a number (NaN): NaN, is not a mathematical idea. It was invented in the field of computers to signify non-numeric values. It is often used while comparing inputs to numbers and identifying if an input was supposed to be numeric but got distorted with other characters. NaN was introduced in Python 3.5.

# importing the module in the program import math
print (math.pi)
>>> 3.141592653589793 
# Code to calculate a circle’s circumference
r=3
circumference = 2 * math.pi * r
print (f" The circle’s Circumference = 2 * {math.pi:.4} * {r} = {circumference:.4}") >>> ’ The circle’s Circumference = 2 * 3.142 * 3 = 18.85’ 
Print (math.tau)
>>> 6.283185307179586 
# Code to calculate a circle’s circumference using Tau
r=3
circumference = math.tau * r
print (f" The circle’s Circumference = {math.tau:.4} * {r} = {circumference:.4}") >>> ’ The circle’s Circumference = 6.283 * 3 = 18.85’ 
# Euler’s Number Print(math.e)
>>> 2.718281828459045 
Print (f"Positive Infinity = {math.inf}") >>> ’Positive Infinity = inf’
Print (f"Negative Infinity = {-math.inf}") >>> ’Negative Infinity = -inf’ 
float("inf") == math.inf >>>True 
# NaN Print(math.nan) Nan 
# Infinity as a Concept

Arithmetic Functions in Python’s Math Module

The study of natural numbers (Number Theory) usually deals with positive integers. The math module delivers functions that are helpful in the implementation of number theory and representation theory, an associated mathematical field. These functions allow for the calculation of a range of important values, including factorials, logarithms, and many more. One thing to observe here is, all the in-built functions in Python, like factorial() or pow() have a faster execution time when compared to their implementation using looping or recursion. The reason is its underlying C implementation. The in-built functions are also more stable as all disaster and boundary cases are self-implemented. It is therefore considered best practice to use the in-built functions when possible.

Finding Nearly Identical Numbers using Python

  • Relative tolerance, or rel_tol, is defined as the maximum difference for being judged “close” to the magnitude of the input. This is the tolerance percentage. The default value is 1e-09 or 0.000000001.
  • Absolute tolerance, or abs_tol, is the maximum difference of being considered “close” irrespective of input’s magnitude. The default value is 0.0.
    The isclose() functions returns a Boolean value based on the following calculation:
    abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).
Relative tolerance can be passed to the isclose() function as an argument and can take any defined value. For instance, if rel_tol is set to 0.2, then 6 and 7 are considered close. Like rel_tol, the abs_tol value can also be adjusted as needed. Values are considered close when the difference between input values is less than or equal to the absolute tolerance value. Let’s go through the implementation of the mentioned concepts:

# Implementing Factorial using ‘For’ loop 
def fact_loop(num):
       if num < 0:
              return 0
       if num == 0:
              return 1
       factorial = 1

          for i in range(1, num + 1):
             factorial = factorial * i
       return factorial

fact_loop(7)
>>> 5040

#Implementing the isclose() function 
math.isclose(6, 7) >>> False 
math.isclose(6.999999999, 7) >>> True 
#Implementing isclose() with relative tolerance 
math.isclose(6, 7, rel_tol=0.2) >>> True 
#Implementing isclose() with absolute tolerance 
math.isclose(6, 7, abs_tol=1.0) >>> True
math.isclose(6, 7, abs_tol=0.2) >>> False 

Logarithms with Python

Mathematical and Statistical Programming often revolves around calculation of growth, decay, or deviations. These traits are majorly calculated using Log functions.
  • Calculating Natural Log in Python:
    The log() function computes the logarithm of a number to the base of the Euler’s number, i.e., mathematical constant e. Like the exponential function, natural log also uses the constant e, that we discussed in the previous section.
  • Understanding log2() and log10(): The Python math module also provides two separate functions that let you calculate the log values to the base of 2 and 10. log2() is used to calculate the log value to the base 2. log10() is used to calculate the log value to the base 10.

#Implementing Natural Log in Python 
math.log(4)
>>> 1.3862943611198906 
math.log(3.4) >>>1.2237754316221157 
#Checking Log for a Negative Number 
math.log(-3)
>>> Traceback (most recent call last): >>> File "<stdin>", line 1, in <module> >>> ValueError: math domain error 
# Implementing Log with different base values (The second argument is the base): math.log(math.pi, 2)
>>> 1.651496129472319
math.log(math.pi, 5) 
>>> 0.711260668712669 
# Implementing Log to Bases 2 and 10 
math.log2(math.pi)
>>> 1.6514961294723187 math.log(math.pi, 2)
>>> 1.651496129472319 
math.log10(math.pi) 
>>> 0.4971498726941338 math.log(math.pi, 10)
>>> 0.4971498726941338 

Other Mathematical Functions using Python

  • i. Determine Trigonometric Values: The relationship between angles and the sides of a triangle, most commonly the right-angled triangles are studied in Trigonometry. The math module provides very useful functions for performing trigonometric calculations.
  • ii. You can calculate the sine value of an angle with math.sin(), the cosine value with math.cos(), and the tangent value with math.tan(). The math module also provides functions to calculate arc sine with math.asin(), arc cosine with math.acos(), and arc tangent with math.atan(). Finally, you can calculate the hypotenuse of a triangle using math.hypot().
  • iii. The comb(n, k) function returns the number of ways to choose k items from n items without enabling repetition and not in any order.
  • iv. The perm(n, k) function returns the number of permutations to select k items from n items without repetition but in a specified order.
  • v. The isqrt() function returns the square root value of a non-negative integer input.
  • vi. The prod() function evaluates the product of all elements in the input data type. This approach can take iterables such as arrays, lists, or tuples as its input.
  • vii. The dist() function returns the Euclidean distance between two points p and q, each given as a succession of coordinates. Note: The given two points should belong to the same dimension.
  • viii. The hypot() function can handle more than two dimensions.

#Implementing Trigonometric Functions in Python 
a = math.pi/8 b =3
c= 4 
# the value of sine of pi/8 print (math.sin(a))
>>> 0.382683432365 
# the value of cosine of pi/8 print (math.cos(a))
>>> 0.923879532511 
# returning the value of tangent of pi/8 print (math.tan(a)) 
>>> 0.414213562373 
# Calculating Hypotenuse of 3 and 4 print (math.hypot(b,c))
>>> 5.0 
# Implementing Permutations and Combinations 
n =7
k=5
print (math.comb(n, k)) >>> 21 
n = 10
k=2
print (math.perm(n, k)) >>> 90 
#Implementing Square Roots and Product Functions 
print(math.sqrt(4)) >>> 2 
arr = [1, 2, 3, 4, 5] print (math.prod(arr)) >>> 120 
# Calculating the Euclidean Distance 
p = [3]
q = [1]
print (math.dist(p, q)) >>> 2.0 
# Calculating the Hypotenuse 
perpendicular = 10
base = 5 print(math.hypot(perpendicular, base)) >>> 11.180339887498949 

The Way Forward

Python as a language, has grown to become popular among AI Developers, given all the perks of the language. The trend of learning AI and implementing it for the betterment of the software industry is upward growing and our focus will continue to work in this area. In the next few chapters, we will walk through Python constructs and functional programming techniques that form the basis of AI coding. We will also dive deep into Statistics and ways of programming for Statistical Modelling in Python. AI is a buzz word that every programmer in the present era wants to enable. We have chosen Python to be our route to reaching the heights of building intelligent applications.

Coming Up...

  • 1. Constructs, Looping and Functional Programming
  • 2. Object Oriented Programming with Python
  • 3. Statistics with Python