Computer Programming

Getting started with Python | Machine Learning Libraries

Prerequisites: This is in continuation with the first part Python tutorial for Beginners

In this post we’ll delve deeper into the Python language’s concepts, structure and its syntax. We’ll learn about more complex parts of the language. In the later section, we’ll introduce Python’s most popular Machine Learning libraries. So let’s get started with the portion left from the previous post.

Decision Making

Decision making is predicting the conditions occurring while execution of the program and specifying actions taken according to those conditions. It is useful in situations where you have several inputs or expressions and you want different outputs for those inputs. Decision structures evaluate several expressions which produce TRUE or FALSE (boolean value) as outcome. You determine which action to take and which statements to execute based on the outcome.

#Code
a = 10 
if a == 10: 	
  print(a) 
elif a > 10: 	
  print("Greater") 
else: 	
  print("Smaller")  

Output

#Print Output
10

Note: People coming from languages like C or C++ might find the use of elif unusual. But it’s basically a shorter form of ‘else if’.


Loop Control

As we know code statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. But sometimes a situation may arise, when you need to execute a block of code several number of times before executing the next block.

A loop control instruction allows us to execute a portion of code either a specified number of times or until a particular condition is satisfied. Python language provide us with two methods for repeating a part of a program:

  • while loop
#Loop
i = 0 
while i<5: 	
  print(i) 	
  i=i+1 

Output

#Print Output
0 
1 
2 
3 
4 
  • for loop
#Loop
for i in range(0, 5):	
  print(i)

Output

#Print Output
0
1
2
3
4

Loop control statements[1]

Loop control statements change the normal execution of the loop. We often come across situations where we want to exit the loop instantly before the next iteration or skip some part of the code for particular iteration. Loop control statements come for rescue, in such situations.

Let us go through the loop control statements briefly:

Python

Also read: How to crawl Instagram data using Python

Python Standard Library Methods

Python provide us with a large set of useful library methods which comes in very handy while performing redundant tasks like “String manipulation” or “Complex mathematical calculations”. Let’s go through the most commonly used methods.

Math library methods
#Math Functions
import math as m  
print(m.floor(5.6)) 
5 
print(m.log(10)) 
2.3025 
  • abs
#Math Functions
abs(-4/3) 
1.33333333 
  • min
#Math Functions
min(1, 2, 3) 
1 
min('b', 'c', 'a') 
a 
  • max
#Math Functions
max(1, 2, 3) 
3 
max('b', 'c', 'a') 
c 
  • sorted
#Math Functions
a = [2 , 10, 30] 
print(sorted(a)) 
[2, 10, 30] 
  • sum
#Math Functions
a = [2 , 10, 30] 
print(sum(a)) 
42 
String methods
#String Manipulation
str = "Hello" 
print(len(str)) 
6

print(str.lower()) 
hello 

print(str.upper()) 
HELLO

str = " cricket " 
print(str.strip()) #removes white spaces
'cricket'

Note: You can also concatenate methods

#String Manipulation
print(str.strip().replace("cr", 'w'))  
wicket		   #replaces substring/literal with substring/literal 
 
str = "Hello World" 
print(str.split(' ')) 
['Hello', 'World'] 
 
a = ['Hello', 'World'] 
print(' '.join(a)) 
Hello World 

Quick Tip: Have you noticed that the original string str didn’t change even after performing the operations like split, lower & upper. This is because we didn’t assign it the value. You’ve to explicitly assign the value to the variables (using ‘=’ assignment operator) in order for change to reflect.

Python modules[2]

A module allows you to logically organise your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.

To use a module: import module_name

Module test.py

#Defining Module
def college(): 
	print("IIT")

Use Module

#Import
import test 
test.college() 

Output

#Print Statement
IIT

OOP in Python

OOP — Object Oriented Programming is is a computer programming paradigm that organises software design around data, and objects, rather than functions and logic. OOP consists of objects which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures or methods.
A feature of objects is that an object’s own procedures can access and often modify the data fields of itself. Objects have a notion of self (similar to this in Java). In OOP, computer programs are designed by making them out of objects that interact with one another.[3]

#file_name.py
class Person: 
  
  institution = 'College'  # class variable    
	
  def __init__(self, college, location):    #constructor 
    self.location = location                #instance variables 
    self.college = college 

  def set_college(self, college): 
   	self.college = college 
	
  def set_location(self, location):      
    self.location = location 
 	
  def print(self): 
    print("Studies in {0} at {1}".format(self.college, self.location)) 
 
def main(): 
    person = Person("IIT", "Delhi") 
    print("{0}:".format(Person.institution))
    person.print() 

if __name__ == "__main__":            #Program starts here 
    main() 

Note: Variables with double underscores on both sides are special variables, like __init__

To run in shell: python3 file_name

Output

#Print Statement
College:
Studies in IIT at Delhi

Python Machine Learning Libraries

Python has several ML libraries but major libraries that are used are the following:

  • Numpy: NumPy is a python library used for working with arrays. It also has functions for working in domain of linear algebra, Fourier transform, and matrices. Usage:
pip install numpy 
import numpy as np 
  • Scikit-Learn: Scikit-learn is a Python module for machine learning built on top of SciPy and is distributed under the 3-Clause BSD license. Usage:
pip install scikit-learn 
from sklearn.model_selection import train_test.split 
  • Pandas: Provides key data structure like Dataframe. It also provide support for reading/writing data in different formats. Usage:
pip install pandas 
import pandas as pd 
  • Matplotlib: Matplotlib is a comprehensive library for creating static, animated, and interactive visualisations in Python. Usage:
pip install matplotlib 
import matplotlib.pyplot as plt

In the future posts, we’ll learn about how to use these libraries for performing basic tasks required in Data Sciences.


Happy Programming!

Footnotes

[1,2] Python – Tutorialspoint

[3] Object-oriented programming – Wikipedia