Docsity

Appunti di "Machine Learning - Labs of Python", Esercizi di Machine learning

Anteprima parziale del testo

Scarica Appunti di "Machine Learning - Labs of Python" e più Esercizi in PDF di Machine learning solo su Docsity!

PYTHON LABS

Machine Learning Course A.Y. 2019- 2020

Chiara Gasparato

Politecnico di Milano

Python – Introduction

Jupiter Notebook

Python creates a server trough the webpage that is in your computer

Closing the window won’t stop the server. To shut down you need to do it through the Kernel - > Shutdown

We can put some text or Python commands in each cell and then execute them

If I just want to put some texts, I can write the text in a cell, then go to Cell – Cell Type – Markdown

The numbers near to the cell indicates the order through which commands are executed

Staying on a cell marked blue, we can press dd to delete the cell and b to add a new one below

Zero-based index: an array of 5 will be from 0 to 4

sum_squares=0 (initialization)

for i in range(5): (that’s to say that the cycle will be run 5 times)

s = i**2 (the two asterisks indicate the power)

sum_squares = sum_squares + s

print(sum_squares)

OR

sum_squares=

for i in range( 5 ):

sum_squares+=i**

print(sum_squares)

We don’t need any kind of bracket

In Python we can have a list with different type of data, even multiples in one single list

mylist = [2,5,1,9,"learning",0,"machine"]

The list is defined with brackets

We can also have a list of list, such as alistoflist=[[1,2],[True,False]]

It can also happen that the dimensions of the list are different

To verify which kind of data we are dealing with, we can use type() and it shows the type of the object into

the brackets

List slicing: advanced way to get more components of a list at the same time

mylist[-1] means that we are dealing with the last element of the list

mylist[1:3] where 1 is included and 3 is excluded, so if the list is:[2,5,1,9,"learning",0,"machine"]

We will obtain:[5, 1] (this because Python counts from 0, so the first position is 5)

mylist[:2] : we will obtain the elements until the second- 1 position

mylist[1]="hello" : redefine what’s in the first position

mylist[0:2]=[5,2]: I change the values in positions 0 and 1 with numbers 5 and 2

If I have concatenated lists, typing alistoflists[x][y] I want as output the position y in the sublist x

I can also sum up lists through mylist+mylist (I obtain a single list with values of both)

for i in data:

if i < min_value:

min_value=i

elif i > max_value:

max_value=i

return min_value,max_value

data = [2,3,1,6]

minmax(data)

IF

def is_multiple(n,m):

if m!=0 and n%m==0:

return True

else:

return False

is_multiple(10,2)

n%m tells you the rest of the division between the two numbers

FOR

sum_squares = 0

n = 5

for i in range(n+1): #I put the n+1 because I want to get until 5, otherwise I would come to 4

sum_squares+=i**

print(sum_squares)

WHILE

def is_even(k):

while k>0:

k-=

return k==0 #either we finish with 0 or - 1. This “return” gives back the result

The difference between k=0 and k==0 is that with == I assign the value 0, in the other

one I make a comparison between k and 0

is_even(21)

How to import modules in Python? (this in order to compute things not inside the Python basics)

import math

from math import factorial

In this way we just import a function inside that module

We might also go for creating our own function

Numpy Library (Numerical Python)

Computation on N dimensional lists, faster with big lists

import numpy as np (from now on, numpy will be called with “np”)

np_scores=np.array(scores) # I transform my Python list into a numpy array

Using this list like this, it will run faster

The result will be True or False

The problem is that the syntax used for lists is not working (for instance, the + used to concatenate two lists

does not the same on np_array)

With numpy, the operations will be made on the single components of the array

import numpy as np

scores=[24,23,30,29,17,16]

np_scores=np.array(scores)

np_scores*

scores*

np_scores>=

An array is bigger or equal than a value à comparison with each element of the array, component by

component

np_scores[np_scores>=18] will show us the components of the array that respect the filter

2D Numpy arrays

A way to construct those arrays is through a list of lists

scores_1=[]

scores_2=[]

np_2d_scores=np.array([scores_1,scores_2])

np_2d_scores.shape will get back the number of rows and columns of the built matrix (n,p)

To select some elements from matrixes we use the notation np_2d_scores[x][y] with x as the row number

