AI

Python for Machine Learning (7-day mini-course)

Python for Machine Learning Crash Course.
Learn core Python in 7 days.

Python is an amazing programming language. Not only it is widely used in machine learning projects, you can also find its presence in system tools, web projects, and many others. Having good Python skills can make you work more efficiently because it is famous for its simplicity. You can try out your idea faster. You can also present your idea in a concise code in Python.

As a practitioner, you are not required to know how the language is built, but you should know that the language can help you in various tasks. You can see how concise a Python code can be, and how much the functions from its libraries can do.

In this crash course, you will discover some common Python techniques, from doing the exercises in seven days.

This is a big and important post. You might want to bookmark it.

Let’s get started.

Python for Machine Learning (7-Day Mini-Course)
Photo by David Clode, some rights reserved.

Who Is This Crash-Course For?

Before you get started, let’s make sure you are in the right place.

This course is for developers who may know some programming. Maybe you know another language, or you may be able to write a few lines of code in Python to do something simple.

The lessons in this course do assume a few things about you, such as:

You know your way around basic Python.
You understand the basic programming concepts, such as variables, arrays, loops, and functions.
You can work with Python in command line or inside an IDE.

You do NOT need to be:

A star programmer
A Python expert

This crash course can help you transform from a novice programmer to an expert who can code comfortably in Python.

This crash course assumes you have a working Python 3.7 environment installed. If you need help with your environment, you can follow the step-by-step tutorial here:

How to Set Up Your Python Environment for Machine Learning With Anaconda

Crash-Course Overview

This crash course is broken down into seven lessons.

You could complete one lesson per day (recommended) or complete all of the lessons in one day (hardcore). It really depends on the time you have available and your level of enthusiasm.

Below is a list of the seven lessons that will get you started and productive with Python:

Lesson 01: Manipulating lists
Lesson 02: Dictionaries
Lesson 03: Tuples
Lesson 04: Strings
Lesson 05: List comprehension
Lesson 06: Enumerate and zip
Lesson 07: Map, filter, and reduce

Each lesson could take you between 5 and up to 30 minutes. Take your time and complete the lessons at your own pace. Ask questions, and even post results in the comments online.

The lessons might expect you to go off and find out how to do things. This guide will give you hints, but part of the point of each lesson is to force you to learn where to go to look for help with and about the algorithms and the best-of-breed tools in Python.

Post your results in the comments; I’ll cheer you on!

Hang in there; don’t give up.

Lesson 01: Manipulating lists

In this lesson, you will discover a basic data structures in Python, the list.

In other programming languages, there are arrays. The counterpart in Python is list. A Python list does not limit the number of elements it stores. You can always append elements into it, and it will automatically expand its size. Python list also does not require its elements to be in the same type. You can mix and match different elements into a list.

In the following, we create a list of some integers, and then append a string into it:

x = [1, 2, 3]
x.append(„that’s all“)

Python lists are zero-indexed. Namely, to get the first element in the above list, we do:

print(x[0])

This will print 1 to the screen.

Python lists allow negative indices to mean counting elements from the back. So the way to print the last element from the above list is:

print(x[-1])

Python also has a handy syntax to find a slice of a list. To print the last two elements, we do:

print(x[-2:])

Usually, the slice syntax is start:end where the end is not included in the result. If omitted, the default will be the first element as the start and the one beyond the end of the entire list as the end. We can also use the slice syntax to make a step.” For example, this is how we can extract even and odd numbers:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd = x[::2]
even = x[1::2]
print(odd)
print(even)

Your Task

In the above example of getting odd numbers from a list of 1 to 10, you can make a step size of -2 to ask the list go backward. How can you use the slicing syntax to print [9,7,5,3,1]? How about [7,5,3]?

Post your answer in the comments below. I would love to see what you come up with.

In the next lesson, you will discover the Python dictionary.

Lesson 02: Dictionaries

In this lesson, you will learn Python’s way of storing a mapping.

Similar to Perl, an associative array is also a native data structure in Python. It is called a dictionary or dict. Python uses square brackets [] for list and uses curly brackets {} for dict. A Python dict is for key-value mapping, but the key must be hashable, such as a number or a string. Hence we can do the following:

