Machine Learning (Kaggle - Intro to ML, Intermediate ML, ML Explainability, Feature Engineering)

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/73

encourage image

There's no tags or description

Looks like no tags are added yet.

74 Terms

1
New cards

Whats the goal of feature engineering?

Daten für Modelle und Algorithmen so aufbereiten, dass sie die Beziehungen besser erkennen können

2
New cards

Why do we perform feature engineering? (3 reasons)

Vorhersagen eines Modells verbessern, Rechenleistung oder Datenbedarf verringern, Wie kommt das Modell auf diese Vorhersagen – Verständnis erhöhen

3
New cards

Guiding principle of feature engineering?

Damit ein feature nützlich ist, muss es eine Beziehung zum target haben, den das Modell lernen kann

4
New cards

How do we find out which features are useful and how does it work? Which kind of relationships does it measure? Which scores are good? Whats the range of scores?

Mutual Info misst alle Arten von Beziehungen zwischen features und target, indem es die Entropie (= Unsicherheit) misst – es stellt sich die Frage, wie viel sicherer bin ich mir über das target, wenn ich dieses feature kenne? Dies scores gehen von 0 bis theoretisch unendlich, es gibt keine obere Deckelung. Je höher der score desto besser, wobei Werte über 2 selten sind, da der MI logarithmisch wächst. 0 bedeutet, dass die Variablen unabhängig sind.

5
New cards

Was bedeutet Entropie?

Unsicherheit einer Variable. Wie viel sicherer bin ich mir über das target, wenn ich dieses feature kenne? Es stellt ja/nein fragen um vom feature zum target zu kommen. Je mehr fragen er stellen muss, desto unsicherer ist dieses feature.

6
New cards

Worauf muss man bei der oben gefragten Metrik für beziehungen achten?

kann bei wenigen Daten ungenau sein. Es betrachtet jedes feature einzeln (= univariatische Metrik) – Features, die nur in Kombination nützlich sind, können niedrig abschneiden. Hohe MI heißt nur, dass Info drin steckt, ob es das Modell rausholen kann, ist eine andere Frage.

7
New cards

Whats the most useful tip on discovering new features as well as in data science generally?

Fachwissen ansammeln & Features kennen, am besten über die Datendokumentation

8
New cards

Was bewirkt man durch die erstellung von neuen features mittels einer rechnung (bsp.: Spalte 1 + Spalte 2)?

Man zeigt dem Modell die Beziehungen und erleichtert somit ihre Arbeit.

9
New cards

Wieso gruppiert man kategorien als eine feature engineering maßnahme?

Ein modell sieht immer nur eine Zeile, Statistiken über mehrere Zeilen kann es nicht selbst berechnen

10
New cards

Was macht .transform(‚mean‘)?

Es rechnet den mean pro Gruppe aus und gibt das gleiche format zurück wie der input – wenn zb. ein DF eingegeben wird schreibt es den mean jeder Gruppe in jede Zeile

11
New cards

Gib an ob richtig oder falsch: a. Verhältnisse sind für die meisten modelle leicht zu lernen b. Lineare Modelle lernen Summen und Differenzen natürlich, können aber nichts komplexes lernen c. Baummodelle können nur einfache Kombinationen lernen d. Counts sind hilfreich für baummodelle, weil sie infos über mehrere features nicht sammeln können e. Es kann für baummodelle besser sein, wenn man wichtige beziehungen explizit hervorhebt f. Normalisierung     i. Neuronale netze brauchen keine skalierung der features     ii. Lineare modelle und neuronale netze schneiden besser ab mit normalisierten features     iii. Baummodelle brauchen unbedingt normalisierte features

a. Verhältnisse sind für die meisten modelle leicht zu lernen (F) b. Lineare Modelle lernen Summen und Differenzen natürlich, können aber nichts komplexes lernen (T) c. Baummodelle können nur einfache Kombinationen lernen (F) d. Counts sind hilfreich für baummodelle, weil sie infos über mehrere features nicht sammeln können (T) e. Es kann für baummodelle besser sein, wenn man wichtige beziehungen explizit hervorhebt (T) f. Normalisierung     i. Neuronale netze brauchen keine skalierung der features (F)     ii. Lineare modelle und neuronale netze schneiden besser ab mit normalisierten features (T)     iii. Baummodelle brauchen unbedingt normalisierte features (F)

12
New cards

Erkläre die Begriffe unsupervised und supervised learning.

Bei unsupervised learning wird unabhängig vom target gearbeitet. Beim supervised arbeitet man mit dem target, also den „lösungen“

13
New cards

Was bedeutet clustering? Wieso nutzt man es?

Gruppieren. Weil man Werte zusammenfasst, die etwas gemeinsam haben. Das erleichtert das errechnen von komplizierten beziehungen durch die modelle.

14
New cards

Wie geht k-means clustering vor?

Es setzt eine k-Zahl an sogenannten centroiden. Die Punkte (Werte die auf einer Grafik dargestellt sind) werden dem nähesten centroiden zugeordnet. Danach wandern die centroide in die mitte ihrer gruppe und die punkte werden wieder dem nähesten centroiden zugeordnet. Das geht so lange weiter bis sich die centroide kaum mehr bewegen oder so oft wie wir es angegeben haben, dass es maximal durchgeführt werden soll. Somit zerlegt es die Daten in Gruppen, die nah beieinander liegen.

15
New cards

Was ist die Voronoi-Zerlegung?

Die Zerlegung der grafik in flächen, die anzeigen in welche gruppe zukünftig gruppen zugeordnet werden, weil sie in diesen flächen am nähesten zu der entsprechenden centroide sind. Für die erstellung dieser zerlegung werden kreise von den centroiden wie wellen ausgesendet. Dort wo sich diese Kreise mit den anderen Kreisen von anderen centroiden verbinden, gehen sie nicht mehr weiter und bilden eine schnittstelle. Wenn ein punkt auf dieser schnittstelle landet, ist es genau gleich weit von mehreren centroiden entfernt.

16
New cards

Was bedeuten diese 3 Parameter von k-means? a. n_clusters = b. max_iter = c. n_init =

a. n_clusters = Anzahl d. Gruppen, die man haben will b. max_iter = gibt an, wie oft es maximal die centroide in die Mitte der Gruppen bewegen darf c. n_init = gibt an, wie oft es die centroide an neue zufällige Stellen setzen soll und somit das algorithmus neu starten soll. Am Ende wird das Ergebnis mit der kleinsten Distanz zw. Punkten und Centroids zurückgegeben.

17
New cards

Braucht kmeans skalierte Daten? Begründe deine Antwort.

Je nach Daten, aber eher schon. Weil es die abstände zwischen den Punkten misst, ist es sehr empfindlich gegenüber den Abständen. Die Ergebnisse werden extrem verzerrt, wenn die Daten nicht auf einer gleichen Skala sind, weil es extrem große Abstände geben kann.

18
New cards

Sinn und Zweck der Principal Component Analysis?

Es hilft neue features zu erstellen, während es die Hauptinfos beinhaltet und noise von diesen Hauptinfos trennt, die man dann löschen kann.

19
New cards

Braucht PCA skalierung? Begründe deine Antwort.

Ist von den Daten abhängig aber eher schon, weil es alle punkte auf einer grafik einzeichnet und wenn die Daten aus den verschiedenen features nicht auf einer ähnlichen skala sind, wird es die Ergebnisse verzerren und verfälschen. Deshalb sollte man bei solchen Daten skalieren.

20
New cards

Erkläre die Vorgangsweise des PCA.

Es erstellt eine grafik mit so vielen achsen, wie man spalten, also features, reingibt. Dann zeichnet es alle werte aus diesen spalten als punkte in der grafik ein. Danach betrachtet es diese punktewolke von jener stelle, die am „breitesten“ ist und somit die höchte varianz hat (= es erklärt die meisten Werte). Durch diese länge wird die erste Achse, genannt PC1, gesteckt. Die Mitte der Achse und dieser Punktewolke kommt auf den Nullpunkt der alten Grafik, das passiert auch mit den nächsten Achsen, was bedeutet, dass der Nullpunkt aller Achsen (ob die von den alten features oder die von den PCs) gleich. Danach kommt in einem rechten winkel auf die PC1 die PC2 und zwar so, dass es wieder die höchstmögliche Varianz hat. So geht das weiter und es gibt so viele PC (= principal components) wie man ursprünglich features reingefüttert hat. Diese neuen Achsen sind die Kombination von mehreren features – man erkennt anhand der loadings, welche features am meisten zu dieser Achse „beitragen“.

21
New cards

Was sind loadings? Kann man damit was anfangen?

Loadings sind Richtungskoeffizienten, die die Richtung der PCs anzeigen. Es bedeutet sowas wie „so viel in richtung der alten achse x, so viel in Richtung der alten achse y“ usw. Sie liegen zwischen -1 und 1. Man nutzt sie um PCs zu interpretieren und neue features daraus abzuleiten.

22
New cards

Was sind die scores?

Das sind die koordinaten bzw. werte der punkte in der neuen grafik. Rechenweg: Summe von (Loading x Wert)

23
New cards

Was bedeutet explained variance?

Das gibt an wie viel % von der gesamtvarianz eine PC erklärt. PC1 hat die meiste Varianz, PC2 weniger usw. Varianz = streuung der Daten -> höhere Varianz führt zur Erklärung von mehr Werten, weil sie auf einer größeren Range verteilt sind

24
New cards

Erkläre die zwei Wege, wie man PCA für feature engineering nutzen kann. Nenne beim zweiten Weg auch alle Gründe für die Nutzung bzw. wie genau man es nutzt.

Man kann sich durch die loadings inspirieren lassen. Dazu lässt man die MI-scores für die PCs berechnen und die, die einen hohen score haben nimmt man raus und nutzt sie als inspiration für neue features. Man schaut sich die gewichte an und versucht dadurch ein feature zu finden was (= welches neue feature) zu dieser kombination der alten features passen könnte. Der zweite weg ist, dass man die PCs direkt selber nutzen kann, dafür nimmt man die mit der höchsten varianz auf und kann die mit sehr geringer varianz auslassen. Das ist der erste Grund warum man es so (damit ist der zweite Weg gemeint) nutzt und zwar: Hauptinfo behalten und Dimension reduzieren. Der zweite Grund bzw Nutzungsweg ist dass man damit Ausreißer finden kann. Dazu schaut man sich die PCs mit geringer Varianz an. Dort sieht man am besten welche Werte Ausreißer sind, weil alle anderen Werte zusammengehäuft sind. Der dritte Grund: Rauschreduktion = Rauschen landet in den hinteren PCs und wird von der echten Info getrennt, die man ganz leicht weglassen/rauslöschen kann. Stark korrelierte features werden zu unkorrelierten Komponenten – somit wird die gleiche Info nicht doppelt ausgesagt und verwirrt die Modelle somit nicht.

25
New cards

Was ist target encoding?

Man encoded kategorien mit etwas, was uns am meisten bedeutet, nämlich mit der Beziehung der features zum target. Dafür nimmt man einen Wert her, den man vom target dieser kategorie abgeleitet hat.

26
New cards

Nenne die zwei Probleme vom target encoding inkl. den Gründen warum diese Punkte ein problem sind

Es führt zu overfitting, deshalb darf man sich nur einen teil aus den Daten raussuchen, mit dem trainiert wird, das hat aber zur Folge, dass es später Kategorien geben kann, die der Encoder noch nicht gesehen hat. Wenn es manche Werte nicht so oft gibt, kann es sein, dass die Ergebnisse dieser Kategorien auch falsch sind, weil es eben zu wenig Beobachtungen gibt, mit denen man rechnen kann.

27
New cards

Was ist die Lösung zu den oben genannten problemen von target encoding und wie funktioniert es?

Smoothing. Es mischt den durchschnitt der kategorie mit dem Gesamtdurchschnitt, damit der Wert der nach dem encoding rauskommt nicht allzu sehr von der Kategorie abhängt. Wie sehr da der Gesamtdurchschnitt mitmischt, kann man selber angeben. Beim target encoder ist das der Parameter „m“. je höher desto mehr wird gesamtdurchschnitt mitgemischt.

28
New cards

Wann nutzt man target encoding? (2 punkte)

Wenn es zu viele kategorien für one-hot-encoding gibt. Wenn die Metriken sagen, dass dieses feature unwichtig ist, man aber durch das Fachwissen weiß, dass es nicht sein kann. Dann nimmt man target encoding her und holt den wahren Informationsgehalt dieser features raus.

29
New cards

How do models work?

Models look at a data and try to find out the logic and patterns behind it. After it learned it, it can make predictions for future

30
New cards

What is fitting?

= training = step of capturing patterns; in the first step the model learns the logic and patterns in the training data

31
New cards

Why is a decision tree model so important and how does it function?

  • Its important because it’s the base of many models
  • How does it function?     ◦ Its basically a sorting system     ◦ It sorts the training data with Yes/No questions into groups which have similar targets – measured by comparing the targets of each observation in the group with the group average – and puts the observations with closest targets together     ◦ Its dividing the observations in every split into the groups     ◦ Overfitting/underfitting         ▪ The more it splits the less observations are in the last groups, which are called leafs -> this leads to overfitting because it separates the data so many times that there is only one or very small amounts of observations in the leafs         ▪ If we have too less splits then the groups are large and have a big error to the group average target     ◦ To make predictions the model just puts every observation in this sorting system and watches which leaf it lands on, that’s the most probable target based on the patterns which it learned during training
32
New cards

Whats the first step in any ML project?

Familiarizing yourself with the data

33
New cards

Why do we look at .describe()?

To see how the data is distributed, we can see its min, max, average, standard deviation, and quantiles

34
New cards

What are features?

Columns which we feed into the model, which help us predict the target

35
New cards

What are the main steps to building a model?

  • Preprocess data
  • Make a base model
  • check results
  • Make a plan for getting better results and apply it on the data
  • Make a new model
  • Repeat the last 3 steps till you get good results
36
New cards

What is “random_state=” for and why do we use it?

  • Some models or functions have randomness in them (for ex. they chose random data out of all the data) and if we need the same random data everytime we run the code, we need to type in any number in random_state
  • We use it because we need the same random data every round because otherwise we wouldn’t know if the changes of the results are because of another random set of data or because of our changes we made for ex. feature engineering
37
New cards

What is MAE and how does it work?

  • = mean absolute error
  • It calculates the absolute error between the predictions and the real targets and only takes the absolute value of it (= nur Betrag = ohne vorzeichen)
  • It calculates the average of these errors and that’s our MAE
38
New cards

Why do we need validation? Whats the function for splitting data in train and validation data?

  • train_test_split()
  • we need to test our model on some data which the model hasn’t seen during training (= new data = validation data = data which we put to the side before training the model) to see its real results because it can have good results on a dataset which it has already seen but maybe not on new data
39
New cards

What is overfitting and underfitting? Is it good or bad?

  • Overfitting = the model learns the exact combinations of each observation in the training dataset so it can perfectly predict the targets in the training dataset but will have bad results with new data because it didn’t learn the logic behind the data, it just saved these exact combinations in its memory
  • Underfitting = opposite of overfitting; this time model doesn’t learn the logic at all and performs bad on train and test data
  • We need the middle of these two for best results
40
New cards

How do random forests work? What are its advantages compared to decision trees?

  • It makes many decision trees – every one of them has some random features and random observations; in the end it makes a combination of the best trees and combines them to one
  • Its more accurate than a single decision tree because it tries much more combinations
41
New cards

What is the simple option, the better option and the extension to the better option regarding missing values? What are the problems of the three approaches of treating missing values?

◦ Simple option     ▪ = dropping columns with missing values     ▪ Bad because we could lose valuable information ◦ Better option     ▪ = imputing data     ▪ Might be wrong but usually its much better than dropping whole columns     ▪ We impute data which we get from the rest, for ex.: mean, median, most frequent ◦ Extension to imputing data     ▪ “flagging” rows where we imputed data     ▪ might be better but also worse than just imputing without flagging

42
New cards

What is a categorical variable?

It has a limited amount of values which it can be (a fixed set); you can’t chose anything else except these categories

43
New cards