and y the column

To select many elements in certain rows or columns we use np_2d_scores[x,y]

We can also create 3D matrixes putting together three dimensional arrays

Pandas

Mainly used to manipulate Databases

We create a dictionary in which we have the keys of elements (the key is the column’s name while the

elements are the values of that data point)

We can assign a name to rows with ranrest.index=[“ “, “ “]

Really difficult to build it! à Easier to import from a csv (from a database to a dataframe)

dataframe=pd.read_csv(“file_name.csv”, sep=”;”, index_col=0) (from pandas “pd” we use the

function read_csv) (the separator is important, we tell how are columns separated)

Putting index_col=0 we indicate that the first columns gives the name to the first column, the keys of the

rows

dataframe.head() will show just the first 5 rows

dataframe.tail(2) will show the last two rows

dataframe.sample(2) will take 2 samples from the dataframe

Arrays in Pandas are called “panda series”

With two brackets restaurants[[“x“]] we will obtain that column x but maintain the structure of the

dataframe, otherwise with just one bracket we’ll obtain just an array

We have two other different ways to select:

[24, 23, 30, 29, 17, 16, 24, 23, 30, 29, 17, 16]

array([48, 46, 60, 58, 34, 32])

array([True, True, True, True, False, False)]

array([24,23,30,29])

data.dropna() will drop the rows with at least one NaN cell

data.dropna(inplace=’True’) will allow to drop NaN on the same dataset we are considering,

otherwise we need to assign the dropna to a new dataframe to have the NaN values cancelled

data.dropna(axis=’columns’) when we have a NaN in the column, we remove columns that have at

least one NaN cell type

data.dropna(how=’all’) drops the rows where all elements are missing

data.dropna(subset=[‘ ‘]) will define where to look for NaN

Data Standardization

If we have different orders of magnitude of the variables, we might need to standardize data, most of all if we

are dealing with the creation of a prediction model

sklearn is the library dedicated to this

These libraries also contain lot of datasets

We are going to create a dataframe out of the dataset contained in the library as:

df=pd.DataFrame(dataset().data)

Then, we will need to rename the columns getting the name of columns and assigning them as names

df.columns=dataset().feature_names

df.describe() will give some information such as mean and standard deviation for each row

It’s easier to plot them, recalling the plots from the library, for instance through a boxplot

From the plot is noticeable that not all the columns are in the same order of magnitude

%matplotlib inline: the plot will appear directly below the code cell that produced it

How to deal with this?

  • MinMax: transformation in the range [0,1]

This is made just dividing by a constant that will allow us to scale the values into a particular range

We are going to apply a particular function on problematic columns

For each element of the column I will apply the function lambda x that will divide each value by 10,

assigning the result to a brand new column of the dataframe

Plotting the new column we notice that the values are squeezed and more in line with the other

columns of the dataframe

  • Standardscaler (from sklearn.preprocessing import StandardScaler)

Once that I have computed the mean and scale (standard deviation) of each column, data will be

scaled to unit variance and mean=

scaler=StandardScaler().fit(df) will assign to the variable scaler the mean and std.dev. of df that

can be later used to scale the values

scaler.transform(df) will perform the standardization by centering and scaling

This function will scale values inside, then we will need to create a new dataframe with scaled data

  • Linear transformation and put it in a particular space. This is called MinMaxScaler

With this method, we don’t need to create another dataframe, previously we needed to do it

If I do not indicate anything, the range will be taken from 0 to 1. If I want a different scale, we need to

indicate it with feature_range(x,y)

scaler=MinMaxScaler(copy=False) will perform inplace normalization

scaler.fit_transform(df) will fit and then transform data belonging to the dataframe

Outliers

We can interpret the boxplot in different ways

For instance, we can notice that is not a normal distribution, we have lot of points over a certain threshold

Might be that those outliers are not really outliers, they are just really distant from the mean because of the

distribution

Standardizing data we can understand if we are really dealing with outliers

This is a way to understand outliers that can work only on certain distributions

Data visualization

Seaborn: library to make graphs

We create a dataframe through Pandas by the dataset

boston_df.hist(column="DIS", bins='auto') where column defines the values to plot and bins the

number of bins in which the data will be divided into