price = {
„apple“: 1.5,
„orange“: 1.25,
„banana“: 0.5
}
print(„apple costs $“, price[„apple“])

Adding a key-value mapping to a dict is similar to indexing a list:

price[„lemon“] = 0.6
print(„lemon costs $“, price[„lemon“])

We can check if a key is in a dict using the codetext{in} operator, for example:

if „strawberry“ in price:
# if price is not found, assume $1
print(„strawberry costs $1“)
else:
print(„strawberry costs $“, price[„strawberry“])

But in Python dict, we can use the codetext{get()} function to give us a default value if the key is not found:

print(„strawberry costs $“, price.get(„strawberry“, 1))

But indeed, you are not required to provide a default to codetext{get()}. If you omitted it, it will return codetext{None}. For example:

print(„strawberry costs $“, price.get(„strawberry“))

It will produce

strawberry costs $ None

Since the Python dict is a key-value mapping, we can extract only the keys or only the values, using:

fruits = list(price.keys())
numbers = list(price.values())
print(fruits)
print(numbers)

We used list() to convert the keys or values to a list for better printing.
%
The other way to manipulate a list is with the items() function. Its result would be key-value pairs:

pairs = list(price.items())
print(pairs)

This prints:

[(‚apple‘, 1.5), (‚orange‘, 1.25), (‚banana‘, 0.5), (‚lemon‘, 0.6)]

Since they are pairs in a list, we can use list manipulation syntax to combine items from two dicts and produce a combined dict. The following is an example:

price1 = {
„apple“: 1.5,
„orange“: 1.25,
„strawberry“: 1.0
}
price2 = {
„banana“: 0.5
}
pairs1 = list(price1.items())
pairs2 = list(price2.items())
price = dict(pairs1 + pairs2)
print(price)

This will print:

{‚apple‘: 1.5, ‚orange‘: 1.25, ’strawberry‘: 1.0, ‚banana‘: 0.5}

Your Task

Depending on your version of Python, the last example above can have a simplified syntax:

price = price1 | price2
price = {**price1, **price2}

Check in your installation if you can reproduce the same result as the last example.

In the next lesson, you will discover the tuple as a read-only list.

Lesson 03: Tuples

In this lesson, you will learn the tuple as a read-only data structure.

Python has a list that behaves like an array of mixed data. A Python tuple is very much like a list, but it cannot be modified after it is created. It is immutable. Creating a tuple is just like creating a list, except using parentheses, ():

x = (1, 2, 3)

You can refer to the first element as x[0] just like the case of a list. But you cannot assign a new value to x[0] because a tuple is immutable. If you try to do it, Python will throw a TypeError with the reason that the tuple does not support the item assignment.

A tuple is handy to represent multiple return values of a function. For example, the following function produces a value’s multiple powers as a tuple:

def powers(n):
return n, n**2, n**3
x = powers(2)
print(x)

This will print:

(2, 4, 8)

which is a tuple. But we usually use the unpacking syntax:

itself, squared, cubed = powers(2)

In fact, this is a powerful syntax in Python in which we can assign multiple variables in one line. For example,

count, elements = 0, []

This will assign variable count to integer 0 and variable elements to an empty list. Because of the unpacking syntax, this is the Pythonic way of swapping the value of two variables:

a, b = b, a

Your Task

Consider a list of tuples:

x = [(„alpha“, 0.5), („gamma“, 0.1), („beta“, 1.1), („alpha“, -3)]

You can sort this list using sorted(x). What is the result? From the result of comparing tuples, how does Python understand which tuple is less than or greater than another? Which is greater, the tuple („alpha“, 0.5) or the tuple („alpha“, 0.5, 1)?

Post your answer in the comments below. I would love to see what you come up with.

In the next lesson, you will learn about Python strings.

Lesson 04: Strings

In this lesson, you will learn about creating and using strings in Python.

A string is the basic way of storing text in Python. All Python strings are unicode strings, meaning you can put unicode into it. For example:

x = „Hello “
print(x)

The smiley is a unicode character of code point 0x1F600. Python string comes with a lot of functions. For example, we can check if a string begins or ends with a substring using:

if x.startswith(„Hello“):
print(„x starts with Hello“)
if not x.endswith(„World“):
print(„x does not end with World“)

