How to Use Python For AI & ML?

Society of AI
10 min readSep 22, 2020

Python Basics

What is Python?

Python is an object oriented , interpreted, high-level programming language with dynamic semantics.It was introduced by Guido van Rossum, and released in 1991.

Python is the most popular programming language because of its simplicity, powerful libraries, and readability.Python has a simple syntax, is readable, and has great community support.

Python is the very first step in many new age technologies like Machine Learning, Data Science, Deep Learning and Artificial Intelligence. However It is also used in Web Development, Game Development, Desktop GUI, Web Scraping Applications, Business Applications ,cad Applications, Embedded Applications etc.

There are some interesting Applications of python.

● Creating Machine Learning Algorithms

● Build Neural Networks

● Analyze complex Data sets

● Build chatbots

● Work on Raspberry pi robot

● Manage server-side web applications

● Work on Language processing

Working with python

To work with python we have to first install python in the system. Let’s understand some basic concepts in the python.

● Printing the first sentence in python.

Comments

❏ Comments used to explain python code.

❏ In python we can use “#” symbol to explain single line comment and “””…”””(triple quotes) to explain multiline comments.

Variables

❏We can use variables in python is easy.we do not need to declare variables.Instead we can choose a name and assign the value directly.Instead we can pick a name and immediately assign the value.

Strings

❏ In python we can define strings by using single quotes or double quotes.

Python Functions and Packages

Python Functions

Types of functions in python. (1)UserDefined Functions

(2)Built-In Functions

UserDefined Functions

❏ In python def keyword is used to declare the function and followed by the function name and parentheses(()).In parenthesis we can input parameters or arguments and also we can define parameters inside these parenthesis.

❏ The code block within every function begins with a colon (:) and gets indented.

❏ The return [expression] statement exits a function and optionally returns an expression to the caller. A return statement with no arguments is the same as returning None.

❏ We can call the function by function name followed by parenthesis.

Built-In Functions

❏ The built-in functions of Python are defined as the functions in which functionality is predefined.

❏ Python provides many built-in functions.Some examples of built-in functions are listed below.

abs():returns absolute value of a number

len():This function returns an object’s length (the number of items): In this function we can pass sequences such as string,bytes,tuple,list or range or a collection such as a dictionary, set, or frozen set.

input():Input function allows user input.

Python Packages

A Python package refers to a python module(s) directory. Python package is actually a directory with python files and a file with the name with init.py.

Steps For creating and importing package in Python:

● Create a new folder with any name.Example: G:\My_App

● Inside a created folder create subfolder with any name: Example: G:\My_App\mypackage

● Create an empty __init__.py file in the mypackage(subfolder) folder.

○ __init__.py serves two purposes.

■ The Python interpreter recognizes a folder as the package if it contains __init__.py file.

■ __init__.py exposes specified resources from its modules to be imported.

● Using any python editor create any modules.Example:

Importing a module from python

Working with Data Structures,Arrays,Vectors and Data Frames

Data Structures In Python

● Python provides two types of data structure.

○ Built-in data structures which enable us to store and access data.These data structures are called List,Dictionary,Tuple and Set.

○ Python also helps us to build our own data Structures. Stack, queue, Tree, Linked List etc are the most common data structures as in other programming languages.

Built-In Data Structure in python

(1)List:

● Lists are used to store data of different data types in a sequential manner.List is a collection which is ordered and changeable. List allows duplicate members.In Python lists are written with square brackets.

● Addresses are assigned to each element of the list which is called an index. The index value begins at 0 and continues until the last element called the positive index.There is also negative indexing which starts from -1 enabling you to access elements from the last to first.

● Declaring a list:

(2)Dictionary:

● A dictionary is comparable to hash or maps in other languages like c,c++,java. It consists of key value pairs. The value accessed by a unique key in the dictionary.In Python dictionaries are written within curly brackets.

● Dictionary is a collection unordered, changeable and indexed. No duplicate members.

● Declaring a Dictionary:

ML,AI,DS are the keys and 1,2,3 are their values respectively.(3)Tuple:

● A tuple is a collection which is ordered and unchangeable.

● Python tuples work exactly like Python lists except they are immutable, i.e. they can’t be changed in place.

● In Python tuples are written with round brackets.

● Declaring Tuple:

(4)Set:

● Sets are the unordered collections of unique objects.In Python sets are written with curly brackets.

● Declaring Set:

Arrays in Python

● An array is simply a data structure which can hold a group of elements.And these elements are of same data type.Creating an Array in python:

○ In python,Arrays is created after importing the array module as follows.