We want to see if one column follows the normal distribution

Boxplot: is the distribution normal? Might be, but with a different visualization tool could be more powerful

describe() will show us some information about data (mean, quantiles,…)

Before comparing the two distribution in order to check the normality of ours, we need to standardize data

How to compare distributions? à Q-Q plot

Scaler: apply it in order to have data on the same scale

The problem is that the scaler gives as output an array of arrays, where each array is the value scaled

A solution is to flat the array, transforming it into a simple array .flatten()

The distribution is now from - 4 to 4, the only difference from before is the range, given by the scale

We have to check whether it’s normal: the check is done generating some probability distributions that will

be further compared to ours

From the scipy we can use some statistical tools to generate samples

I want to get some parameters that can allow me to fit a normal distribution to mine

The observations have already been scaled

Then, we can get the parameters that will fit the normal distribution into mine

The parameters will be (-1.3736…,1)

To create a certain distribution we use: dist= getattr (scipy.stats, ‘uniform’)

The parameters to fit the normal into our distribution are: parameters = dist.fit (our_data)

We generate a sample trough the function ‘ rvs’ of the same size of our data, with a certain distribution given

by the previous parameters, mean as ‘loc’ and standard deviation as ‘scale’

test = dist.rvs (*param[], loc=param[], scale=param[], size=len(our_data))

Creating the percentiles and then generating the Q-Q plot we find that the normality is not particularly met

Percentiles are created through the linspace function, that has the starting number, the end value and the

number of samples to generate and then adapted to the distributions through:

q= np.percentiles (input_array , percentile_value)

Size has to be put big enough, for instance equal to 500

where ‘i’ is corresponding to the row number.

Inside the function we have the x we want to

consider, the y and the text ‘i’ we are going to

write for these coordinates

Once that the plot has been drafted, we might

draw some conclusions looking at the

observations and their positioning

For instance, points 4 and 6 have a great positive

value for PC1, meaning that the structure is bad,

while they have a great negative value for PC2,

meaning that this location has a good service.

Considering again the breast cancer dataset, we make the transformation with the standard scaler and then

consider a new column called target, that is 0 or 1 if the cancer is good or bad

Then, considering two columns we try to understand which are the best characteristics that can best describe

data, but is difficult. We need to perform PCA, that considers a linear combination of two variables

We take the first 10 PCA components, then we transform data and put data in the new coordinates

Plotting the PCA, we understand that the first component will explain just the 50%

Taking 10 variables, this mean that something is lost. But we are sure that this is possible because the new

variables explain the dataset

Recalling the target and taking the first two components, we see that is much easier to separate the two

groups, the PCA is able to make a good separation then simplifying the classification problem that might

come further

Actually, just with the first component we have a good explanation of data (understandable that under 0 we

have target=1)

Minka’s MLE will tell us the optimal number of components typing:

pca = PCA(n_components=0.9,svd_solver='full') where 0.9 is the percentage of variance you want to

explain

n_components=0.9 I need enough components to explain at least 90%

Classification

The algorithm has to be defined to classify the data

K-nearest Neighbor

st

: the dataset is drawn from pandas as diabetes.txt

The last columns (Target) classifies the rows between 0 and 1. We need to find the way through which the

target is set, finding an algorithm to predict the target given the other variables

First command df.info(verbose=True) is to understand the space on the memory occupied by the dataset

Then, we check whether the dataset is complete

We move our dataset into a dataframe and compute isna() to find NaN values

Then, we can also compute the sum in order to understand how many NaN we have

Graphically, we can plot the boxplot to see the distribution and identify possible outliers

We can also use the histograms to see how every column is distributed

We are particularly interested in the target columns, for this reason we see how are 0 and 1 distributed

We take the dataframe and groupby the target df.groupby(‘target’)

Then, we can get the size of the groups; we have 268 1s and 500 0s

We can make a barplot of the target to see how is distributed. This barplot is made through:

target.plot(x=’ ‘, y=’ ‘, title=’distribution of target’, kind = ‘bar’, color=[ ])

We have more zeros than ones

This is important to keep in mind because in the test set we will need to maintain this proportion

First of all, we need to remove the target column as it will be the response of the algorithm, that needs to be

created without the result

x will consider all the columns apart from the last one

