Docsity

Appunti di Coding for data science, Sintesi del corso di Programmazione Avanzata

Toggle sidebar
bg1
CODING FOR DATA SCIENCE
Introduction:
The binary digit
Using binary sequences of constant length k, we must
establish the minimum value k that allows us to represent the #S elements of
the set S. A sequence of k bits allows us to identify 2k different elements; the
problem posed is the reverse one: given the number #S of elements to be
identified, we must now determine the length k of the required sequences.
The notion of algorithm
An algorithm is the description of the solution to a
problem expressed in the form of a set of instructions that, by operating on the
initial data, allow us to obtain results that constitute the solution to the
problem. These instructions are determined by iteratively breaking down the
initial problem into elementary subproblems, the solution to each of which is
called a step of the algorithm.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Anteprima parziale del testo

Scarica Appunti di Coding for data science e più Sintesi del corso in PDF di Programmazione Avanzata solo su Docsity!

CODING FOR DATA SCIENCE

Introduction:

The binary digit  Using binary sequences of constant length k, we must

establish the minimum value k that allows us to represent the #S elements of the set S. A sequence of k bits allows us to identify 2k different elements; the problem posed is the reverse one: given the number #S of elements to be identified, we must now determine the length k of the required sequences.

The notion of algorithm  An algorithm is the description of the solution to a

problem expressed in the form of a set of instructions that, by operating on the initial data, allow us to obtain results that constitute the solution to the problem. These instructions are determined by iteratively breaking down the initial problem into elementary subproblems, the solution to each of which is called a step of the algorithm.

First step with python: Python language has different properties and function so each word we use has a type, that is an object, and each complex sentence is called expression. The expression always causes an output (being a final return or an error). Python allows to assign the object used to the so-called variables, that are objects of a defined type. We can also name the variables and the object to memorize the object for further reuse  variables assignment, ex. print (x), type (x). Operations in Python: Commands in Python: Function, print (arg)* , like print (‘a text’, ‘2’, ‘print’), there is also the rule pf the triple quote “”” that determinate the priority between the “” and the “. Function, input (arg) , it displays always a string, received as a parameter, called prompt. Function, int (arg)  ex. name = int (input (‘give me a number: ‘))

Each Python expression can be interpreted as True or False and is evaluated by Python as True or False. While instruction: the while statement allows us to repeat one or more actions as long as a condition remains True  loop. Ex. Shopping, if the condition “my shopping list sill contains item” is true, the action “Buy next item and delete from the list” is performed and stop when the list is empty. For instruction: the for statement allows us to repeat one or more actions and performs these actions for each object in a sequence. Ex. Character: The sequence to the right of the in keyword in a for-statement must be an iterable, that are objects from which the for-statement can take one object at a time until there are none left. An example in

python is the list (a collection of items separated by commas and enclosed in square brackets). The range ()* function: create a list of number/object that are in the range set. Extended Assignment: Towards programs second part: In python the instruction follows the rule FIFO but if we talk about function instruction or function call, we follow the rule LIFO, so the last instruction is the first that is analysed. This is more efficient and faster and respond better to one to the principal aim of coding. Look at the example of the closed door in the different situation provided, for

each there is the right way to code. We analyse the algorithm (no order) and

the binary search (in which there are always two part and there is an order).

We can have different complexity of the algorithm: n, n/2, log n. Then in the worst case we have O (n^2 , n log n, n, log n, 1) while in best case there is omega in the different complexity (n^2 , n log n, n, log n, 1). Is important to reduce complexity, choosing the best algorithm also for the pollution that coding produce.

Sorting algorithm: the output is sorted the input that are unsorted, the outer for