Syntax:a=arr.array(data type,value list)

Vectors in Python

● A vector is a tuple of one or more values called scalars.

● Vectors are built from components, which are ordinary numbersWe can consider a vector as a set of numbersVectors are often represented using the lower case character “v.”

● . A NumPy array can be created from a list of numbers. We define a vector with the length of 3 and the integer values 1 , 2 and 3 as example below.

Dataframes in python

● Dataframe is a powerful data structure that makes data manipulation and analysis easy.

● Dataframe in python comes with pandas library.Is a two-dimensional data structure, i.e. data is aligned in a tabular form in rows and columns.

● pandas dataframe’s size is mutable

Example:

Jupyter Notebook-Installation and Function

● Basically,Jupyter Notebook is an open-source web application that enables us to create and share documents that contain live code, equations, visualizations and narrative text.

● Jupyter supports 3 core programming languages that are Julia, Python, and R.

● Jupyter Notebook is saved as .ipynb extension format. Jupyter (.ipynb) also allows converting the document into standard formats like HTML, presentation slides, PDF, Markdown, Python. Jupyter notebook is commonly used in the data Science domain.

Installation

Following are the steps for installing the jupyter notebook using python.

● Open the command prompt (cmd)..

● Then open the directory where python is installed. If the environment variable is set for python then there is no need to go to the python directory.

● We can install a jupyter notebook with pip command.But for this pip command should be upgraded..

● After opening cmd use command “pip install jupyter”.

Command

● After installing the jupyter notebook we can open it using the following command.

“jupyter notebook”

Command

● After this step, it will open the Jupyter notebook in our default browser.

Function

● There are mainly two types of cell in jupyter notebook.(1)Markdown Cell (2) Code Cell

● A Markdown cell contains rich text. In addition to classic formatting options like bold or italics, we can also add links, images, HTML elements, LaTeX mathematical equations, and many more.

● A code cell that contains code to be executed by the kernel. The programming language corresponds to the kernel’s language.

● Markdown Cell

● Code Cell:

Pandas,NumPy,Matplotlib.Seaborn

Pandas

● Pandas is an open-source python Library which provides high-performance data manipulation and analysis tools using its powerful data structures.

● It is built on the Numpy package and its key data structure of pandas library is called the DataFrame.

● We can install pandas library of python using following command.:”pip install pandas”

● To use the functions pandas library we have to import it as shown below.

● We can create a data frame using a csv file,excel file etc.

Pandas provides a useful method, named read_csv() to read the contents of the CSV file into a DataFrame.

● We can use df.head(n) to get the first n rows or df.tail(n) to print the last n rows.

Numpy

● NumPy is the most important python library used for working with arrays.

● It has functions for working in the domain of linear algebra,fourier transform, and matrices.

● We can install a numpy library using the following command. :”pip install numpy”

● To use numpy we have to import numpy library as shown follow.

● Numpy provides a large number of various mathematical operations.Also numpy provides standard trigonometric functions,functions for arithmetic operations,handling complex numbers etc.

● Some example:

Matplotlib

● Matplotlib.pyplot is a most popular visualization library used for 2D graphics in python programming language.It can be used in python scripts,shell,web application servers and other graphical user interface toolkits.

● There are various plots that can be generated using matplotlib .Some of them are listed below:

○ Bar Graph

○ Histogram

○ Scatter Plot

○ Area Plot

○ Pie chart

○ Box plot

We can install matplotlib library using the following command.:”pip install matplotlib”

Command

Some Example:

Seaborn

● The Seaborn library of python is used to ease the challenging task of data visualization and it is based on Matplotlib.

● Seaborn library provides a high-level interface for drawing attractive and informative statistical graphics

● The main idea of seaborn is that it provides high-level commands to create a variety of plot types useful for statistical data exploration, and even some statistical model fitting.

● We can install seaborn using following command:”pip install seaborn”

Command

● We can import the seaborn library using the following command as shown below.

● There are some dependencies for seaborn are:

○ Numpy

○ Scipy

○ Matplotlib

○ Pandas

As like matplotlib, seaborn provides various plots to visualize the data(information).

Some examples of it are as follows.

Instance

If you liked the story and want to appreciate us you can clap as much as you can. Appreciate our work by your constructive comment and also you can connect to us on….

Youtube: https://www.youtube.com/channel/SocietyOFAI

LinkedIn : https://www.linkedin.com/company/society-of-ai

Facebook: https://www.facebook.com/societyofai/

Website : https://www.societyofai.in/

--

--

Society of AI

Society of AI has an vision to educate people how Artificial Intelligence can change their life!