y will be the vector considering the ‘target’ column

Now, we split data into training and test set. The splitting will be done through:

X_train, X_test, y_train, y_test = train_test_split(X, y,

test_size =0.30,

stratify=y,

random_state= 123)

where the function ‘split’ is obtained by the sklearn.model_selection libray

x as independent variable and y as dependent

Both x and y will be divided into two sets, one training and one test

Blue is the proportion of 0s and 1s in the test set

The thing is that the proportions are different à stratifying the y, we will obtain exactly the same proportion

We can also compute the proportions values

Now we can build the classification algorithm

The first model can be the K-nearest neighbor

Supposing a new observation, what color will it be?

Qualitatively, the new observation might be red as there are two reds in that space

We will see that taking the first three neighbors, two of them will be red

The parameter that might be changed is K; now we are using three, but we might go for five

Considering 5 nearest neighbor, the majority is blue

We have a method in the sklearn to classify by nearest neighbor

sklearn.neighbors import KNeighborsClassifier

We create the new classifier with the parameter=3, the neighbors we want to consider

Then we fit the classifier into our training set knn3.fit(X_train, y_train)

Using the train sets both of dependent and independent variable, we are going to create the algorithm

Then, we predict the Y on the test set through the X on the test set: Y_pred=knn3.predict(X_test)

What changes with other classifiers is just the knn3, the classifier itself

Now, we have to compare the prediction with the Y_test, understanding how good the algorithm is

We create a matrix through the sklearn library and metric object

metrics.f1_score(y_test,y_pred))

We can use the accuracy, recall,…

With no really good results, we might change algorithm

Which are the alternatives?

We can change the parameter to do better and try to understand which is the best K

Represents the proportion of

the dataset to include in the

test set. By default, is set to

Conversion of categorical data

In case we are dealing with categorical data, we need to pass from this:

Type

To this:

This can be done through the pd.get_dummies()

Balancing

This is needed whenever the target variable contains a great majority of one type with respect to the other

Building the model on this situation would bias the result, giving always the majority class target

For this reason, apart from choosing an evaluation metric different from the accuracy, we can perform a

downsizing through: resample(df_majority (column with the major class), replace=False, n_samples=

(number of the other class records), random_state=seed)

Classification Task – Generalities

  1. Separation between independent and dependent variables
  2. Define the model we would like to use
  3. Find parameters and the best ones through the GridSearch
  4. Select the best score and choose the best model with those
  5. Predict into the test set the independent variable
  6. Save the predictions into a txt

Decision Trees

Data is separated in two ways:

  1. Explanatory variables and target attribute
  2. Train and test data
Simple Regression

Relation of the variables with the target variable

The main aim is to predict the target column

Seaborn: we make some plots fixing the target variable and changing the x-axis

The last plot shows a certain relation between the variable on the x-axis and the target one

Take two groups, train and test set, taking only the x columns

In this case we are performing a simple linear regression, meaning that we just take one variable

Import from sklearn.linear_model the LinearRegression, creating a regressor and fitting it into the

training set

Now, we need to find the best parameters through the GridSearch

Some of the parameters of the LinearRegression() function are:

  • fit_intercept: the model is going to pass from 0 or not, hence finding the best intercept
  • normalize: pre-normalization of the variables
  • copy_x: replace the values with normalized values

We can try both normalizing and not

The best is normalizing it

We can now apply the model to the test, as to see how the score is

Actually, we are scoring 0.45 on the R

2

, not so good

Is this a good model? How can we say it?

We need to analyze the errors and how are distributed

We compute the error for the train and test by computing the difference between the predictions and the

real values

The error distribution should be a gaussian

However, the percentiles and the standard deviation do not seem really normally distributed

We need to check it

We can do it by a scatterplot with the prediction and the errors

The plot doesn’t seem normal

Normality Test

Standardize data but we get an array of arrays, hence we need to put the flatten

The histogram does not show a real normal

Making the Q-Q Plot, we do not obtain the dots following the diagonal à Not normally distributed

We can do some hypothesis test: Kolmogorov-Smirnov Test, D’Agostino Test,…

Kolmogorov tests one distribution comparing it to another distribution

The test is included in the scipy library

I expect a low p-value in order to reject the hypothesis of normally distributed errors

