Docsity
Top Seller

Python basics and exercises for machine learning, Appunti di Machine learning

Toggle sidebar
bg1
PYTHON'S MAIN TECHNICAL FEATURES:
• free
• portable
• object-oriented language
• hybrid between easy-to-use scripting languages (bash) and advanced compiled languages (C, C++, C#)
• interpreted language
• dynamic typing
• it automatically manages the memory
• simple syntax
• large collection of built-in tools or external pre-coded libraries, called modules
JUPYTER NOTEBOOKS
The notebook extends the console-based approach to interactive computing in a qualitatively new direction,
providing a web-based application suitable for capturing the whole computation process: developing, documenting,
and executing code, as well as communicating the results.
The Jupyter notebook combines 2 components:
1. a web application: a browser-based tool for interactive authoring of documents which combine explanatory text,
mathematics, computations and their rich media output
2. notebook documents: a representation of all content visible in the web application, including inputs and outputs
of the computations, explanatory text, mathematics, images, and rich media representations of objects
In other words, a Jupyter notebook is simply like a script, but you can have in the same page many cells.
Each cell can be used to write and run independently some code, or to write some text.
It is preferred when you need to learn, so that you can write formatted text rather than comments, or when you
want to have in the same page the code and the output (also images), visualized sequentially.
So, it becomes a mix between programming and writing a story, which is much better for readability.
VARIABLES
Python is an interpreted language and typing is dynamic.
The declaration of a variable is done simply by assigning a value to the variable we intend to declare.
Variables (and functions) are visible throughout the notebook as long as you have executed the cells containing their
declarations: for example, if you have not executed the previous cell, the following code will return an error.
In Python, each variable is an object with three properties:
• identity: the object's location in your computer memory, which never changes
• data type: it’s the category of data the object belongs to, which determines the properties the object has
• value: the object that represents the data
DATA TYPES
Python groups data into different categories called data types.
Since Python is a dynamic typing language, it is possible to change the type of variables at runtime.
• string: a sequence of one or more characters surrounded by quotes (they could be single or double, but the
quotes at the beginning and end of a string must match);
strings can be accessed by position (remember that Python counts starting from 0);
strings are immutable (we can’t change an element of an already defined string)
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24

Anteprima parziale del testo

Scarica Python basics and exercises for machine learning e più Appunti in PDF di Machine learning solo su Docsity!

PYTHON'S MAIN TECHNICAL FEATURES:

  • free
  • portable
  • object-oriented language
  • hybrid between easy-to-use scripting languages (bash) and advanced compiled languages (C, C++, C#)
  • interpreted language
  • dynamic typing
  • it automatically manages the memory
  • simple syntax
  • large collection of built-in tools or external pre-coded libraries, called modules JUPYTER NOTEBOOKS The notebook extends the console-based approach to interactive computing in a qualitatively new direction, providing a web-based application suitable for capturing the whole computation process: developing, documenting, and executing code, as well as communicating the results. The Jupyter notebook combines 2 components:
  1. a web application: a browser-based tool for interactive authoring of documents which combine explanatory text, mathematics, computations and their rich media output
  2. notebook documents: a representation of all content visible in the web application, including inputs and outputs of the computations, explanatory text, mathematics, images, and rich media representations of objects In other words, a Jupyter notebook is simply like a script, but you can have in the same page many cells. Each cell can be used to write and run independently some code, or to write some text. It is preferred when you need to learn, so that you can write formatted text rather than comments, or when you want to have in the same page the code and the output (also images), visualized sequentially. So, it becomes a mix between programming and writing a story, which is much better for readability. VARIABLES Python is an interpreted language and typing is dynamic. The declaration of a variable is done simply by assigning a value to the variable we intend to declare. Variables (and functions) are visible throughout the notebook as long as you have executed the cells containing their declarations: for example, if you have not executed the previous cell, the following code will return an error. In Python, each variable is an object with three properties:
  • identity: the object's location in your computer memory, which never changes
  • data type: it’s the category of data the object belongs to, which determines the properties the object has
  • value: the object that represents the data DATA TYPES Python groups data into different categories called data types. Since Python is a dynamic typing language, it is possible to change the type of variables at runtime.
  • string : a sequence of one or more characters surrounded by quotes (they could be single or double, but the quotes at the beginning and end of a string must match); strings can be accessed by position (remember that Python counts starting from 0); strings are immutable (we can’t change an element of an already defined string)

The 'int' object is not sub-scriptable:

  • list : it’s a container that stores objects, also of different type, in a specific order. The list class provides numerous methods, including: Lists are mutable, so we can access a specific element and change it:
  • tuple : it’s a container that stores objects, also of different type, in a specific order The tuple class provides some methods including: Tuples are immutable, so we can’t access a specific element and change it:

Tuples are often used as function parameters: this prevents the code within the function from changing the values of the parameters during the function call.

  • dictionaries contain couples of (key: value) and the key-set contains unique values: We can access a dictionary by using the unique key value: Dictionaries are mutable:
  • set : it’s a list of unique objects; pay attention to the fact that python will ignore duplicate items: Sets are mutable, but unsorted:
  • FOR loop A Python for loop is used to iterate through an iterable (a process called iterating), that means to repeat a block of code for a fixed number of times. The for-loop is always used in combination with an iterable object, like a list or a range. The Python for statement iterates over the members of a sequence in order.

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops (stop element is always excluded):

  • WHILE loop : the while statement is used for repeated execution as long as an expression is true:

EXTERNAL MODULES

Imagine you wrote a program with 10000 lines of code: if you put all the code in one file, it would be difficult to navigate and maintain it. Programmers solve this issue by dividing large programs into multiple pieces, called modules: each module contains pieces of code. Python allows you to use code from one module in another module and has built-in modules and you can directly use them after importing. Python also has modules that must be installed before importing and using them. To import a module, the Python syntax is: Once you have imported a module, you can use code from it, by using the syntax: In most of the signal processing exercises we will use the following external modules:

  • NumPy : it’s the fundamental package for scientific computing in Python, that provides a multidimensional array object, various derived objects (masked arrays and matrices), and an assortment of routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O, discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more; to use it, we must import it: In contrast to Python's lists, Numpy's arrays (ndarray = n-dimensional array) are homogeneous (they can contain only elements of the same type). The initialization of an ndarray is performed with the function array(...), that, in its basic version, accepts a list of values as a parameter: The ndarray are mutable and the access is managed by indexing:

NumPy can handle multidimensional ndarrays; below there’s an example of declaring a 2 - dimensional ndarray (the parameter consists of a list of lists of identical length and each sublist describes the contents of one row): To obtain the shape of an ndarray, simply access its attribute shape, by using the syntax: Algebraic operations:

  • Matplotlib : it’s a comprehensive library for creating static, animated and interactive visualizations in Python, simplifying things

Subplots:

For a DataFrame, passing a single label selects a columns and yields a Series equivalent to df.Age: For a DataFrame, passing a slice means select matching rows: We can select by position using DataFrame.iloc(). Select via the position of the passed integers: Integer slices acts like NumPy/Python: Lists of integer position locations: For slicing rows and columns explicitly: For getting a value explicitly:

For NumPy data types, np.nan represents missing data : it’s by default not included in computations. DataFrame.dropna() drops any rows that have missing data: Statistics : operations in general exclude missing data. Calculate the mean value for each column: