markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Linear spline functions are calculated with the following:
$$i \in [1,\ \left\vert{X}\right\vert - 1],\ i \in \mathbb{N}: $$
$$P_i = \frac{x-x_i}{x_{i+1}-x_i} * y_{i+1} + \frac{x_{i+1}-x}{x_{i+1}-x_i} * y_i$$
By simplification, we can reduce to the following:
$$P_i = \frac{y_{i+1} (x-x_i) + y_i (x_{i+1}-x)}{x_{i+1}-x_i... | print('x1 = %i' % data[0][0])
print('y1 = %i' % data[1][0])
print('---')
# linear spline function aproximation
print('no values: %i' % len(columns))
spline = {}
for i in range(len(columns)-1):
print('\nP[' + str(i+1) + ']')
# we calculate the numerator
num_1s = str(data[1][i+1]) + ' * x - ' + str(da... | FII-year3sem2-CN/Exam.ipynb | danalexandru/Algo | gpl-2.0 |
Jupyter Notebooks
This file - a Jupyter (IPython) notebook - does not follow the standard pattern with Python code in a text file. Instead, an IPython notebook is stored as a file in the JSON format. The advantage is that we can mix formatted text, Python code and code output. It requires the IPython notebook server to... | import math | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
This includes the whole module and makes it available for use later in the program. For example, we can do: | import math
x = math.cos(2 * math.pi)
print(x) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Alternatively, we can chose to import all symbols (functions and variables) in a module to the current namespace (so that we don't need to use the prefix "math." every time we use something from the math module: | from math import *
x = cos(2 * pi)
print(x) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
This pattern can be very convenient, but in large programs that include many modules it is often a good idea to keep the symbols from each module in their own namespaces, by using the import math pattern. This would elminate potentially confusing problems with name space collisions.
As a third alternative, we can chose... | from math import cos, pi
x = cos(2 * pi)
print(x) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Looking at what a module contains, and its documentation
Once a module is imported, we can list the symbols it provides using the dir function: | import math
print(dir(math)) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
And using the function help we can get a description of each function (almost .. not all functions have docstrings, as they are technically called, but the vast majority of functions are documented this way). | help(math.log)
math.log(10)
math.log(10, 2) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can also use the help function directly on modules: Try
help(math)
Some very useful modules form the Python standard library are os, sys, math, shutil, re, subprocess, multiprocessing, threading.
A complete lists of standard modules for Python 3 are available at http://docs.python.org/3/library/.
For example, this... | import os
os.listdir() | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Variables and types
Symbol names
Variable names in Python can contain alphanumerical characters a-z, A-Z, 0-9 and some special characters such as _. Normal variable names must start with a letter.
By convention, variable names start with a lower-case letter, and Class names start with a capital letter.
In addition, t... | # variable assignments
x = 1.0
my_variable = 12.2 | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Although not explicitly specified, a variable does have a type associated with it. The type is derived from the value that was assigned to it. | type(x) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
If we assign a new value to a variable, its type can change. | x = 1
type(x) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
If we try to use a variable that has not yet been defined we get an NameError: | import traceback
try:
print(y)
except NameError as e:
print(traceback.format_exc()) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Fundamental types | # integers
x = 1
type(x)
# float
x = 1.0
type(x)
# boolean
b1 = True
b2 = False
type(b1)
# complex numbers: note the use of `j` to specify the imaginary part
x = 1.0 - 1.0j
type(x)
print(x)
print(x.real, x.imag) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Type utility functions | x = 1.0
# check if the variable x is a float
type(x) is float
# check if the variable x is an int
type(x) is int | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can also use the isinstance method for testing types of variables: | isinstance(x, float) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Type casting | x = 1.5
print(x, type(x))
x = int(x)
print(x, type(x))
z = complex(x)
print(z, type(z))
import traceback
try:
x = float(z)
except TypeError as e:
print(traceback.format_exc()) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Operators and comparisons
Most operators and comparisons in Python work as one would expect:
Arithmetic operators +, -, *, /, // (integer division), '**' power | 1 + 2, 1 - 2, 1 * 2, 1 / 2
1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0
# Integer division of float numbers
3.0 // 2.0
# Note! The power operators in python isn't ^, but **
2 ** 2 | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Note: The / operator always performs a floating point division in Python 3.x.
This is not true in Python 2.x, where the result of / is always an integer if the operands are integers.
to be more specific, 1/2 = 0.5 (float) in Python 3.x, and 1/2 = 0 (int) in Python 2.x (but 1.0/2 = 0.5 in Python 2.x).
The boolean operat... | True and False
not False
True or False | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Comparison operators >, <, >= (greater or equal), <= (less or equal), == equality, is identical. | 2 > 1, 2 < 1
2 > 2, 2 < 2
2 >= 2, 2 <= 2
# equality
[1,2] == [1,2]
# objects identical?
list1 = list2 = [1,2]
list1 is list2 | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Exercise:
Mindy has $5.25 in her pocket. Apples cost 29 cents each. Calculate how many apples mindy can buy and how much change she will have left. Money should be represented in variables of type float and apples should be represented in variables of type integer.
Answer:
mindy_money = 5.25
apple_cost = .29
num_apple... | s = "Hello world"
type(s)
# length of the string: the number of characters
len(s)
# replace a substring in a string with somethign else
s2 = s.replace("world", "test")
print(s2) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can index a character in a string using []: | s[0] | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Heads up MATLAB and R users: Indexing start at 0!
We can extract a part of a string using the syntax [start:stop], which extracts characters between index start and stop -1 (the character at index stop is not included): | s[0:5]
s[4:5] | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
If we omit either (or both) of start or stop from [start:stop], the default is the beginning and the end of the string, respectively: | s[:5]
s[6:]
s[:] | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can also define the step size using the syntax [start:end:step] (the default value for step is 1, as we saw above): | s[::1]
s[::2] | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
This technique is called slicing. Read more about the syntax here: https://docs.python.org/3.5/library/functions.html#slice
Python has a very rich set of functions for text processing. See for example https://docs.python.org/3.5/library/string.html for more information.
String formatting examples | print("str1", "str2", "str3") # The print statement concatenates strings with a space
print("str1", 1.0, False, -1j) # The print statements converts all arguments to strings
print("str1" + "str2" + "str3") # strings added with + are concatenated without space
print("value = %f" % 1.0) # we can use C-style st... | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Exercise:
Paste in the code from your previous exercise and output the result as a story (round monetary values to 2 decimal places). The ouptut should look like this:
"Mindy had \$5.25 in her pocket. Apples at her nearby store cost 29 cents. With her \$5.25, mindy can buy 18 apples and will have 10 cents left over."
L... | l = [1,2,3,4]
print(type(l))
print(l) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can use the same slicing techniques to manipulate lists as we could use on strings: | print(l)
print(l[1:3])
print(l[::2]) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Heads up MATLAB and R users: Indexing starts at 0! | l[0] | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Elements in a list do not all have to be of the same type: | l = [1, 'a', 1.0, 1-1j]
print(l) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Python lists can be heterogeneous and arbitrarily nested: | nested_list = [1, [2, [3, [4, [5]]]]]
nested_list | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Lists play a very important role in Python. For example they are used in loops and other flow control structures (discussed below). There are a number of convenient functions for generating lists of various types, for example the range function: | start = 10
stop = 30
step = 2
range(start, stop, step)
# in python 3 range generates an iterator, which can be converted to a list using 'list(...)'.
# It has no effect in python 2
list(range(start, stop, step))
list(range(-10, 10))
s
# convert a string to a list by type casting:
s2 = list(s)
s2
# sorting lists ... | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Adding, inserting, modifying, and removing elements from lists | # create a new empty list
l = []
# add an elements using `append`
l.append("A")
l.append("d")
l.append("d")
print(l) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can modify lists by assigning new values to elements in the list. In technical jargon, lists are mutable. | l[1] = "p"
l[2] = "p"
print(l)
l[1:3] = ["d", "d"]
print(l) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Insert an element at an specific index using insert | l.insert(0, "i")
l.insert(1, "n")
l.insert(2, "s")
l.insert(3, "e")
l.insert(4, "r")
l.insert(5, "t")
print(l) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Remove first element with specific value using 'remove' | l.remove("A")
print(l) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Remove an element at a specific location using del: | del l[7]
del l[6]
print(l) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
See help(list) for more details, or read the online documentation
Tuples
Tuples are like lists, except that they cannot be modified once created, that is they are immutable.
In Python, tuples are created using the syntax (..., ..., ...), or even ..., ...: | point = (10, 20)
print(point, type(point))
point = 10, 20
print(point, type(point)) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can unpack a tuple by assigning it to a comma-separated list of variables: | x, y = point
print("x =", x)
print("y =", y) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
If we try to assign a new value to an element in a tuple we get an error: | try:
point[0] = 20
except TypeError as e:
print(traceback.format_exc()) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Dictionaries
Dictionaries are also like lists, except that each element is a key-value pair. The syntax for dictionaries is {key1 : value1, ...}: | params = {"parameter1" : 1.0,
"parameter2" : 2.0,
"parameter3" : 3.0,}
print(type(params))
print(params)
print("parameter1 = " + str(params["parameter1"]))
print("parameter2 = " + str(params["parameter2"]))
print("parameter3 = " + str(params["parameter3"]))
params["parameter1"] = "A"
params["para... | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Exercise:
Mindy doesn't want 18 apples, that's too many for someone who lives by themselves. We're now going to represent mindy's world using our new data types.
Make a list containing the fruits that mindy desires. She likes apples, strawberries, pinapples, and papayas.
Make a tuple containing the fruits that the stor... | statement1 = False
statement2 = False
if statement1:
print("statement1 is True")
elif statement2:
print("statement2 is True")
else:
print("statement1 and statement2 are False") | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
For the first time, here we encounted a peculiar and unusual aspect of the Python programming language: Program blocks are defined by their indentation level.
Compare to the equivalent C code:
if (statement1)
{
printf("statement1 is True\n");
}
else if (statement2)
{
printf("statement2 is True\n");
}
else
{
... | statement1 = statement2 = True
if statement1:
if statement2:
print("both statement1 and statement2 are True")
# # Bad indentation!
# if statement1:
# if statement2:
# print("both statement1 and statement2 are True") # this line is not properly indented
statement1 = False
if statement1:
pri... | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Loops
In Python, loops can be programmed in a number of different ways. The most common is the for loop, which is used together with iterable objects, such as lists. The basic syntax is:
for loops: | for x in [1,2,3]:
print(x) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
The for loop iterates over the elements of the supplied list, and executes the containing block once for each element. Any kind of list can be used in the for loop. For example: | for x in range(4): # by default range start at 0
print(x) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Note: range(4) does not include 4 ! | for x in range(-3,3):
print(x)
for word in ["scientific", "computing", "with", "python"]:
print(word) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
To iterate over key-value pairs of a dictionary: | for key, value in params.items():
print(key + " = " + str(value)) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Sometimes it is useful to have access to the indices of the values when iterating over a list. We can use the enumerate function for this: | for idx, x in enumerate(range(-3,3)):
print(idx, x) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
List comprehensions: Creating lists using for loops:
A convenient and compact way to initialize lists: | l1 = [x**2 for x in range(0,5)]
print(l1) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
while loops: | i = 0
while i < 5:
print(i)
i = i + 1
print("done") | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Note that the print("done") statement is not part of the while loop body because of the difference in indentation.
Exercise:
Loop through all of the fruits that mindy wants and check if the store has them. For each fruit that she wants print
"Mindy, the store has apples and they cost $.29"
or
"Mindy, the store does no... | def func0():
print("test")
func0() | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Optionally, but highly recommended, we can define a so called "docstring", which is a description of the functions purpose and behaivor. The docstring should follow directly after the function definition, before the code in the function body. | def func1(s):
"""
Print a string 's' and tell how many characters it has
"""
print(s + " has " + str(len(s)) + " characters")
help(func1)
func1("test") | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Functions that returns a value use the return keyword: | def square(x):
"""
Return the square of x.
"""
return x ** 2
square(4) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can return multiple values from a function using tuples (see above): | def powers(x):
"""
Return a few powers of x.
"""
return x ** 2, x ** 3, x ** 4
powers(3)
x2, x3, x4 = powers(3)
print(x3) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Default argument and keyword arguments
In a definition of a function, we can give default values to the arguments the function takes: | def myfunc(x, p=2, debug=False):
if debug:
print("evaluating myfunc for x = " + str(x) + " using exponent p = " + str(p))
return x**p | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
If we don't provide a value of the debug argument when calling the the function myfunc it defaults to the value provided in the function definition: | myfunc(5)
myfunc(5, debug=True) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition. This is called keyword arguments, and is often very useful in functions that takes a lot of optional arguments. | myfunc(p=3, debug=True, x=7) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Unnamed functions (lambda function)
In Python we can also create unnamed functions, using the lambda keyword: | f1 = lambda x: x**2
# is equivalent to
def f2(x):
return x**2
f1(2), f2(2) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
This technique is useful for example when we want to pass a simple function as an argument to another function, like this: | # map is a built-in python function
map(lambda x: x**2, range(-3,4))
# in python 3 we can use `list(...)` to convert the iterator to an explicit list
list(map(lambda x: x**2, range(-3,4))) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Exercise:
Mindy is great, but we want code that can tell anyone what fruits the store has. To do this we will generalize our code for Mindy using a function.
Write a function that takes the following parameters
- full_name (string)
- fruits_you_want (list)
- fruits_the_store_has (tuple)
- prices (dict)
and prints to th... | class Point:
"""
Simple class for representing a point in a Cartesian coordinate system.
"""
def __init__(self, x, y):
"""
Create a new Point at x, y.
"""
self.x = x
self.y = y
def translate(self, dx, dy):
"""
Translate the point ... | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
To create a new instance of a class: | p1 = Point(0, 0) # this will invoke the __init__ method in the Point class
print(p1) # this will invoke the __str__ method | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
To invoke a class method in the class instance p: | p2 = Point(1, 1)
p1.translate(0.25, 1.5)
print(p1)
print(p2) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Note that calling class methods can modifiy the state of that particular class instance, but does not effect other class instances or any global variables.
That is one of the nice things about object-oriented design: code such as functions and related variables are grouped in separate and independent entities.
Modules... | %%file mymodule.py
"""
Example of a python module. Contains a variable called my_variable,
a function called my_function, and a class called MyClass.
"""
my_variable = 0
def my_function():
"""
Example function
"""
return my_variable
class MyClass:
"""
Example class.
"""
def __ini... | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
We can import the module mymodule into our Python program using import: | import mymodule | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Use help(module) to get a summary of what the module provides: | help(mymodule)
mymodule.my_variable
mymodule.my_function()
my_class = mymodule.MyClass()
my_class.set_variable(10)
my_class.get_variable() | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
If we make changes to the code in mymodule.py, we need to reload it using reload: | import importlib
importlib.reload(mymodule) # Python 3 only
# For Python 2 use reload(mymodule) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Exceptions
In Python errors are managed with a special language construct called "Exceptions". When errors occur exceptions can be raised, which interrupts the normal program flow and fallback to somewhere else in the code where the closest try-except statement is defined.
To generate an exception we can use the raise ... | try:
raise Exception("description of the error")
except Exception as e:
print(traceback.format_exc()) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
A typical use of exceptions is to abort functions when some error condition occurs, for example:
def my_function(arguments):
if not verify(arguments):
raise Exception("Invalid arguments")
# rest of the code goes here
To gracefully catch errors that are generated by functions and class methods, or by ... | try:
print("test")
# generate an error: the variable test is not defined
print(test)
except Exception:
print("Caught an exception") | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
To get information about the error, we can access the Exception class instance that describes the exception by using for example:
except Exception as e: | try:
print("test")
# generate an error: the variable test is not defined
print(test)
except Exception as e:
print("Caught an exception:", e) | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Excercise:
Make two classes with the following variables and methods
Store
variables
- inventory (dict)
methods
- show_inventory()
* nicely displays the store's inventory
- message_customer(customer)
* shows the customer if the store has the fruits they want and how much each fruit costs (this is code from previous e... | %reload_ext version_information
%version_information | notebooks/intro-python.ipynb | AlJohri/DAT-DC-12 | mit |
Coordinate Transformation | def trans(x, y, a):
'''create a 2D transformation'''
s = np.sin(a)
c = np.cos(a)
return np.asarray([[c, -s, x],
[s, c, y],
[0, 0, 1]])
def from_trans(m):
'''get x, y, theta from transform matrix'''
a = np.arctan2(m[1, 0], m[0, 0])
return np.as... | kinematics/inverse_kinematics_2d_jax.ipynb | DAInamite/programming-humanoid-robot-in-python | gpl-2.0 |
Parameters of robot arm | l = [0, 3, 2, 1]
#l = [0, 3, 2, 1, 1]
#l = [0, 3, 2, 1, 1, 1]
#l = [1] * 30
N = len(l) - 1 # number of links
max_len = sum(l)
a = random.random_sample(N) # angles of joints
T0 = trans(0, 0, 0) # base | kinematics/inverse_kinematics_2d_jax.ipynb | DAInamite/programming-humanoid-robot-in-python | gpl-2.0 |
Forward Kinematics | def forward_kinematics(T0, l, a):
T = [T0]
for i in range(len(a)):
Ti = np.dot(T[-1], trans(l[i], 0, a[i]))
T.append(Ti)
Te = np.dot(T[-1], trans(l[-1], 0, 0)) # end effector
T.append(Te)
return T
def show_robot_arm(T):
plt.cla()
x = [Ti[0,-1] for Ti in T]
y = [Ti[1,-1]... | kinematics/inverse_kinematics_2d_jax.ipynb | DAInamite/programming-humanoid-robot-in-python | gpl-2.0 |
Inverse Kinematics
Numerical Solution: jax | def error_func(theta, target):
Ts = forward_kinematics(T0, l, theta)
Te = Ts[-1]
e = target - Te
return np.sum(e * e)
theta = random.random(N)
def inverse_kinematics(x_e, y_e, theta_e, theta):
target = trans(x_e, y_e, theta_e)
func = lambda t: error_func(t, target)
func_grad = jit(grad(func... | kinematics/inverse_kinematics_2d_jax.ipynb | DAInamite/programming-humanoid-robot-in-python | gpl-2.0 |
We start with preparing the data points for clustering. The data is two-dimensional and craeted by drawing random numbers from four superpositioned gaussian distributions which are centered at the corners of a square (indicated by the red dashed lines). | # generate the data points
npoints = 2000
mux = 1.6
muy = 1.6
points = np.zeros(shape=(npoints, 2), dtype=np.float64)
points[:, 0] = np.random.randn(npoints) + mux * (-1)**np.random.randint(0, high=2, size=npoints)
points[:, 1] = np.random.randn(npoints) + muy * (-1)**np.random.randint(0, high=2, size=npoints)
# draw t... | ipython/Example01.ipynb | cwehmeyer/pydpc | lgpl-3.0 |
Now comes the interesting part.
We pass the numpy ndarray with the data points to the Cluster class which prepares the data set for clustering. In this stage, it computes the Euclidean distances between all data points and from that the two properties to identify clusters within the data: each data points' density and ... | clu = Cluster(points) | ipython/Example01.ipynb | cwehmeyer/pydpc | lgpl-3.0 |
Now that we have the decision graph, we can select the outliers via the assign method by setting lower bounds for delta and density. The assign method does the actual clustering; it also shows the decision graph again with the given selection. | clu.assign(20, 1.5) | ipython/Example01.ipynb | cwehmeyer/pydpc | lgpl-3.0 |
Let us have a look at the result.
We again plot the data and red dashed lines indicating the centeres of the gaussian distributions. Indicated in the left panel by red dots are the four outliers from the decision graph; these are our four cluster centers. The center panel shows the points' densities and the right panel... | fig, ax = plt.subplots(1, 3, figsize=(15, 5))
ax[0].scatter(points[:, 0], points[:, 1], s=40)
ax[0].scatter(points[clu.clusters, 0], points[clu.clusters, 1], s=50, c="red")
ax[1].scatter(points[:, 0], points[:, 1], s=40, c=clu.density)
ax[2].scatter(points[:, 0], points[:, 1], s=40, c=clu.membership, cmap=mpl.cm.cool)
... | ipython/Example01.ipynb | cwehmeyer/pydpc | lgpl-3.0 |
The density peak clusterng can further resolve if the membership of a data point to a certain cluster is strong or rather weak and separates the data points further into core and halo regions.
The left panel depicts the border members in grey.
The separation in the center panel uses the core/halo criterion of the origi... | fig, ax = plt.subplots(1, 3, figsize=(15, 5))
ax[0].scatter(
points[:, 0], points[:, 1],
s=40, c=clu.membership, cmap=mpl.cm.cool)
ax[0].scatter(points[clu.border_member, 0], points[clu.border_member, 1], s=40, c="grey")
ax[1].scatter(
points[clu.core_idx, 0], points[clu.core_idx, 1],
s=40, c=clu.member... | ipython/Example01.ipynb | cwehmeyer/pydpc | lgpl-3.0 |
This concludes the example.
In the remaining part, we address the performance of the pydpc implementation (numpy + cython-wrapped C code) with respect to an older development version (numpy). In particular, we look at the numerically most demanding part of computing the Euclidean distances between the data points and e... | npoints = 1000
points = np.zeros(shape=(npoints, 2), dtype=np.float64)
points[:, 0] = np.random.randn(npoints) + 1.8 * (-1)**np.random.randint(0, high=2, size=npoints)
points[:, 1] = np.random.randn(npoints) + 1.8 * (-1)**np.random.randint(0, high=2, size=npoints)
%timeit Cluster(points, fraction=0.02, autoplot=False)... | ipython/Example01.ipynb | cwehmeyer/pydpc | lgpl-3.0 |
The next two cells measure the full clustering. | %%timeit
Cluster(points, fraction=0.02, autoplot=False).assign(20, 1.5)
%%timeit
tmp = RefCluster(fraction=0.02, autoplot=False)
tmp.load(points)
tmp.assign(20, 1.5) | ipython/Example01.ipynb | cwehmeyer/pydpc | lgpl-3.0 |
Step 1.2: Data Preprocessing
Now that we have a basic understanding of what our dataset looks like, lets convert our labels to binary variables, 0 to represent 'ham'(i.e. not spam) and 1 to represent 'spam' for ease of computation.
You might be wondering why do we need to do this step? The answer to this lies in how s... | '''
Solution
'''
df['label'] = df.label.map({'ham':0, 'spam':1})
print(df.shape)
df.head() # returns (rows, columns) | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Step 2.1: Bag of words
What we have here in our data set is a large collection of text data (5,572 rows of data). Most ML algorithms rely on numerical data to be fed into them as input, and email/sms messages are usually text heavy.
Here we'd like to introduce the Bag of Words(BoW) concept which is a term used to spec... | '''
Solution:
'''
documents = ['Hello, how are you!',
'Win money, win from home.',
'Call me now.',
'Hello, Call hello you tomorrow?']
lower_case_documents = []
for i in documents:
lower_case_documents.append(i.lower())
print(lower_case_documents) | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Step 2: Removing all punctuations
Instructions:
Remove all punctuation from the strings in the document set. Save them into a list called
'sans_punctuation_documents'. | '''
Solution:
'''
sans_punctuation_documents = []
import string
for i in lower_case_documents:
sans_punctuation_documents.append(i.translate(str.maketrans('', '', string.punctuation)))
print(sans_punctuation_documents) | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Step 3: Tokenization
Tokenizing a sentence in a document set means splitting up a sentence into individual words using a delimiter. The delimiter specifies what character we will use to identify the beginning and the end of a word(for example we could use a single space as the delimiter for identifying words in our do... | '''
Solution:
'''
preprocessed_documents = []
for i in sans_punctuation_documents:
preprocessed_documents.append(i.split(' '))
print(preprocessed_documents) | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Step 4: Count frequencies
Now that we have our document set in the required format, we can proceed to counting the occurrence of each word in each document of the document set. We will use the Counter method from the Python collections library for this purpose.
Counter counts the occurrence of each item in the list a... | '''
Solution
'''
frequency_list = []
import pprint
from collections import Counter
for i in preprocessed_documents:
frequency_counts = Counter(i)
frequency_list.append(frequency_counts)
pprint.pprint(frequency_list) | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Congratulations! You have implemented the Bag of Words process from scratch! As we can see in our previous output, we have a frequency distribution dictionary which gives a clear view of the text that we are dealing with.
We should now have a solid understanding of what is happening behind the scenes in the sklearn.fea... | '''
Here we will look to create a frequency matrix on a smaller document set to make sure we understand how the
document-term matrix generation happens. We have created a sample document set 'documents'.
'''
documents = ['Hello, how are you!',
'Win money, win from home.',
'Call me now.'... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Instructions:
Import the sklearn.feature_extraction.text.CountVectorizer method and create an instance of it called 'count_vector'. | '''
Solution
'''
from sklearn.feature_extraction.text import CountVectorizer
count_vector = CountVectorizer() | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Data preprocessing with CountVectorizer()
In Step 2.2, we implemented a version of the CountVectorizer() method from scratch that entailed cleaning our data first. This cleaning involved converting all of our data to lower case and removing all punctuation marks. CountVectorizer() has certain parameters which take car... | '''
Practice node:
Print the 'count_vector' object which is an instance of 'CountVectorizer()'
'''
print(count_vector) | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Instructions:
Fit your document dataset to the CountVectorizer object you have created using fit(), and get the list of words
which have been categorized as features using the get_feature_names() method. | '''
Solution:
'''
count_vector.fit(documents)
count_vector.get_feature_names() | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
The get_feature_names() method returns our feature names for this dataset, which is the set of words that make up our vocabulary for 'documents'.
Instructions:
Create a matrix with the rows being each of the 4 documents, and the columns being each word.
The corresponding (row, column) value is the frequency of occu... | '''
Solution
'''
doc_array = count_vector.transform(documents).toarray()
doc_array | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Now we have a clean representation of the documents in terms of the frequency distribution of the words in them. To make it easier to understand our next step is to convert this array into a dataframe and name the columns appropriately.
Instructions:
Convert the array we obtained, loaded into 'doc_array', into a data... | '''
Solution
'''
frequency_matrix = pd.DataFrame(doc_array,
columns = count_vector.get_feature_names())
frequency_matrix | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Congratulations! You have successfully implemented a Bag of Words problem for a document dataset that we created.
One potential issue that can arise from using this method out of the box is the fact that if our dataset of text is extremely large(say if we have a large collection of news articles or email data), there ... | '''
Solution
'''
# split into training and testing sets
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(df['sms_message'],
df['label'],
random_state=1)
pr... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Step 3.2: Applying Bag of Words processing to our dataset.
Now that we have split the data, our next objective is to follow the steps from Step 2: Bag of words and convert our data into the desired matrix format. To do this we will be using CountVectorizer() as we did before. There are two steps to consider here:
Fir... | '''
[Practice Node]
The code for this segment is in 2 parts. Firstly, we are learning a vocabulary dictionary for the training data
and then transforming the data into a document-term matrix; secondly, for the testing data we are only
transforming the data into a document-term matrix.
This is similar to the process... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Step 4.1: Bayes Theorem implementation from scratch
Now that we have our dataset in the format that we need, we can move onto the next portion of our mission which is the algorithm we will use to make our predictions to classify a message as spam or not spam. Remember that at the start of the mission we briefly discus... | '''
Instructions:
Calculate probability of getting a positive test result, P(Pos)
'''
'''
Solution (skeleton code will be provided)
'''
# P(D)
p_diabetes = 0.01
# P(~D)
p_no_diabetes = 0.99
# Sensitivity or P(Pos|D)
p_pos_diabetes = 0.9
# Specificity or P(Neg/~D)
p_neg_no_diabetes = 0.9
# P(Pos)
p_pos = (p_diabete... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Using all of this information we can calculate our posteriors as follows:
The probability of an individual having diabetes, given that, that individual got a positive test result:
P(D/Pos) = (P(D) * Sensitivity)) / P(Pos)
The probability of an individual not having diabetes, given that, that individual got a positive ... | '''
Instructions:
Compute the probability of an individual having diabetes, given that, that individual got a positive test result.
In other words, compute P(D|Pos).
The formula is: P(D|Pos) = (P(D) * P(Pos|D) / P(Pos)
'''
'''
Solution
'''
# P(D|Pos)
p_diabetes_pos = (p_diabetes * p_pos_diabetes) / p_pos
print('Proba... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Congratulations! You have implemented Bayes theorem from scratch. Your analysis shows that even if you get a positive test result, there is only a 8.3% chance that you actually have diabetes and a 91.67% chance that you do not have diabetes. This is of course assuming that only 1% of the entire population has diabetes ... | '''
Instructions: Compute the probability of the words 'freedom' and 'immigration' being said in a speech, or
P(F,I).
The first step is multiplying the probabilities of Jill Stein giving a speech with her individual
probabilities of saying the words 'freedom' and 'immigration'. Store this in a variable called p_j_tex... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Now we can compute the probability of P(J|F,I), that is the probability of Jill Stein saying the words Freedom and Immigration and P(G|F,I), that is the probability of Gary Johnson saying the words Freedom and Immigration. | '''
Instructions:
Compute P(J|F,I) using the formula P(J|F,I) = (P(J) * P(J|F) * P(J|I)) / P(F,I) and store it in a variable p_j_fi
'''
'''
Solution
'''
p_j_fi = p_j_text / p_f_i
print('The probability of Jill Stein saying the words Freedom and Immigration: ', format(p_j_fi))
'''
Instructions:
Compute P(G|F,I) using ... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
And as we can see, just like in the Bayes' theorem case, the sum of our posteriors is equal to 1. Congratulations! You have implemented the Naive Bayes' theorem from scratch. Our analysis shows that there is only a 6.6% chance that Jill Stein of the Green Party uses the words 'freedom' and 'immigration' in her speech a... | '''
Instructions:
We have loaded the training data into the variable 'training_data' and the testing data into the
variable 'testing_data'.
Import the MultinomialNB classifier and fit the training data into the classifier using fit(). Name your classifier
'naive_bayes'. You will be training the classifier using 'tra... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
Now that predictions have been made on our test set, we need to check the accuracy of our predictions.
Step 6: Evaluating our model
Now that we have made predictions on our test set, our next goal is to evaluate how well our model is doing. There are various mechanisms for doing so, but first let's do quick recap of th... | '''
Instructions:
Compute the accuracy, precision, recall and F1 scores of your model using your test data 'y_test' and the predictions
you made earlier stored in the 'predictions' variable.
'''
'''
Solution
'''
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
print('Accuracy score: ... | Project-practice--naive_bayes_tutorial/Naive_Bayes_tutorial.ipynb | littlewizardLI/Udacity-ML-nanodegrees | apache-2.0 |
We will be using the re library to parse our lines of text. We will import the InteractiveRunner class for executing out pipeline in the notebook environment and the interactive_beam module for exploring the PCollections. Finally we will import two functions from the Dataframe API, to_dataframe and to_pcollection. to_d... | class ReadWordsFromText(beam.PTransform):
def __init__(self, file_pattern):
self._file_pattern = file_pattern
def expand(self, pcoll):
return (pcoll.pipeline
| beam.io.ReadFromText(self._file_pattern)
| beam.FlatMap(lambda line: re.findall(r'[\w\']+', li... | courses/dataflow/demos/beam_notebooks/beam_notebooks_demo.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.