In this case, the p-value is really small, I cannot say that the H 0

is valid

The other test also gives a really small p-value

To do better, we can introduce more variables, thus performing a multiple regression model

We add the LSTAT, even though the relationship doesn’t seem linear, seems negatively exponentially

correlated

We apply the logarithm and the plot betters a little bit

Computing the correlation, we can try to understand which are the mostly correlated variables

The two that are more correlated are RM and LSTAT with 0.7 and - 0.74 (with one growing, the other grows

too and viceversa, in a negative way)

RAD and TAX are highly correlated, thus it makes sense to take just one of the two, they are similar, it does

not make sense to take both of them

We select the data we aim to use

The perfect model would be the one which let us obtain a perfect diagonal

The OLS can show us which are the best variables

The best model results to be the one with logarithm of LSTAT

min # 𝑒

!

%

%

Lasso:

min # 𝑒

!

%

What changes is just how they behave with big values

With small c, I do not consider the generalization capability of the model and I weight more the residuals

In the algorithm, c is substituted by alpha

Intercept: y 0

Coefficients: ω

Neural-Network Regressor

As for classification, we have the input layers in which we put our parameters and then we try to combine

them through hidden layers and obtain a single output layer

Each parameter is multiplied by a weight, how important is that parameter

In each hidden layer we can apply an activation function such as the sigmoid

The last node is obtained through a linear combination of the last nodes trying to obtain the smallest possible

error

max_iter: this is the number of maximum iterations, the minimum is considered in this number of iterations

The errors are little, big just for two observations

The problem here is that in the train we have a little error whereas in the test set is higher, this means that we

are dealing with an overfitting model

The algorithm is behaving well in something he knows; once that he performs on unknown data, the

algorithm performs really bad (MSE on the train is 1.45 and on the test is 9.1)

Support Vector Regressor

Very good results, the errors are close to the zero

However, train and test set results are very far

In general, the results will be closer to the test results, not to the train

Clustering

Assign every record to a group in such a way that we are far from records of other groups and really close to

the similar ones

K clusters

Assign some positions in the n dimensional space of the features to the centers of the clusters

Then, we assign to every center the observations that are closer to one of the centroids

All the observations will be multiplied by the matrix in order to expand data in a direction and shrink in the

other, changing the scaling

y

0

ωx

k-means

KMeans function

The parameters are:

  • n_clusters: number of clusters to form
  • init: methods for initialization
  • max_iter: maximum number of iterations
  • random_state
  • tol

km.fit and then km.predict to predict the clusters

We get the groups and the centroids

The centroids can be found through .cluster_centers_

We need to look at the clustering quality to understand if we can do better

In particular, it can be measured as .inertia_ , that is computing the sum of squared distances of

observations to their closest centroid

We can try to insert more clusters and find the best number of them, then measuring the distortion, the

quality measure of clusters

But how to decide the optimal k?

We can use the “Elbow Method” , plotting the values of the k

on the x-axis and then the distortion on the y-axis ,

understanding which is the optimal value of k

From the plot we can notice that distortion is decreasing

(the best k should be 3); however, is decreasing to the

infinite, so is difficult to decide

How can we decide if we are in a better situation?

à Silhouette analysis

2,3,4 cluster and have them compared

Library to compute the silhouette

Silhouette: Minimum value of the intra-class distance compared to the distance with outside clusters

!

!

max

!

!

where 𝑢

!

=intra-cluster distance and 𝑣

!

=nearest-cluster distance

Expect that the distance in the cluster is smaller than the distance with others, being well separated and

dense within the same belonging-to cluster

The best value is 1, meaning that I am really far from other clusters

If value is close to zero, then clusters are overlapping

silhouette_samples(dataset, clusters, metric=’ ‘)

Plot the values of the silhouette, we get a good result as we have all positive values

Ranging the number of clusters, do predictions for each of them, we can plot the results

With n_clusters=2 we get a 0.62 as mean silhouette, with lot of observations getting a really low silhouette

This because we have some observations that are almost at the same distance from the two clusters

k-means is not a good model with the rounded data

What we can do is changing the system of coordinates, from cartesian to polar, using the angle and distance

from the center

Even doing it, k-mean is not able to do it because we have really stretched data on the y-axis

