Python for Deep Learning and Machine Learning.
Learn deep learning with Python from scratch! Start your journey with hands-on coding exercises and overcome your Python limitations for deep learning.
This article is for those who want to learn about deep learning and gain hands-on experience in this area but are limited by Python. It will serve as a starting point to help them overcome this hurdle.
Before you go ahead please click on the button (play in Colab) copy the codes given in tutorial and have fun.
Introduction to IDE: Integrated Development Environment
There are multiple IDEs available for writing Python code. Some examples include JetBrains' PyCharm, Kaggle Notebooks, and Google Colab. All these IDEs work perfectly, but Kaggle Notebooks and Google Colab are web-based, so you don't have to install them on your computer. You can simply click and start coding. Deep learning requires a GPU for faster calculations, and this problem is also solved by Kaggle and Google Colab, which offer free GPU access for training.
Python basics
Python is a high-level language, which means it is human-readable and easy to code in. For example:
a = 5
b = 6
# if you want to print the addition just write
print(a+b)
Did you notice something? I have written statements with #
. In Python, you can write anything after #
and it will not be executed. We do this because comments help explain the code. Now, let's ask for input from the user.
# take input from user
a = input('give me a number or any string:' )
type(a) # 'type' will tell us the type of the input ('a') (there are many types like: string(sentence), integer, or real numner (float) )
When you take input from the user, the type of input is str
(which means string). But what if you are making a calculator app? In that case, you need integers (int
) like 1, 2, 3, or floats (numbers with decimals like 1.2). So how do you do it? Let's see.
# we have seen example above of addition now lets do something more
# take input from user use 'input' command:
a = float(input('give me a number: ')) # the input will be a sentence or we say it string so we add float (like 1.0 or 1.8788)
b = float(input('give me a number: ')) # the input will be a sentence or we say it string so we add float (like 1.0 or 1.8788) (same as above)
# now add them and
print('the addition of a and b is: ', a+b)
So what did we change here? We just added float
before the input
command. This changes the input type from str
to float
. Just like addition, you can perform almost every mathematical operation in Python, such as subtraction (-
), division (/
), multiplication (*
), etc.
Loops in Python
- When we need to do repetitive work, we use a Python feature called a
loop
. There are multiple types of loops:for
,while
, anddo while
. In this chapter, we will learn about the most commonly used loop in deep learning and data science: thefor loop
. - Sometimes we need to define certain conditions in Python. Similar to the English language, we can use
if
,elif
(short for "else if"), andelse
(for everything not covered byif
andelif
). It's simple, right? π
Let's first explore loops. We will cover the two most commonly used loops: for
and while
.
for loop
If you want to print numbers from 1 to 10 then you will not write like:
print(1)
print(2)
print(3)
# and so on ....
But this does not make sense, you will need to think something else, let's see how to use for loop to print the numbers from 1 to 10.
Now the code will look like this:
# lets code the above diagram
a = 1 # step 1 done
print(a)
for i in range(9):
a = a+1 # increase a by 1
# you can also write 'a += 1' both are same but this one look coolπ right?
print(a)
print('DONE π')
while loop
While loop is a conditional loop, for example keep eating until your stomach is full. Below is a coding example of while loop.
# lets code the above diagram
a = 1 # step 1 done
print(a)
i = 0
while i < 9:
a = a + 1 # increase a by 1
# you can also write 'a += 1' both are same but this one look coolπ right?
print(a)
i += 1
print('DONE π')
Conditional statements in Python
There are always conditions in life. For example, if you drink alcohol, you will have health problems in the long run. If you drink too much alcohol, you will get sick soon. Otherwise, if you drink water, you will be fine. This might be a silly example, and the statements may not make much sense, but sitting in this bar at this moment, itβs the best I can come up with. :et's see how to code this situation in python:
# Take input from the user
user_input = input("Do you drink alcohol? (yes or no): ").strip().lower()
if user_input == "yes":
amount_input = input("Do you drink too much alcohol? (yes or no): ").strip().lower()
if amount_input == "yes":
print("You will be sick soon.")
else:
print("You will have health problems in the longer run.")
else:
print("You drink water and will be fine soon.")
While working with data you will use mostly for loop and conditional statements (if, elif and else).
Function
Let me ask a question. Suppose you have to clean the floor. Will you prefer to make a broom first and then clean the floor?
The most expected answer is: NO
Your answer will be: We will go to a shop, buy a broom, and use it for cleaning. In Python, there are many shops; some are free, and some are paid (or private).
Here, the shop is a library, and the broom is a function. In our case, we will make a broom (i.e., a function) once, and then we will use it again and again.
In our case, we will check the shop (library) first. If it is not available, then we will make a broom (in our case, a function) once, and then we will use it again and again like this.
Here is the function for calculator
def calculator():
# Display the options to the user
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4): ")
# Check if the choice is one of the four options
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Perform the corresponding operation
if choice == '1':
print(f"{num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"{num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"{num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 != 0:
print(f"{num1} / {num2} = {num1 / num2}")
else:
print("Error! Division by zero is not allowed.")
else:
print("Invalid input. Please enter a number between 1 and 4.")
# Call the calculator function
calculator()
This code works perfectly, but you will notice something its too long and for a beginner it's bit long because there are many operations this function does.
Class
Now suppose you have to clean the entire house, not just the floor. You need different tools: a broom for the floor, a duster for the furniture, and a mop for the tiles. Will you prefer to make each tool individually every time you clean?
The most expected answer is: NOOOOO
Your answer will be: We will go to a shop, buy all the necessary cleaning tools, and use them for cleaning.
A class groups together different functions (methods) and variables (attributes) that work together to perform a task. In our case, the class is like a cleaning kit that contains a broom, a duster, and a mop. You create this cleaning kit (i.e., a class) once, and then you can use it again and again to clean your house.
class Calculator:
def __init__(self):
self.operations = {
'1': self.add,
'2': self.subtract,
'3': self.multiply,
'4': self.divide
}
def add(self, num1, num2):
return num1 + num2
def subtract(self, num1, num2):
return num1 - num2
def multiply(self, num1, num2):
return num1 * num2
def divide(self, num1, num2):
if num2 != 0:
return num1 / num2
else:
return "Error! Division by zero is not allowed."
def run(self):
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice(1/2/3/4): ")
if choice in self.operations:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = self.operations[choice](num1, num2)
print(f"The result is: {result}")
else:
print("Invalid input. Please enter a number between 1 and 4.")
# Create an instance of the Calculator class and run it
calc = Calculator()
calc.run()
In this implementation:
- The
Calculator
class encapsulates the calculator's operations as methods. - The
__init__
method initializes a dictionary mapping choices to corresponding methods. - The
run
method handles user interaction, selecting the appropriate method based on user input and displaying the result.
This class-based approach allows for easier extension and reuse of the calculator functionality.
That's it, if you practice these topics for few days π€, you will become better and you can start with machine learning and deep learning.
Happy Coding π