What are the three approaches of preparing categorical data?

  • Dropping categorical columns     ◦ Problem of losing data
  • Ordinal Encoding     ◦ assigns an integer to each category     ◦ makes sense if there is a “rank” among the categories because models think that higher numbers are better/more important than lower --> these variables are called ordinal variables
  • One-Hot encoding     ◦ Makes as many new columns as there are categories and marks present categories with a 1, rest of the columns is 0 because each row can only have one present category     ◦ Makes sense to use with data without a rank among the categories --> these variables are called nominal variables     ◦ The dataframe gets very big because of the new columns, especially if we encode cols with many categories or have many columns which we encode with the OneHotEncoder
44
New cards

When isn’t it wise to use the third approach of preparing categorical data?

If there are more than 15 categories its usually not good because then you have many columns

45
New cards

Which parameter lets us avoid errors in the validation dataset (in the third approach) if there are categories which the encoder didn’t see in the training dataset? What does it do?

“handle_unkown=’ignore’” --> alle Spalten werden auf 0 gesetzt Beim rückumwandeln in die Kategorien steht dann „None“ da

46
New cards

What does the parameter “sparse_output=False” (third approach)? When do we need it – when not?

  • A sparse matrix is a compressed matrix without all the 0s; it just contains the indices and the column names and its values
  • We need to set it to False if we need to impute the matrix into a dataframe and we can set it to True if we feed it into a model because they can read it
47
New cards

What do pipelines do?

Pipelines bundle together preprocessing and modeling steps and run one after another

48
New cards

What are the benefits of pipelines?

  • Cleaner code
  • Less bugs because less code and less steps
  • Easier to transform to real world because it works on its own and its easier to get it to work
  • Faster and safer – for ex some validation methods are extremely complex if we do it by hand, for ex.: cross validation
49
New cards

What is ColumnTransformer? Whats the difference to pipelines?

It can apply different steps to different columns, pipelines can’t differentiate between columns

50
New cards

How does cross-validation work? Why do we use it instead of a “normal validation”?

  • CV splits the data in same size n-amount pieces and uses every piece once for validation, the rest is always the training data. The score is the average error of all runs
  • We use it instead of normal validation because a single set validation depends heavily on the validation set – it could perform worse with another validation set. To eliminate the luck in this randomness of choosing validation data we use CV because every set (and every data) gets chosen once as a validation data
51
New cards

When is it better to use single validation, when cv?

If we have big datasets because CV would take a much longer time and there is also no need for a CV because a small piece of very big datasets have already a good amount of randomness

CV on smaller datasets, when it only takes a couple minutes with single validation

52
New cards

How can we know that a single validation would be okay too?

If the errors of every run in a CV is approximately the same

53
New cards

Explain following code: “cross_val_score(cv=5, scoring='neg_mean_absolute_error')” Why does it use the negative mae?

  • It divides the data in 5 same sized pieces and validates a model with the CV method
  • The negative MAE is sth special of scikit-learn because scikit-learn is programmed to see higher numbers as better. so in this case it uses the negative MAE because “lower” numbers (= lower MAE) are better than numbers which are farer away from 0 even though they are smaller
54
New cards

What is an ensemble method?

It combines predictions of several models

55
New cards

How does gradient descent work?

A model makes a prediction and looks how much (= höhe des Betrags) and in which direction (= anhand d. Vorzeichens) it was off the real target, then it makes a step toward the target and checks again and so on

56
New cards

How does gradient boosting work?

  • With the gradient descent method
  • It makes many trees, one after another. Every tree corrects the error of the previous tree with a step in the direction of the target (contrast to RandomForest: there every tree is created independently from another)
  • The combination of the trees which led to the best results stay in the model
  • steps toward the real target are reduced by a factor which is the learning rate
57
New cards

Whats the library we use for gradient boosting for standard tabular data (= not for pictures or other complex data)?

XGBoost

58
New cards

Explain following parameters of gradient boosting: a. n_estimators = b. early_stopping_rounds = c. eval_set = d. learning_rate = e. n_jobs =