We can scale data and, in this way, can work

Hierarchical methods

Distance between every pair of points in a matrix

How to decide the number of clusters from the dendrogram?

New function called sq applied for a parameter i

While i is positive, I subtract 4

If the number is still positive, I subtract 4 until the number becomes negative

Return TRUE if is 0 or - 2, FALSE in all the other cases

It works with positive and even numbers plus the zero and - 2, it won’t subtract anything but is equal to

0, will return TRUE

Theoretical Questions

  1. Which ones among the following answer is correct?

A. Ridge Regression cannot be used is the matrix X’X is singular

B. The hat matrix is defined as 𝐻 = 𝑋(𝑋

&

'$

C. F-statistic is defined as 𝐹 =

(

!"" #$#

%

)

""&

'(%

D. Ridge regression requires to solve the problem min

E. The adjusted determination coefficient is defined as 𝑅

+,-

%

%

.'$

.'"

F. None of the answers

B: Minimize the sum of the squares and we will obtain H

The problem is that I cannot invert it

To reduce the space in which I am looking for the solution I need to insert a penalization term,

like in the Ridge

The minimum coming from the penalized problem is different from the other one

Ridge is made to overcome the problem of the matrix singularity, that’s why the first is wrong,

Ridge born to did it

D: wrong, Ridge is using the square, here we are putting the Lasso

In a more practical way, better to use the squares because is differential in all the domain,

instead the norm is not defined in the zero

C: The F-test finds the distribution of the variance. SSE is already normally distributed, we

need to use an unbiased estimator for variance

∑ ( 1 )

' 2 )

.'$

E: The adjusted has got m-n-1 on the denominator

  1. Which ones among the following is correct?

A. The split at a node can be done my maximizing the Gini Index of the descendants

B. On support vector machines the objective function is

$

%

!

C. A classification tree is said multivariate if more than one variable determines the path from one

root to each leaf

D. In logistic regression it is assumed that 𝑃

$ 4 *

1

$ 45

,

E. A Bayesian model is called naïve if only simple hypothesis are involved in class prediction

F. None of these

The answer is: F

A: Gini and Entropy try to measure the disorder

We want to minimize the disorder, having just ones or zero in a group

Disorder in the son should be less than in the father node, the partition improves

I want an improvement, thus is false

B: there should be a squared in the normalization term

C: multivariate tree means that we have linear combination of variables, we can cut the space

also in diagonal, not just horizontally or vertically

E: Naïve means that variables are independent

D: sigmoid to a linear combination

  1. Referring to ROC Curve, which ones among the following answers are corrects?

A. The ideal classifier corresponds to an area under the curve equal to 0.

B. A classifier with no parameters to be tuned yields at 45° line in the diagram

C. The point (0,1) represents the ideal classifier

D. The trajectory of the curve is based on the combination of different classifiers

E. A classifier is preferred if the area under the curve is larger

F. None of the answers

The ideal situation is to have zero False Positives (x-axis) and 1 True Positive (y-axis)

E: correct answer

F: wrong

D: we have one curve for each classifier, is not true

C: true, zero FP and 1 TP

A: false, the ideal would have 1 as area

B: the 45° line is using the random classifier, thus is not true

  1. Referring to the table, which ones among the following answers are correct?

Positive Negative <- classified as

Positive Negative <- classified as

60 40 Positive

0 100 Negative

A. The recall is 1

B. 80% of the instances have been correctly classified

C. The precision is 1

D. The TP rate is 0.

E. The dataset is unbalanced

F. None of these

Recall: TP+FP/TP

A: false, is 60/

B: 160/200, that is 80%

C: Never fail when I put the positive, thus precision=

D: 60/100, thus is true

E: wrong, we have a totally balanced dataset, same number of real 1 and 0

  1. Given the following histogram, which ones among the following answers are correct?

A. The density of x is skewed to the left

B. The 89% confidence interval is given by 66.99 ± 4

C. The density of x is normal shaped

D. The 95% CI is given by 66.99± 8

E. The 68% CI is given by 66.99± 2

A: False, is centric, the order of magnitude of the skewness is really little compared to the

mean

Skewness: unbalanced to the left or to the right

C: True

In our case, the mean is 67 and the standard deviation is 2, the root of variance