Docsity

Appunti Machine Learning, Appunti di Machine learning

Anteprima parziale del testo

Scarica Appunti Machine Learning e più Appunti in PDF di Machine learning solo su Docsity!

MACHINE LEARNING FOR ECONOMICS s Machine learning and friends. ca . ARTIFICIAL INTELLIGENCE ‘Any technique which enables ‘computers to mimic human behavior MACHINE LEARNING ‘Al techniques that give computers “lf the abiltyto leam without being — [DEEP LEARNING explicitiy programmed to do so A subset of ML which make the dB computation of mult-Jayer neural networks feasible | x J J L T Th % Î Ù Ù Ù LI 7 19508 19608 19708 19808 19908 20008 20108 ARTIFICIAL INTELLIGENCE is the science that allows machines to act like humans by replicating their behavior and nature. MACHINE LEARNING algorithms are ‘designed insuch a way that the machine tries to learn by itself without being explicitly i programmed for each and every instruction. The machines learn and make predictions based on their i experience (data ) Can the machine recognize a ‘number? | We want the machine to recognize a “number: is this a 1 or a 7? This number is a 1 This number is a 7 Can we. define some RULES?. That is basically a collection of IF-THEN EXPRESSIONS. Using. these rules, we can classify the prediction of numbers. . For instance, the angle (A): -* -IfA<45,thenit's a7 - If A> 45, then it's a 1 These rules are subjective, in this example depending o on how the‘ 1 and 7are written. i But the reality is more complex, and we add new information to our Ir algorithm: angle (B). The set of rules involves A and BL - I{A< 45 and B>45, then its a7 - If A>45 and B< 45, then it's a'1 THE MORE COMPLEX THE SITUATION, THE MORE COMPLEX THE RULES. Sometimes the reality is so complex that many ‘rules are created and it happens that they refer to s specific cases s and we are not able to generalize. RULE- BASED APPROACH: A set of if- then rules that a machine i checks to obtain a prediction about the numbers. Can we define an algorithm (if- then) capable of recognizing handwritten numbers? 00004910020 000042000 {NI\I/Z/{ZI\{T{IAXN\4Z}I Rida 2422 IT 22221222722 33333335353333333 L1GFLLAFSYNLSFLFI4HTINLA STESSESISSSSESTSSL5S5 6 G6LLGE 6 666 6 € 6 66 s77197711979221237?7? o 3 BEEPLTERASSIFT? I P°ÎO1ILALIAGZAAILA 141499 In this case, things become much more complicated, and rule- based recognition requires complex rules (which may fail dramatically). So, we should change our perspective. We teach the machine to recognize the number using DATA through an ALGORITHM. Machine learning and statistics. Statistics i ismuch older than ML because we e needed more computer power and more data (see the example). Definition: "The science of learning from data, and of measuring, controlling, and communicating uncertainty." Instead, when we use ML, there is NO UNCERTAINTY. There is an intersection between ML'and statistics, the OLS model is the same. ONE DOES NOTISIMPLY, 2064 2019 Ye Bxse [N=BX4 i SME RUN ATREGRESSION AND CALLIT STATISTICS | Hacuive LEARNINO 9 R10 YEARS CHA LENOEI Statistics Wont Machine » i 4 General problem STE ee aa Supervised.problem with one.response variable.Y (which is continuous) and p regressors. l . Yaf)+ where fis is an unknown function and e £ is s the error term. Our aim. is to compute the relationship between Y and X. Normally, the MODEL-DRIVEN estimation, we assume that the model generated the data, and we estimate the parameters that a are most likely to be true EES. All the cases present in reality are more complex, and the statistics have limitations, so if the model is wrong, our estimation is wrong. The goal of statistics is ERPLANATION giving information about the ‘expected fp. In machine learning, we don't need to have a model, which is DATA-DRIVEN because the data speak about the relationship | between Y and X. We give some inputs to our algorithm, and the more interestirig thing is PREDICTION. Given my model, we only predict my data. Basically, fis a function, but we don't write an expression: It is a sort of BLACK-BOX (algorithm); something - happens, but we don't-know what it is. The only oi is the- HUGE DATA that they need to- function. If we join together the strengths that'we have in'statistics and ML; we obtain STATISFICAL LEARNING = MACHINE: LEARNING + - STATISTICAL MODEL. Different teminoligy Statistics Machine Learning Response/dependent variable Y Target variable, output Predictor, independent variable X Attribute, feature, input Samples, observations (i,Yi) Instances, examples Estimation, fitting Learning Some examples Dermatology-level:(deal) We would like to have ‘an algorithm that can-classify skin cancer - with deep networks, but it.is very.complex because there are many features: shape, color,.etc. The output.is usually explained as the arobabily that it can hiba cancer. Mitigation of AI/ML risks The SAFE approach (Giudici et al. (2024)): - SUSTAINABILITY: (siliheo oi AI SARDE UMILI AeMiaiou: ‘ extreme events; ‘ * : - ACCURACY: predictive accuracy of model outputs; * - - FAIRNESS: absence of biases toward ae . induced by AI output; . . * . - EXPLAINABILITY: capability of model sumput to he . . understood and overseen by humans, particularly.in its . driving causes. — Variable types:-c2 - i 5 De . * . QUANTITATIVE VARIABLES: These.take on numerical values. . (e.g., income, stock price, score, etc.). . . » . QUALITATIVE (categorical/factors). VARIABLES: These ue. . on values in one of K different classes or categories (e.g., . male/female for gender (1/0); yes/no for a fraudulent financial transaction, ...). Categorical variables are usually represented numerically b )7 codes. Supervised vs.-unsupervised learning Supervised Learning Unsupervised Learning (Classification Algorithm) (Clustering Algorithm) Predictive Model — (Unsupervised Learning Predictive Model Supervised learning: Considering the first example (Table 1), we have a column that contains the response variable (the riumber in the picture), and then we have all the regressors (all the colored pixels). The purpose is to fit a model connecting Y on X that predicts the number in the image. - Consider the left picture. The response variable is represented by” the duck, and all the characteristics are the tegressors (human effort to recoghize these). You need to fit/train the model with a lot of data: (more animals) and provide this table to our algorithm: This algorithm-learns how to detect if it is a duck or not according to the characteristics contained in the regressors. . Next, we make. a prediction on one animal using the supervised . model that.we have trained before. The model predicts.a certain . probability that it is a duck. In this case, the prediction is good. Now, we remove from our dataset the response variable that we have just tested and use this for checking how well the model performs because we know that this observation is correct. So, the model is fitted using the remaining observations. What should we do? Leave some observations out and not use them for fitting, but to i supervise if the prediction is correct or not. i Unsupervised learning: In the right picture, we have a ‘bunch of variables. We don't i recognize the input and the response variable, but we just define our observations in GROUPS or CLUSTERS that are similar to each other. The aim is not to focus on the prediction. iti is just to explore ue Hate: If we want to create a relationship between x and v, we start with this ‘approach: Y=f)+e where: ‘ I - © fis FIXED er deterministic); and there is ‘s nothing random :» inside it; i * . *.. £ is a RANDOM ERROR term or residual. The idea is that - . there are many useful regressor that help to provide a . relationship between Y and X, but also there are other . elements that we are not able to explain, so they are 0 contained on the residual. Usually, it is distributed as M(0,02). Statistical learning refers to a set of approaches to ESTIMATE.f using the observed data. The prediction will be denoted by f and. we want as the most precise as possible. This estimation is important for two purposes, if we are statistician we want to do parameter INTERPRETATION and explain about X and Y or for pure PREDICTION, in that case fis a black box (algorithm). Two aspects: relationship Y and x (inference) or r predict Y given X (black box model). Goal of.statistical learning Trade-off between.PREDICTION ACCURACY. (model fitting) and MODEL SIMPLICITY/INTERPRETABILITY. Suppose to have models with different complexity, but with the same capability to.explain, we choose the simple model. INCREASE COMPLEXITY gg MORE ACCURATE [gd BETTER: PREDICTION |a LOWER INTEPRETABILITY. - Usually, machine learningrmodels are more complex than statistical models (random forest vs: linear regression). Stop and think Example: We collect a set of data on the top 500 firms in the US. — For each firm, we record profit, number of employeés, industry, and the CEO salary. We are interested in uage:standng; which factors ‘ affect CEO salary. i i + Classification orregression? regression; » . Inferenceor prediction?.inference because we want to know. . the factors that influence the salary. Example: We are consideringlaunching a new product and-wish to know whether it will be a success or a failure. We collect data on . 20 similar products that were. previously launched. For each product, we have recorded whether it was a success or failure, price charged for the product, marketing budget, competition price, and ten other variables. - Classificationor regression? classifi ication; |* Inference or prediction? prediction because only Ss or f not - the role of marketing budget on the sales. Example: We are interested in predictino, the % change i in the USD/ Euro exchange rate in relation to the weekly changes in the world stock markets. Hence, we collect weekly data for 2012. For each — week, we record the % change in the USD/Euro, the % change in the US market, in the British market, and in the German market. ‘ Classification orregression?regressioh; ‘ Inference or prediction? prediction. NON-PARAMETRIC method, for istance machine learning algorithm, basically we are not able to express f but you do not write down fas a function of some parameters. We have more or less flexibility, therefore more or less complexity, arid it'is required to have more data to train'the model‘and obtain'an accurate estimate. - Training error ‘ We start with an example, and we use simulation, namely a way to create artificial data. - er: ‘Y = sin(13x)+t15 + 3(x-4)? + £ Y is a quantitative response variable, and X is the regressor (p=1). It is not linear function. This f(x) is deterministic because if we‘ decide that X=0, sò Y = 48 + e. Finally, the error term is N(0,100). ‘ Suppose that X=4 then we generate two values from this model, the value of the response variable is different due to the RANDOM ERROR TERM. : I This problem is very simple if.we- 200 have information about X. Otherwise, we will have to.estimate £ 150 So we use the data to estimate our - model, it is.called TRAINING DATA, training, means estimate the f . . ESE 4° These 50 data are the-data that we - data. traln$yobs 27) 50 Pe n 3 i) have, and we implement a model.to - 7 predict Y, knowing.that the...) tn. relationship is not linear. . Here, we are considering a parametric model, and we start from YE Bo+e, so f(x) = BO (no x) MSE train = 3361.88 The black line is the FITTED MODEL, and the estimate of B0 is 51. The 8 model is constant or flat. odg * lee How do we evaluate the error/ | (la . accuracy? "a: ge Through MSE, in this case, it is called ne! TRAINING MSE because it is‘ computed through the data. data traina MSE, = iL MSE train = 1385.66 = iL If we use the famous /inear model, we cannot able to fit properly the true - + n 87 distribution because we do not capture i a ala the effect of the beginning of the.plot . ©]... a that is a negative relationship. . . —. > “a pe0) data_tran$x Compare this model (2) with the model (1), and we choose the model (2) because the MSE IS LOWER. MSE_train = 145.15 But we have again less flexibility, so the di simple way to introduce flexibility i in the linear regression model is through Ùg # POLYNOMIAL TERMS (X?), itis more‘ Sini E ue i i "| i, We prefer to have a model smoother (black line) and more close to blue line, so less flexible. Îf it is TOO FLEXIBLE (overfitting), itis. good only for that datà (50) and could be very PODR FOR OUT- OF DATA (data are not useful'for'training the model). The overfitting model is very COMPLEX and is so FLEXIBLE and ablé to OVERLAP THE POINTS (ERROR TERMS). The points are already'the points that we usé in the training. It is NOT the true relationship between X and Y-because the relationship is SMOOTHER. I O OI Summarize from example 1” Underfitting Desired —_Venrtitg OVERFITTING UNDERFITTING is when the model is.too simple R code’ n=500 x = seg(0,12, length =n) fx =.sin(13x)+1.5 +.3(x:4)?. set.seed(5) . Y = fx +.rnomal(n, mean=0, He sqri(1 00) myf = function(x){. fimeD . FUNCTI sin(13x)+15+ 3(x-4)? \ TRUE E ‘ FUNCI low library(tidyverse) ’ datà.frame[x,y) %>% ggplòt() + géom_ pulniaeria y)) + Heom Punederiduns yi: ‘col="blue",) Polynomial regression c3 Before, we used different models with different values of dthat belonged to the parametric model. We have used the polynomial regression model (similarto multiple regressiori model), with p=1, where the regressor is power transformed at order d, and we must to choose d. The main result is the OVERFITTING, which is determined by the presence of many power regressors, which give greater complexity. Y. Bi px sfociare It is'a lihear model'because we have linear parameters (linear B). we can estimate it and use, for example, OLS. i Which is the best value of d?° We know that the highiest'dimplies highest flexibility, and in the previous example we have compute the TRAINING MSE, distance between the observe value of Y and the predicted value of Y (predicted using in the model), we take the square difference and - we avereged (sum.and divide.for no. of training data). . ME ila) . . ne Gai And we.have said that it is not good approach, if we follow. this approach we choose the highest value, because it creates... OVERFITTING (model is very good for training data, but not good for new data). Is our out-of-sample prediction good? . . So we introduce FUTURE (NEW) DATA, we want.a model that . performs well and using these data we compute the OUT-OF- . SAMPLE ERROR, meaning compute the error not on the training — data (the data that we use to train in the model), but on new data. The requirement is that it belongs on the same distribution. Example: n. of bike rental (Y), temperature, rain... (X), suppose to have 1.000 rows, RANDOMLY we select 80% (800 rows) use for training the model), the rest will be use to testing the model (200 ‘ rows), in order to TEST HOW GOOD IS THE MODEL ON NEW DATA that we don't use for training, this 200 are new for the model. We fit the model (training data) and we compute the prediction given our model for these. TEST OBSERVATIONS, where we know . the value of y: mean((y0 to be precise) - y*0)?/200 observation. This is called TEST MSE, and it is an estimate because we use only a part of the data. Obviously, we want to minimize it. Using TEST MSE, we avoid having OVERFITTING. — 20 Red points (50) are the training = #{ + Traindata a datà, arid the green points (50) e Testdata * are the testing data, sò as | before we want to find the best value of d, we want to tune the 150 100 di” o best level of flexibility; < / --/- |a. di "v ie So we fit different models with. - SE % pe different values of:-dand we _ LL compute the TEST: MSE, we will “A do the prediction for each. STI RT green points with the values that we observe we take square the . distance and we average respect.to the all the green points. On X axis d (level of flexibility). il 5 ‘Training The blue line is the TRAINING 1| e Test MSE, but now we are interesting in 8.| the red line the TESTING MSE, we, || observe that the red line is almost di higher than the blue one, so we - 81 \ expected to do HIGHER ERROR. È ON NEW OBSERVATION. . si 4000 Mi 7001 E T T T T C) 5 10 15 20 Order d The yellow point represents the best level of flexibility. The blue should be 20, and instead, the red is 10. The best value is d=10, which is obtained for TEST ERROR (how we normally choose the level of flexibility). i Summarize what we have done, on the x axis we e have model | complexity/flexibility, the blu line is the TRAINING ERROR, which has decreasing pattern (monotonic decreases pattern), instead the TEST ERROR has U-SHAPE pattern, so decreases and then increases (start to overfitting the training data and it is not ‘able to generalize < on them new data). | € Underfitting ! Overfitting > Error Model “complexity"