Then to check whether a string contains a substring, use the “in” operator:

if „ll“ in x:
print(„x contains double-l“)

There is a lot more. Such as split() to split a string, or upper() to convert the entire string into uppercase.

One special property of Python strings is the implicit concatenation. All of the following produce the string „hello world“:

x = „hel“
„lo world“
x = „hello“ “ world“
x = („hello “
„world“)

The rule is, Python will normally use as a line continuation. But if Python sees two strings placed together without anything separating them, the strings will be concatenated. Hence the first example above is to concatenate „hel“ with „lo world“. Likewise, the last example concatenated two strings because they are placed inside parentheses.

A Python string can also be created using a template. It is often seen in print() functions. For example, below all produce „hello world“ for variable y:

x = „world“
y = „hello %s“ % x
y = „hello {}“.format(x)
y = f“hello {x}“

Your Task

Try to run this code:

coord = {„lat“: 51.5072, „lon“: -0.1276}
print(„latitude %(lat)f, longitude %(lon)f“ % coord)
print(„latitude {lat}, longitude {lon}“.format(**coord))

This is to fill a template using a dictionary. The first uses the %-syntax while the second uses format syntax. Can you modify the code above to print only 2 decimal places? Hints: Check out https://docs.python.org/3/library/string.html!

Post your answer in the comments below. I would love to see what you come up with.

In the next lesson, you will discover list comprehension syntax in Python.

Lesson 05: List Comprehension

In this lesson, you will see how list comprehension syntax can build a list on the fly.

The famous fizz-buzz problem prints 1 to 100 with all 3-multiples replaced with “fizz,” all 5-multiples replaced with “buzz,” and if a number is both a multiple of 3 and 5, print “fizzbuzz.” You can make a for loop and some if statements to do this. But we can also do it in one line:

numbers = [„fizzbuzz“ if n%15==0 else „fizz“ if n%3==0 else „buzz“ if n%5==0 else str(n)
for n in range(1,101)]
print(„n“.join(numbers))

We set up the list numbers using list comprehension syntax. The syntax looks like a list but with a for inside. Before the keyword for, we define how each element in the list will be created.

List comprehension can be more complicated. For example, this is how to produce all multiples of 3 from 1 to 100:

mul3 = [n for n in range(1,101) if n%3 == 0]

And this is how we can print a $10times 10$ multiplication table:

table = [[m*n for n in range(1,11)] for m in range(1,11)]
for row in table:
print(row)

And this is how we can combine strings:

directions = [a+b for a in [„north“, „south“, „“] for b in [„east“, „west“, „“] if not (a==““ and b==““)]
print(directions)

This prints:

[’northeast‘, ’northwest‘, ’north‘, ’southeast‘, ’southwest‘, ’south‘, ‚east‘, ‚west‘]

Your Task

Python also has a dictionary comprehension. The syntax is:

double = {n: 2*n for n in range(1,11)}

Now try to create a dictionary mapping using dictionary comprehension that maps a string x to its length len(x) for these strings:

keys = [„one“, „two“, „three“, „four“, „five“, „six“, „seven“, „eight“, „nine“, „ten“]
mapping = {…}

Post your answer in the comments below. I would love to see what you come up with.

In the next lesson, you will discover two very useful Python functions: enumerate() and zip().

Lesson 06: Enumerate and Zip

In this lesson, you will learn an the enumerate() function and zip() function.

Very often, you will see you’re writing a for-loop like this:

x = [„alpha“, „beta“, „gamma“, „delta“]
for n in range(len(x)):
print(„{}: {}“.format(n, x[n]))

But here we need the loop variable n just to use as an index to access the list x. In this case, we can ask Python to index the list while doing the loop, using enumerate():

x = [„alpha“, „beta“, „gamma“, „delta“]
for n,string in enumerate(x):
print(„{}: {}“.format(n, string))

The result of enumerate() produces a tuple of the counter (default starts with zero) and the element of the list. We use the unpacking syntax to set it to two variables.

If we use the for-loop like this:

x = [„blue“, „red“, „green“, „yellow“]
y = [„cheese“, „apple“, „pea“, „mustard“]
for n in range(len(x)):
print(„{} {}“.format(x[n], y[n]))

Python has a function zip() to help:

x = [„blue“, „red“, „green“, „yellow“]
y = [„cheese“, „apple“, „pea“, „mustard“]
for a, b in zip(x, y):
print(„{} {}“.format(a, b))

The zip() function is like a zipper, taking one element from each input list and putting them side by side. You may provide more than two lists to zip(). It will produce all matching items (i.e., stop whenever it hits the end of the shortest input list).

Your task

Very common in Python programs, we may do this:

results = []
for n in range(1, 11):
squared, cubed = n**2, n**3
results.append([n, squared, cubed])

Then, we can get the list of 1 to 10, the square of them, and the cube of them using zip() (note the * before results in the argument):

numbers, squares, cubes = zip(*results)

Try this out. Can you recombine numbers, squares, and cubes back to results? Hints: Just use zip().

In the next lesson, you will discover three more Python functions: map(), filter(), and reduce().

Lesson 07: Map, Filter, and Reduce

In this lesson, you will learn the Python functions map(), filter(), and reduce().

The name of these three functions came from the functional programming paradigm. In simple terms, map() is to transform elements of a list using some function, and filter() is to short list the elements based on certain criteria. If you learned list comprehension, they are just another method of list comprehension.

Let’s consider an example we saw previously:

def fizzbuzz(n):
if n%15 == 0:
return „fizzbuzz“
if n%3 == 0:
return „fizz“
if n%5 == 0:
return „buzz“
return str(n)

numbers = map(fizzbuzz, range(1,101))
print(„n“.join(numbers))

Here we have a function defined, and map() uses the function as the first argument and a list as the second argument. It will take each element from a list and transform it using the provided function.

Using filter() is likewise:

def multiple3(n):
return n % 3 == 0

mul3 = filter(multiple3, range(1,101))
print(list(mul3))

If that’s appropriate, you can pass the return value from map() to filter() or vice versa.

You may consider map() and filter() as another way to write list comprehension (sometimes easier to read as the logic is modularized). The reduce() function is not replaceable by list comprehension. It scans the elements from a list and combines them using a function.

While Python has a max() function built-in, we can use reduce() for the same purpose. Note that reduce() is a function from the module functools:

from functools import reduce
def maximum(a,b):
if a > b:
return a
else:
return b

x = [-3, 10, 2, 5, -6, 12, 0, 1]
max_x = reduce(maximum, x)
print(max_x)

By default, reduce() will give the first two elements to the provided function, then the result will be passed to the function again with the third element, and so on until the input list is exhausted. But there is another way to invoke reduce():

x = [-3, 10, 2, 5, -6, 12, 0, 1]
max_x = reduce(maximum, x, -float(„inf“))
print(max_x)

This result is the same, but the first call to the function uses the default value (-float(„inf“) in this case, which is negative infinity) and the first element of the list. Then uses the result and the second element from the list, and so on. Providing a default value is appropriate in some cases, such as the exercise below.

Your Task

Let’s consider a way to convert a bitmap to an integer. If a list [6,2,0,3] is provided, we should consider the list as which bit to assert, and the result should be in binary, 1001101, or in decimal, 77. In this case, bit 0 is defined to be the least significant bit or the right most bit.

We can use reduce to do this and print 77:

def setbit(bitmap, bit):
return bitmap | (2**bit)

assertbits = [6, 2, 0, 3]
bitmap = reduce(setbit, assertbits, ???)
print(bitmap)

What should be the ??? above? Why?

Post your answer in the comments below. I would love to see what you come up with.

This was the final lesson.

The End!
(Look How Far You Have Come)

You made it. Well done!

Take a moment and look back at how far you have come.

You discovered:

Python list and the slicing syntax
Python dictionary, how to use it, and how to combine two dictionaries
Tuples, the unpacking syntax, and how to use it to swap variables
Strings, including many ways to create a new string from a template
List comprehension
The use of functions enumerate() and zip()
How to use map(), filter(), and reduce()

Summary

How did you do with the mini-course?
Did you enjoy this crash course?

Do you have any questions? Were there any sticking points?
Let me know. Leave a comment below.

The post Python for Machine Learning (7-day mini-course) appeared first on Machine Learning Mastery.

Click to comment

Leave a Reply

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Most Popular

To Top
Translate »