# Python – Machine Learnining Code Snippets

## Feature Engineering

### Skewed Distribution

You’ve been fine-tuning a machine learning model you created for predicting mortgage defaults on a mortgages DataFrame. You’re aiming to eliminate skewness from your numerical variables by using a log transformation. Despite the transformation, one of your columns is still skewed – why do you think so and what is the solution? • The presence of an outlier on the right is responsible for skewness, and the solution is applying another round of transformation.
• The presence of an outlier on the right is responsible for skewness, and the solution is removing the outlier.
• The concentration of values on the left-hand side is responsible for skewness, and the solution is applying another round of transformation.
• The mean is responsible for skewness, and the solution is removing outliers from the column.

### Exploratory Data Analysis – Datavisualisation

As part of a project, you’ve been assigned to create a machine learning model that predicts whether customers are going to churn or not, you want to investigate the relationship between the Age column and the target variable Attrition in your churn DataFrame.

Create a boxplot to visually uncover the distribution of Age by different values of Attrition. ### Exploratory Data Analysis – Observation

Consider the histogram below. Which of the following statements is true. • The mean value for Group 1 is the lowest of the three groups
• Group 2 clearly has fewer observations than either of the other groups
• Group 3 has a skewed distribution, making it’s mean higher
• All of the groups have very different distributions of the data

### Skewed Data

You’ve been tasked with creating a classification system that predicts whether employees in your organization are leaving their job or staying. The employee_churn contains numerous numeric columns which are skewed, and you want a statistical measure that measures their spread in order to identify which columns could be transformed.

What is most appropriate measure of spread?

• Range because it covers the distance from the minimum and maximum of the distribution.
• Variance because it measures how far values are spread out around their mean.
• Standard Deviation because it measures how narrowly or widely spread values are around their mean.
• Interquartile range because it is based on the median and is less sensitive to outliers.

### Scaling Data

Before we fit a model to our data we should consider centering and scaling the data so that:

• It’s easier to interpret the model output because the variables are the same values
• A feature does not have more influence on the model because of larger or smaller values
• We can remove outliers from the data because they will all be on the same range
• We can use both the original and scaled version of the variables in our model

### Scaling or Standardization

As part of an interview for a Data Scientist role, you’ve been asked about key differences between Min-Max scaling and Standardization. Choose the correct answer:

• There are no differences between them, they’re just two techniques to get data in the same range.
• Min-Max scaling always produces columns between 0 and 1 whereas the range of standardized data is not predetermined.
• Min-Max scaling is a preprocessing technique, whereas Standardization is a statistical measure.
• Min-Max scaling is a preprocessing technique, whereas Standardization is a machine learning algorithm,

### Transform Data

Consider the variable x in the Pandas DataFrame df shown in the plot below. Apply a Box-Cox Transformation to the variable x. ### Missing data

Consider the data frame df below that shows the total number of observations per month. Fit a suitable imputer to fill the missing values.

Code

## Model Selection & Validation

### Bias-Variance

• Technical details underpinning model fitting that we don’t need to worry about.
• Incorporating expert knowledge of a process at the expense of model simplicity.
• Balancing how well a model fits with how well it generalizes to new data.
• Choosing to focus on only one of a models ability to explain or predict a process.

### Assessing Performance

Which of the following metrics would not be used when assessing the performance of a regression model?

• Accuracy.
• Root Mean Square Error.
• Median Absolute Deviation.
• Akaike Information Criteria.

### Grid Search

Determine if 50, 150 or 250 is the best value for the n_estimators hyperparameter of a random forest classifier.

## Unsupervised Learning

### PCA

Available in you working session is the dataset scaled_samples. Instantiate a principal component analysis model object with 2 components, and fit the model to the scaled_samples object.

### Dendrogram

Consider the dendrogram below. Which height yields 4 clusters? • 10
• 8
• 6
• 4

### Clustering – hierarchical clustering

Using the scipy package and the linkage matrix ward_linkage_matrix package return a cut tree at height set to 3.

The Pandas DataFrame df is loaded on your working session. Using the scipy package, compute the cluster distance (with linkage method complete) between the observations the columns x_scaled and y_scaled.

## Supervised Learning

### Regression – Logistic Regression

A LogisticRegression model is fitted on the training data X_train and y_train, and stored in model. Use model and the X_test feature data to predict values for the response variable, and store it in y_pred. Then get the model score using X_test and y_test.

### Regression – Lasso Regression

Available in this session are the training (X_train, y_train) and test (X_test, y_test) sets.

Implement a Lasso Regression model with alpha equal to 0.01. Determine the RMSE achieved by the model.

### Regression – interpretation results

Consider the summary below from a linear model, fitting the continuous target chol (cholesterol) with the feature sex (0 if female, 1 if male). What does this model suggest regarding the relationship between the variables chol and sex?

• All else equal, females are likely to have higher cholesterol than males, by 261.30.
• All else equal, females are likely to have higher cholesterol than males, by 22.01.
• All else equal, males are likely to have higher cholesterol than females, by 22.01.
• All else equal, males are likely to have higher cholesterol than females, by 261.30.

### Regression – Generalized LM or simple LM

In which of the following situations would you recommend the use of a generalized linear model with a non-Gaussian distribution rather than a simple linear model?

• Where the response variable is continuous, and the feature variable is continuous.
• Where the response variable is continuous, and the feature variable is categorical.
• Where the response variable is binary, and the feature variable is continuous.
• Where the response variable is continuous, and the feature variable is binary.

### Regression – Linear Regression with Polynomial features – interaction terms

An array X with two features has been loaded for you along with the target variable array y. Fit a multiple linear regression model with interaction terms on the target variable y as a function of the feature variables contained in X.

### Generalized Linear Model

A (Poisson) generalized linear model is fitted on the dataset score and stored in this session as model. Using model, apply the prediction method on the test dataset.

### Classifier – Decision Tree Classifier

Available in this session are the training data X_train and y_train for feature and target variables, respectively; as well as the testing data X_test and y_test for feature and target variables, respectively.

Using sklearn, fit a classification decision tree model on X_train and y_train.

### Classifier – RandomForest Classifier

Available in this session are the training data X_train and y_train for feature and target variables, respectively; as well as the testing data X_test and y_test for feature and target variables, respectively.

Using sklearn, fit a classification random forest model on X_train and y_train.

### Classifier – Gradient Boosting Classifier

Available in this session are the training data X_train and y_train for feature and target variables, respectively; as well as the testing data X_test and y_test.

Using sklearn, fit a classification gradient boosting model on X_train and y_train.