a. n_estimators = how many steps do we want in direction of the target (too low -> underfitting; too high --> overfitting) = amount of trees; typical values: 100-1.000 b. early_stopping_rounds = the amount of rounds where the results of the validation set stays about the same or gets worse --> the model stops learning and takes the combination of the trees where it stopped getting better (= it uses the best version) c. eval_set = the validation set (as a tuple) for the early stopping rounds d. learning_rate = the % of the error --> that’s the size of the new step (ex.: error = 10.000, learning_rate = 0,05 --> step = 500) e. n_jobs = amount of cores of the processor to use for calculating everything and building the model; “-1” = all cores

59
New cards

Which combination of learning_rate and n_estimators gives a more accurate XGBoost model and whats the deficit of it?

  • Small learning rate, large number of n_estimators
  • Takes longer time
60
New cards

Whats data leakage? Why is it a problem?

  • = data which won’t be available at the time of prediction leaks in during training of a model
  • It’s a problem because the model will deliver good results during training because it used a part of the “solution” which it won’t have during prediction/testing --> there it will get bad results
61
New cards

What are the 2 types of data leakage? What are the solutions for them?

  • Target-leakage     ◦ = data which won’t be available at the time of predicting is used during training     ◦ Solution: think about the time where every feature will be available for you         ▪ after target or same time with target? --> don’t use         ▪ not available during prediction? --> don’t use
  • Train-test-contamination     ◦ = validation data leaks into train data --> good performance on validation but bad in real life     ◦ Solution: use pipelines
62
New cards

What are Insights?

= how did the model think and work

63
New cards

Which insights can we get out of the models?

  • How important is each feature for the model?
  • How does a features use affect the predictions?
  • How do the features affect a single observation?
64
New cards

Why are these insights valuable? / What do we need them for?

  • Debugging --> we see how the model uses each feature and can react to it
  • Informing human decision making
  • Directing future data collecting
  • Feature engineering
  • Convincing people about the truthfulness of the model
65
New cards

Why do we need to perform insights analysis on a validation dataset?

We need to see how the model works with unseen data

66
New cards

What does Permutation Importance do?

Measures what variables mostly affect predictions

67
New cards

How does Permutation Importance work?

  • It runs the model on the validation set so that it has the base results to compare with
  • Then it takes out a feature and shuffles it
  • Then it runs the model and looks at the new predictions
  • If the predictions got much worse, it means the model was heavily relying on that feature; if not then the model wasn’t using it much
68
New cards

How do we interpret the weights?

  • The values go from 0 to infinite, the higher the more important the feature
  • Negative values mean that the shuffled values got better predictions than the true order of the values
  • The number after the “+/-“ shows the variation of the weight when the feature was reshuffled because permutation importance shuffles the features more than once to see the real effect of the changes
69
New cards

What does Partial Dependence Plots?

They show how the predictions of the model changes in average when a feature is set to different values --> They show how the feature influences the predictions

70
New cards

How does the PDP work?

  • It takes a feature and makes every value in this feature the same (the chosen values are in the range of the features values)
  • Then it runs the model and lets it predict
  • Then it takes the average prediction and draws a dot on a graph where the x-axis is the feature value and on the y-axis we got the average prediction
  • It repeats this step for many values and in the end we get a line on the graph by connecting the dots --> that’s how the values of these feature interact with predictions
71
New cards

What does SHAP do? How does it work?

  • = shows the impact of each feature on the prediction for a single row
  • It shows the base comparison (= the average prediction) to compare with
  • Shap values show which features drive the prediction up and down and by how much in this single observation
72
New cards

What are shap summary plots for?

  • It shows sth similar like the Permutation Importance = how important is a feature for the model – in detail
  • But it also shows how each value of the feature effects the prediction --> driving up or down from the base value?
73
New cards

How do we interpret a shap summary plot? (dots, color of dots, SHAP value, features from top to bottom – how does it calculate it?)

  • On the vertical axis it shows the names of the features sorted by how important they are which is calculated by their average SHAP value -> the higher the more important because it means that it has a big affection on the predictions
  • The dots in each row are the observations with their shap values on the horizontal axis
74
New cards

What are SHAP dependence contribution plots for?

  • Shows same as Partial Dependence Plots but not just the average (= the line) but also how it spreads because it draws every observation as a dot
  • The points are also compared to another feature with their c