goes in the right order from the first to the last minus one while the inner for consists in the elements that remain in the list that change the order every time an element is selected (they change the position with the element

Methods (functions of objects):

A method is a function that is called on an object, for example we can create a string variable s and assign the string object ‘Hello’, after that we called the object’s lower() or upper () methods which produce new string.

Visibility rules:

Each variable in the code has a scope, global and local variables are visible from the def part until the end of the block of instructions of a function.

Argument passage:

In passing by reference, the called function can directly access the value of the argument and modify it, if it is mutable. Python copies the object reference into that argument and puts it into the corresponding parameter. For example, if you write x = 7 x refers to (or "points to") the whole object that contains 7. No two separate objects can reside in the same memory area, so each object has a unique address. We can use the built-in id function to get a unique integer value that only identifies the object while it remains in memory. Differences between selection and bubble sort:  Selection  starts ordering from the head of an array  Bubble  starts ordering pairwise and at the end of an array A recursive version of search: A recursive version of sort, merge sort:

Data structure first part: Collection are data structure that consist of related data packets, like your favourite songs. Python built- in collections allow you to store and access this data efficiently. List (mutable) and tuples (immutable) have many features in common; both can store objects of the same or different type. List typically store homogeneous data, but this is not mandatory. To refer to a single element in a list, you write the name of the list followed by the index of the element: To find out the length of a list, just use the built-in len function. The use of a non-integer index of a list would provoke a TypeError. Remember that list are mutable objects, their element can be modified and added later. Using the + for two list the result is a concatenate list with the same sequences. Like we studied with for and range function you reach all the elements of a list: Tuples are immutable and usually, but not necessarily, store heterogeneous data. The number of the element cannot change but i can added other tuples. About tuples we can use some function like time_tuple to represent hours, minutes, and seconds. You can unpack any sequence by assigning the sequence to a comma- separated list of variables. A ValueError occurs when the number of variables to the left of the assignment symbol does not equal the number of sequence elements to the right. You can unpack strings, lists, and range sequences. The best mechanism for accessing the indices and values of list elements is the built-in function enumerate. This function receives an iterable as input and

Then we have the zip methods that enables to iterate contemporarily on two lists: The zip must have the same length. Dictionary is a data structure composed of a list of pairs keys-values, where each key associates with a value. The keys are unique but different keys can have the same value and there are many operations that you can do on a Dictionary and its data like adding elements, make iteration, update values or removing element. The multidimensional list: Lists can contain other lists as elements. Typically, these nested (or multidimensional) lists are used to represent tables of values, organizing the information into rows and columns. To specify a particular element of the table we must use two indices: by convention, the first identifies the row of the table, the second the column. Multidimensional lists can have more than two indices. Here we focus on the two-dimensional ones. Data structures advanced lists: For the Pythagorean table there are two alternative solutions. The first is import numby as np and code ‘pythagora = bp.zeros((10,10))’.

List comprehension: a concise notation to work with lists  Comprehensions in Python are a useful tool for machine learning and data science tasks as they allow for the creation of complex data structures in a concise and readable manner. Generative expression: generates an iterable generative object doing operations on list elements and producing values on request, generative expression does not create immediately a list but only returns value as operations on a list (more efficient). Partial function and passing a function to a variable: partial is a function in the functools module that allows for creating a new function from an existing function with some of its arguments pre-filled. Filter function  The filter function calls is_odd once for each value contained in the iterable passed to it as the second argument (numbers). The filter function returns an iterator; The list function iterates over the results and creates a list containing them.

NumPy array: Arrays are faster and more efficient than list, in big data application there is often a need for collections that are more flexible than NumPy arrays, like vector-like structures, one-dimensional Series and two-dimensional DataFrames. How to use it  firstly importing numpy as np, then we can use it for several things, like for creating and manipulating list. We can ask for the size, the shape of the array and also to iterate it: Many array operations are significantly faster than their corresponding list operations, the demonstration is to use %timeit magic command from IPython. Arrays operator: involve operation on single arrays elements, like number ** 2, then we can also make comparison and computations both on arrays elements and single axis. Indexing in arrays  the idea is to filter elements in long list of matrices: We can also copy an array or simply view it with this notation ‘number2=number.copy(/view)(), if necessary, it’s also possible to reshape and resize an array ‘grades.reshaped(…,…)’. Can be useful transpose an array, for example in math’s exercise, with the code ‘grades.T’. Horizontal and vertical stacking:

Series and Dataframes: A series object is a better one-dimensional array, because support custom indexing, with the ability to also define non-integers indices. They also offer additional features that make them extremely useful in many data science operation, in series object for example we can have missing data. To use series is necessary to import pandas as pd, now an example: Let’s see other example with loc, iloc and grades: String and RE: Strings are immutable objects. Besides it, their structure is similar to lists as well as some operations on them, the backslash ‘\’ character allows us write text on multiple lines when we use the console. As we saw for lists, strings are indexed, starting from zero. When we index a string, we get one of its characters (or letters). A single character is nothing special — it's just a string of length 1. Again, as with lists, we can use negative indexes for strings, where -1 is the index of the last character, we can also find a word in a sentence, split word or letter and count… String, method to control characters:

and the string to digit. Then we have the splits function that is used as separator and return a list of strings. The re.search function can be used also for choosing only the word with certain characteristic, like words that end with ed and that have 5 letters. Preparing Data: Data are often no ready, the process of preparing data is called data munging or data wrangling. Two important steps in it are cleaning data (delete, replace…) and transforming (standardize, combine, sample the data…) into a format that best suits the database and the software used. The action taken by data scientist can vary and are based on quality and nature of data. See exercise in the slide. Files and Data: In python is possible to save files, a file has two key properties, a filename and a path, that specifies the location on the pc. Folders can contain files and other folders, on mc paths are written using (/) as separator, initially we have to import Path from pathlib. Python’s with statement:

  • grabs a resource (in this case the file object of accounts.txt) and assigns its corresponding object to a variable (accounts in the example)
  • allows the application to use the resource through the variable
  • calls the resource object's close method to release the resource when the program reaches the end of the with statement block The with statement assigns the object returned by open to the account’s variable in the ‘as’ clause, in the with statement suite, we use the accounts variable to interact with the file and at the end of the with statement suite, it implicitly calls the file object's close method to close the file. The built-in open function opens the accounts.txt file and associates it with the file object. The mode argument specifies the file opening mode, indicating whether the file should be opened for reading (r), writing (w), or both. If the contents of a file should not be changed, open the file for reading only in order to not changing it. We can do something with the file (account.txt in our case) for example:
  • We use the with statement to update the accounts.txt file, changing the name of account 300 from 'White' to 'Williams' as described above
  • We can rename accounts.txt file and the new temp_file.txt. To complete the upgrade, we need to delete accounts.txt and then rename temp_file.txt to accounts.txt The JSON format: There are some web sites that collect all of the API Restful services that, when queried (via coding or with a user interface) will return you information in JSON, JSON objects are similar to Python dictionaries. Each JSON object contains a comma-separated list of property names and values, enclosed in curly brackets. The json module allows you to convert objects into the JSON format. This process is called data serialization. The dual operation (convert from JSON into objects) is called deserialization. Elaborate the content means serialization, deserialization and printing. Working with dataset: There are several sources where you can find.csv files repositories online, also Python provides many libraries where the access to dataset is integrated, for example. If i want to see the first or the last data set I type .head or .tail after the name, for example titanic.head and gccan also see more data from a data set extending display, pd.set_option(‘display.max_rows’, 10) and search a particular word or value (nan) through [r for r in titanic['age'] if re.search(r'nan', str(r))]. With non numerical data, describe visualizes different descriptive statistics:  Count is the total number of objects in the result.  Unique is the number of unique values in the result.  True (survived) e False (died);top is the value that more frequently appears in the result.  freq is the number of occurrences of the value of top. For example, if i want to see the statistics of survived i must type (titanic.survived).describe(). To see histogram of each column we need to call

the hist method.

Kaggle dataset: The dataset contains information on 53,940 diamonds, such as weight, cut, colour, clarity, depth, table (the flat top surface), price, and

We can have different plot (raw, box, violin…) that explain same data, it’s important to choose the best possible visualization model in order to get positive feedback and result. 5 Testable predictions on Data Visualization:  impresses for the sheer quantity of information that can be rapidly interpreted if it is presented well  allows the perception of emergent properties that were not anticipated  often enables problems with the data to become immediately apparent  facilitates understanding of both large-scale and small-scale features of the data  facilitates hypothesis formation Graphs, context, scales, visual cues and coordinates have their specific grammar, for example we can see the visual cues one: a line signifies a phenomenon on the plane which has measurable length, no area but can has a characteristic mark and it has a direction, a point represents a location on the plane that has no theoretical length or area but it has a position. an area signifies something on the plane that has a measurable size. In general, the more important things in data visualization are title (sub-title), tells context in some way, the scale and the way to communicate data through plot or graph. A graph can contain different visual cues and it’s important to be able to individuate all of them when an analysis is going on. The most common error are to confuse orientation with length and values with colour that often are the “same”. Visual cues:

In order to work with plotly in Spyder is necessary to install it: https://plotly.com/python/getting-started/ Important plotly modules are Plotly.express (used for creating simple charts with minimal code, you can pass the dataframe, and for x and y parameters you can just pass the column name, as it is compatable with pandas dataframes) e Plotly.graph_objects (used for creating a wide range of charts and graphs, we cannot pass the data, we can only pass the series for x and y parameters). It's possible to use graph objects for further customizations: