Python is a popular programming language that is reliable, flexible, easy to learn, free to use on all operating systems, and supported by both a strong developer community and many free libraries (Libraries are pre-written codes that developers use to solve common programming tasks).
Python supports all manners of development, including web applications, web services, desktop apps, scripting, data science, scientific computing, and Jupyter notebooks. Python is a language used by many universities, scientists, casual developers, and professional developers alike.
Python is a high level programming Language. This simply means that the commands used in Python are understandable by humans. These commands are then converted into machine code by using an interpreter.
You can learn more about the language on Python Official Site
Why use Python for learning AI ?¶
Python is more often than not the top most choice for Machine Learning Applications. The main reason for this is the amount of simplicity, consistency and stability Python code can bring to AI workflows. The simplest of AI workflows require extensive mathematical functions running in the background. The wide variety of stable and user friendly libraries like Scikit-Learn (used for handling basic Machine Learning algorithms like clustering, linear and logistic regressions, etc.), Matplotlib (used for creating bar charts, histograms and other data visualizations) etc provide great support for building scalable and efficient code. We shall cover more on these in the later sessions.
Another reason why python is easy to use is that you do not need to declare variable types unlike other programming languages. A variable is the name you give to a value you want to store and use later.
For example, let’s say you would like to create a variable called money to store some numerical value of money, in Python you would only need to assign a value to the word ‘money’ to use it, in other programming languages, this requires a variable type declaration before use.
Now that we have understood why we have chosen Python as our programming language, let’s get started with basic commands we will come across frequently in our AI journey!
Comments¶
Many of the examples in this notebook include comments. Comments in Python start with the hash character, #, and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within the quotation marks “” or ‘’ of a String itself. A hash character between quotation marks is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.
You can learn more about the comments in python on Python Official Site
# This is the first comment
number = 1 # and this is the second comment
# ... and now a third!
'#Meanwhile, this is not a comment'
Welcome = "Hi welcome to your first Python Program!"
print(Welcome) #This is the 'print' Command
Course ='welcome to the course AI for Manufacturing !'
print(Course) Data Types in Python¶
Although we do not have to declare a type for python variables, a value does have a type. These are data types we will be covering in this Notebook:¶
Boolean
Numbers
Strings
Lists
Tuples
Dictionary
You can learn more about the data types in python on Python Official Site
BOOLEAN¶
x = True #Boolean type, only has true or false, think of an on-off switch
print (x)Numbers¶
The Python interpreter can act as a simple calculator: type an expression at it outputs the value.
Expression syntax is straightforward: the operators +, -, * and / work just like in most other programming languages (such as Pascal or C); parentheses (()) can be used for grouping and order or precedence. For example:
# Integer example
x = 5
y = 10
z = x + y
print(z) # Output: 15
A floating-point number, or simply a float, is a data type that represents decimal numbers with a fractional part. Floats are used to represent real numbers, including numbers with decimal points, such as 3.14 or -2.5.
# Floating-point number example
a = 3.14
b = 2.5
c = a * b
print(c) # Output: 7.85
Arithmetic Operations¶
# Get input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
We then add these two numbers using the + operator and store the result in a variable called sum
# Calculate the sum of the two numbers
sum = num1 + num2
# Display the result
print("The sum is:", sum)Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you can use the // operator; to calculate the remainder you can use %:
13 // 5 # Floor division (division which uses the '//' operator) discards the fractional part.13 % 5 # The '%' operator returns the remainder of the division.Use the ** operator to calculate powers:
4**2 # This will print the square of '6'
The equal sign (=) is used for assigning values to a variable
w = 50
t =12
w * tSTRING¶
Single (’ ') or double (" ") quotes are used to separate a group of characters into a string. One of the fundamental data types in Python, strings are used to represent text.
# String example
greeting = "Hello, world!"
name = "Alice"
message = greeting + " My name is " + name + "."
print(message) # Output: Hello, world! My name is Alice.LIST¶
A list is an ordered sequence of items, meaning items in the list are stored in the order of which it was input. Remember, a list may contain different types of items. To define a list, you must put values separated with commas in square brackets.
Students=['Vicky',25,'Jun Kai',12] # Here the name of the student is stored with their respective roll numbers
type(Students)Lists are mutable(can be changed or updated) unlike Strings. Like strings (and all other built-in sequence types), lists can be indexed and sliced:
Students[0] # Indexing returns the item.
Students[-1]Students[:]Lists also support concatenation with the + operator:
Students + ['Gabrielle',13, 'Cao', 47]As mentioned at the start, unlike strings, which are immutable, lists are a mutable type, which means you can change any value in the list:
Students=['Vicky',25,'Jun Kai',12] #Something is wrong here....
#Vicky's roll number is 10Students[1]=10 #correcting the wrong value
StudentsUse the list’s append() method to add new items to the end of the list:
Students.append('Isaac') #Note you can only add one argument at a time
Students
Students.append(15) #Adding the second argument
Students#Replace some values
Students[2:5]=['Ming Ian', 21]
Students# Now remove them.
Students[2:5] = []
StudentsTuples¶
A tuple is an ordered sequence of items. You might be wondering now then how is it different from lists?
The main differences between tuples and lists are :
Tuples cannot be modified element wise like lists (Objects which cannot be modified in such a manner are described as immutable objects. Tuples use parentheses, whereas lists use square brackets.
Students_new = ('Susan',25,'John',12) #Tuple being defined
print(Students_new)Students_new[1]= '26'
print(Students_new) #Notice the error which shows up in the outputSET¶
Sets are used to store multiple items in a single variable.A set is a collection which is unordered, unchangeable*, and unindexed.
t = {"apple", "banana", "cherry"}
print(t)t = {"apple", "banana", "cherry", "apple"}
print(t)t = {"apple", "banana", "cherry", True, 1, 2}
print(t)True and 1 is considered the same value
Dictionary¶
Dictionary is an unordered collection of key-value pairs.
In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type.
A Dictionary in Python works similar to the Dictionary in a real world. Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but the key-values can be repeated and be of any type.
You might want to use a Dictionary over Tuples as it is quicker to access data if the data source is substantially large as finding data in Tuples requires looping which we will go through later
Time={'Day':'Monday','Date':[1,2,3]}
type(Time)
Time['Day'] #Using key to display respective valueTime['Monday'] #Reverse cannot be done, i.e using value one cannot display keyFlow Control in Python¶
In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
For more infortmation click here
IF-ELSE STATEMENT¶
Depending on whether a condition is True or False, you can run several blocks of code using the if-else statement, which is a conditional statement. It gives you a mechanism to base judgements in your code on specific circumstances.
# Get input from the user
num = int(input("Enter a number: "))# Check if the number is even or odd
if num % 2 == 0:
print(num, "is an even number.")
else:
print(num, "is an odd number.")a = 7
#If a is greater than the value 6, execute the statement below it
if a > 6:
print(f"{a} is good")LOOP STATEMENTS¶
While Loop
A while loop in python iterates till its condition becomes False. In other words, it executes the statements under itself while the condition it takes is True. When the program control reaches the while loop, the condition is checked. If the condition is true, the block of code under it is executed. Remember to indent all statements under the loop equally. After that, the condition is checked again. This continues until the condition becomes false. Then, the first statement, if any, after the loop is executed.
a = 0 #Assign the value 0 to the variable a
#The condition of this loop is to run *while* the value of a is LESS THAN 9
while(a < 9):
print(a) #This print is to demonstrate how the condition functions in a loop using an number increment
a += 1
print("Loop has ended at 8, can you tell why?")For Loop¶
A for loop does the same thing as the example in the while loop, but makes it simpler to write and understand.
# Get input from the user
num = int(input("Enter a positive integer: "))
# Initialize the sum to 0
sum = 0
# Use a for loop to iterate from 1 to num (inclusive)
# The range() function generates a sequence of numbers
# starting from 1 and ending at num+1
for i in range(1, num+1):
# Add the current number to the sum
sum += i
# Display the result
print("The sum of numbers from 1 to", num, "is:", sum)Functions in Python¶
In programming we often come across situations where a particular block of code needs to be repeated or reused. Thus the concept of functions comes into play. A function is basically a block of code which performs a specific task.
Functions make the entire code look more organised and manageable. They allow reusability of code and organise the program into small modular chunks. For more information click here
def name_of_function(parameter):
statementsdef sum(x, y): #This example shows a function which can add two numbers x & y
s = x+y
return snum_1 = 27
num_2 = 23
print (sum(num_1,num_2)) #Notice how the two numbers are passed into the 'sum' functionWrite a function in Python to convert celsius Scale to Fahrenheit Scale
#Write your answer hereNumPy¶
NumPy arrays in python are basically grids of values of the same data type. Each element of a NumPy array has a non-negative index associated with it. When dealing with arrays, we come across a useful term called shape which gives the size of the array along each dimension. For more information click here
#Numpy is a popular package for scientific and mathematical computing in Python.
#In the example below we are adding two 2*2 matrices
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(a+b)import numpy as np #importing numpy package
a = np.array([1,2,3]) #initializing an array with the elements given in the brackets
print (a)#Creating an array with more than one dimension
b = np.array([[1, 2], [3, 4]])
print (b)#let's check the shape of the arrays created so far
print("Shape of array 'a' is:",(a.shape))
print("Shape of array 'b' is:",(b.shape))#accessing elements of the array using the index
print(a[0], a[1], a[2])
print(b[0][0]) #printing the first row first, first column element#using the arange function to create an array
c=np.arange(4) #prints the first four elements as 0 onwards by default
print (c)
d=np.arange(1,7)#specifying start point and end point
print (d)# Create the following array with given shape (3, 4). Name the array 'new'
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
new = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print (new)# Slicing is being used to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; new_sub is the following array of shape (2, 2):
new_sub = new[:2, 1:3]
print(new_sub)Array Indexing¶
a = np.array([[1,2], [3, 4], [5, 6]])
#Given the following, this is output of the above, can you see how you would get [1 4 5]?
#For the value of '1' it is at position 0,0 which is the first 'box' and the first 'item' in the 'box'
#For the vlaue of '4' it is at the position of 1,1 which is the second 'box' and the second 'item' in the 'box'
#Can you now figure out how you would get the value of '5'?
print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]"
#The above can also be written as:
# a[0,0] '1'
# a[1,1] '4'
# a[2,0] '5'
# This is an Example of integer array indexing. Look closely can you tell the difference between this statement and the last?
b=(a[[0, 1, 2], [0, 1, 0]]) # Do you now see how array indexing is done and how it relates to the previous statements?
print(b) # Prints "[1 4 5]"
print(b.shape) #Shape is 3# The above example of integer array indexing is equivalent to this:
print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]"
# When using integer array indexing, you can reuse the same
# element from the source array:
print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
# Equivalent to the previous integer array indexing example
print(np.array([a[0, 1], a[0, 1]])) # Prints "[2 2]"# Create an array of indices
b = np.array([1, 0, 1])
print(b)
# Select one element from each row of a using the indices in b
print(a[np.arange(3), b])# Mutate one element from each row of a using the indices in b
a[np.arange(3), b] += 10
print(a)NumPy DataTypes¶
roll_no = np.array([23, 46]) # Let numpy choose the datatype
print(roll_no.dtype) # Prints "int64"
marks = np.array([65.5, 88.0]) # Let numpy choose the datatype
print(marks.dtype) x = np.array([1, 2], dtype=np.int64) # Force a particular datatype
print(x.dtype) # Prints "int64"Array Mathematics ¶
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
# Elementwise sum; both produce the array
# [[ 6.0 8.0]
# [10.0 12.0]]
print(x + y)
print(np.add(x, y))X = np.array([[13.0,7.0],[4.0,47.0]], dtype=np.float64)
Y = np.array([[16.0,14.0],[1.0,23.0]], dtype=np.float64)
print (X-Y)
print(np.subtract(X, Y))#to perform elementwise multiplication
print(x * y)
print(np.multiply(x, y))#to perform elementwise division
print(x / y)
print(np.divide(x, y))Sorting NumPy Arrays¶
a = np.array([1, 2, 3, 4, 5, 2, 1])
print(a)
np.sort(a) #function for sorting elements in ascending order
print (np.sort(a))
np.flip(np.sort(a)) #function for sorting elements in descending order
print (np.flip(np.sort(a)))np.flip(np.sort(a))[:2] #slicing and sorting
print (np.flip(np.sort(a))[:2])Manipulating NumPy Arrays¶
x=np.arange(12) #creating 12*1 array
print(x)y=x.reshape(6,2) #changing shape from 12*1 to 6*2 array
print(y)Pandas¶
Data Frame
A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns.
DataFrames accepts many different kinds of inputs, if you would like to learn more, feel free to search online or go to pandas’ documentation. For the purpose of this example, we shall demonstrate a useful way you can use DataFrames.For information click here
import pandas as pdd = {
"c": [420, 380, 390],
"t": [50, 40, 45]
}
#load data into a DataFrame object:
df = pd.DataFrame(d)
print(df) #refer to the row index:
print(df.loc[0])#use a list of indexes:
print(df.loc[[0, 1]])d = {
"c": [420, 380, 390],
"t": [50, 40, 45]
}
#load data into a DataFrame object:
df = pd.DataFrame(d,index = ["day1", "day2", "day3"])
print(df) #refer to the named index:
print(df.loc["day2"])Load Files Into a DataFrame If your data sets are stored in a file, Pandas can load them into a DataFrame.
import pandas as pd
df = pd.read_csv('retail_price.csv')
print(df) df.head()matplotlib¶
Matplotlib is a Python 2D plotting library that we can use to produce high quality data visualization. It is highly usable (as you will soon find out), you can create simple and complex graphs with just a few lines of codes!
For more information click here
import matplotlib.pyplot as plt#Create variables for graph (x,y)
x = [i for i in range(10)]
print("Values of X:",x)
y = [2 ** i for i in range(10)]
print("Values of Y:",y)#Things to do here: Add Label and run cell
plt.title('My First Plot')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.plot(x,y)
Scatter plot¶
Scatter plots use a collection of points on a graph to display values from two variables. This allow us to see if there is any relationship or correlation between the two variables.
#Plotting a Scatterplot
plt.scatter(x,y)
plt.show()x = np.random.normal(170, 10, 250)
plt.hist(x)
plt.show() import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.plot(x, y)
plt.grid()
plt.show()These are some basic examples of how matplotlib can be used, the plots, labels, etc can be manipulated and adjusted to be displayed however you would like using functionality provided by matplotlib.
Do you know of any more graphs? Name them below! Go online and look for the types of graphs matplotlib offers
matplotlib’s tutorial website
#Answer hereScikit Learn¶
scikit-learn is an open source machine learning library that supports supervised and unsupervised learning. It also provides various tools for model fitting, data preprocessing, model selection and evaluation, and many other utilities.
Here we will walk through the basics of how to get started with scikit learn and some terminologies you will be coming across in the later sessions. Give the codes below a run through! Don’t worry if you do not understand the exact workings of scikit-learn or a machine learning workflow at present, these codes below just demonstrate everything you have come across in the notebooks so far! In the later sessions we will go through the process together step by step in more detail. For more information click here
#Remove quotes to install scikit-learn, conda for Anaconda and pip if using Python in a different environment.
'''
pip install scikit-learn
#or
conda install scikit-learn
'''#Importing sklearn library
import sklearn
print(sklearn.__version__)#Importing numpy, pandas, matplotlib.pyplot, DecisionTreeClassifier and plot_tree: This portion would look similar to examples you would come across later!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import plot_tree
Dataset loading from Sklearn
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names
target_names = iris.target_names
print("Feature names:", feature_names)
print("Target names:", target_names)
print("\nFirst 10 rows of X:\n", X[:10])from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size = 0.3, random_state = 1
)
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size = 0.4, random_state=1
)
from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
classifier_knn = KNeighborsClassifier(n_neighbors = 3)
classifier_knn.fit(X_train, y_train)
y_pred = classifier_knn.predict(X_test)
# Finding accuracy by comparing actual response values(y_test)with predicted response value(y_pred)
print("Accuracy:", metrics.accuracy_score(y_test, y_pred))
# Providing sample data and the model will make prediction out of that data