Your Career Platform for Big Data

Be part of the digital revolution in Germany

 

View all Jobs

DataCareer Blog

   A common and very challenging problem in machine learning is overfitting, and it comes in many different appearances. It is one of the major aspects of training the model. Overfitting occurs when the model is capturing too much noise in the training data set which leads to bad predication accuracy when applying the model to new data. One of the ways to avoid overfitting is regularization technique. In this tutorial, we will examine Ridge regression and Lasso which extend the classical linear regression. Earlier, we have shown how to work with Ridge and Lasso in Python, and this time we will build and train our model using R and the caret package. Like classical linear regression, Ridge and Lasso also build the linear model, but their fundamental peculiarity is regularization. The goal of these methods is to improve the loss function so that it depends not only on the sum of the squared differences but also on the regression coefficients. One of the main problems in the construction of such models is the correct selection of the regularization parameter. Comparing to linear regression, Ridge and Lasso models are more resistant to outliers and the spread of data. Overall, their main purpose is to prevent overfitting. The main difference between Ridge regression and Lasso is how they assign a penalty to the coefficients. We will explore this with our example, so let’s start. We will work with the Diamonds dataset, which you can download from the next website:  http://vincentarelbundock.github.io/Rdatasets/datasets.html . It contains the prices and other attributes of almost 54,000 diamonds. We will be predicting the price of diamonds using other attributes and compare the results for Ridge, Lasso, and OLS. # Upload the dataset diamonds <-read.csv('diamonds.csv', header = TRUE, sep = ',') head(diamonds) ## X carat cut color clarity depth table price x y z ## 1 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43 ## 2 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31 ## 3 3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31 ## 4 4 0.29 Premium I VS2 62.4 58 334 4.20 4.23 2.63 ## 5 5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75 ## 6 6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48 # Drop the index column diamonds<- diamonds[ , -which(names(diamonds)=='X')] head(diamonds) ## carat cut color clarity depth table price x y z ## 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43 ## 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31 ## 3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31 ## 4 0.29 Premium I VS2 62.4 58 334 4.20 4.23 2.63 ## 5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75 ## 6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48 # Print unique values of text features print(levels(diamonds$cut)) ## [1] "Fair" "Good" "Ideal" "Premium" "Very Good" print(levels(diamonds$clarity)) ## [1] "I1" "IF" "SI1" "SI2" "VS1" "VS2" "VVS1" "VVS2" print(levels(diamonds$color)) ## [1] "D" "E" "F" "G" "H" "I" "J" As you can see, there is a finite number of variables, so we can change these categorical variables to numerical. diamonds$cut <- as.integer(diamonds$cut) diamonds$color <-as.integer(diamonds$color) diamonds$clarity <- as.integer(diamonds$clarity) head(diamonds) ## carat cut color clarity depth table price x y z ## 1 0.23 3 2 4 61.5 55 326 3.95 3.98 2.43 ## 2 0.21 4 2 3 59.8 61 326 3.89 3.84 2.31 ## 3 0.23 2 2 5 56.9 65 327 4.05 4.07 2.31 ## 4 0.29 4 6 6 62.4 58 334 4.20 4.23 2.63 ## 5 0.31 2 7 4 63.3 58 335 4.34 4.35 2.75 ## 6 0.24 5 7 8 62.8 57 336 3.94 3.96 2.48 Before building the models, let’s first scale data. Scaling will put the ranges of our features from -1 till 1. Thus a feature with a larger scale won’t have a larger impact on the target variable. To scale a feature we need to subtract the mean from every value and divide it by standard deviation. For scaling data and training the models we’ll use caret package. The caret package (short for Classification And REgression Training) is a wrapper around a number of other packages and provides a unified interface for data preparation, models training, and metrics evaluation. # Create features and target matrixes X <- diamonds %>% select(carat, depth, table, x, y, z, clarity, cut, color) y <- diamonds$price # Scale data preprocessParams<-preProcess(X, method = c("center", "scale")) X <- predict(preprocessParams, X) Now, we can basically build Lasso and Ridge. We’ll split the data into a train and a test dataset but for now we won’t set the regularization parameter lambda. It is set to 1. The “glmnet” method in caret has an alpha argument that determines what type of model is fit. If alpha = 0 then a ridge regression model is fit, and if alpha = 1 then a lasso model is fit. Here we’ll use caret as a wrapper for glment. # Spliting training set into two parts based on outcome: 75% and 25% index <- createDataPartition(y, p=0.75, list=FALSE) X_train <- X[ index, ] X_test <- X[-index, ] y_train <- y[index] y_test<-y[-index] # Create and fit Lasso and Ridge objects lasso<-train(y= y_train, x = X_train, method = 'glmnet', tuneGrid = expand.grid(alpha = 1, lambda = 1) ) ridge<-train(y = y_train, x = X_train, method = 'glmnet', tuneGrid = expand.grid(alpha = 0, lambda = 1) ) # Make the predictions predictions_lasso <- lasso %>% predict(X_test) predictions_ridge <- ridge %>% predict(X_test) # Print R squared scores data.frame( Ridge_R2 = R2(predictions_ridge, y_test), Lasso_R2 = R2(predictions_lasso, y_test) ) ## Ridge_R2 Lasso_R2 ## 1 0.8584854 0.8813328 # Print RMSE data.frame( Ridge_RMSE = RMSE(predictions_ridge, y_test) , Lasso_RMSE = RMSE(predictions_lasso, y_test) ) ## Ridge_RMSE Lasso_RMSE ## 1 1505.114 1371.852 # Print coeficients data.frame( as.data.frame.matrix(coef(lasso$finalModel, lasso$bestTune$lambda)), as.data.frame.matrix(coef(ridge$finalModel, ridge$bestTune$lambda)) ) %>% rename(Lasso_coef = X1, Ridge_coef = X1.1) ## Lasso_coef Ridge_coef ## (Intercept) 3934.27842 3934.23903 ## carat 5109.77597 2194.54696 ## depth -210.68494 -92.16124 ## table -207.38199 -156.89671 ## x -1178.40159 709.68312 ## y 0.00000 430.43936 ## z 0.00000 423.90948 ## clarity 499.77400 465.56366 ## cut 74.61968 83.61722 ## color -448.67545 -317.53366 These two models give very similar results. Now let’s choose the regularization parameter with the help of tuneGrid. The models with the highest R-squared score will give us the best parameters. parameters <- c(seq(0.1, 2, by =0.1) , seq(2, 5, 0.5) , seq(5, 25, 1)) lasso<-train(y = y_train, x = X_train, method = 'glmnet', tuneGrid = expand.grid(alpha = 1, lambda = parameters) , metric = "Rsquared" ) ridge<-train(y = y_train, x = X_train, method = 'glmnet', tuneGrid = expand.grid(alpha = 0, lambda = parameters), metric = "Rsquared" ) linear<-train(y = y_train, x = X_train, method = 'lm', metric = "Rsquared" ) print(paste0('Lasso best parameters: ' , lasso$finalModel$lambdaOpt)) ## [1] "Lasso best parameters: 2.5" print(paste0('Ridge best parameters: ' , ridge$finalModel$lambdaOpt)) ## [1] "Ridge best parameters: 25" predictions_lasso <- lasso %>% predict(X_test) predictions_ridge <- ridge %>% predict(X_test) predictions_lin <- linear %>% predict(X_test) data.frame( Ridge_R2 = R2(predictions_ridge, y_test), Lasso_R2 = R2(predictions_lasso, y_test), Linear_R2 = R2(predictions_lin, y_test) ) ## Ridge_R2 Lasso_R2 Linear_R2 ## 1 0.8584854 0.8813317 0.8813157 data.frame( Ridge_RMSE = RMSE(predictions_ridge, y_test) , Lasso_RMSE = RMSE(predictions_lasso, y_test) , Linear_RMSE = RMSE(predictions_ridge, y_test) ) ## Ridge_RMSE Lasso_RMSE Linear_RMSE ## 1 1505.114 1371.852 1505.114 print('Best estimator coefficients') ## [1] "Best estimator coefficients" data.frame( ridge = as.data.frame.matrix(coef(ridge$finalModel, ridge$finalModel$lambdaOpt)), lasso = as.data.frame.matrix(coef(lasso$finalModel, lasso$finalModel$lambdaOpt)), linear = (linear$finalModel$coefficients) ) %>% rename(lasso = X1, ridge = X1.1) ## lasso ridge linear ## (Intercept) 3934.23903 3934.27808 3934.27526 ## carat 2194.54696 5103.53988 5238.57024 ## depth -92.16124 -210.18689 -222.97958 ## table -156.89671 -207.17217 -210.64667 ## x 709.68312 -1172.30125 -1348.94469 ## y 430.43936 0.00000 23.65170 ## z 423.90948 0.00000 22.01107 ## clarity 465.56366 499.73923 500.13593 ## cut 83.61722 74.53004 75.81861 ## color -317.53366 -448.40340 -453.92366 Our score raised a little, but with these values of lambda, there is not much difference. Let’s build coefficient plots to see how the value of lambda influences the coefficients of both models. We will use glmnet function to train the models and then we’ll use plot() function that produces a coefficient profile plot of the coefficient paths for a fitted “glmnet” object. Xvar variable of plot() defines what is on the X-axis, and there are 3 possible values it can take: “norm”, “lambda”, or “dev”, where “norm” is for L1-norm of the coefficients, “lambda” for the log-lambda sequence, and “dev” is the percent deviance explained. We’ll set it to lambda. To train glment, we need to convert our X_train object to a matrix. # Set lambda coefficients paramLasso <- seq(0, 1000, 10) paramRidge <- seq(0, 1000, 10) # Convert X_train to matrix for using it with glmnet function X_train_m <- as.matrix(X_train) # Build Ridge and Lasso for 200 values of lambda rridge <- glmnet( x = X_train_m, y = y_train, alpha = 0, #Ridge lambda = paramRidge ) llaso <- glmnet( x = X_train_m, y = y_train, alpha = 1, #Lasso lambda = paramLasso ) ## Warning: Transformation introduced infinite values in continuous x-axis ## Warning: Transformation introduced infinite values in continuous x-axis As a result, you can see that when we raise the lambda in the Ridge regression, the magnitude of the coefficients decreases, but never attains zero. The same scenario in Lasso influences less on the large coefficients, but the small coefficients are reduced to zeroes. We can conclude from the plot that the “carat”" feature has the most impact on the target variable. Other important features are “clarity” and “color” while features like “z” and “cut” have barely any impact. Therefore Lasso can also be used to determine which features are important to us and have strong predictive power. The Ridge regression gives uniform penalties to all the features and in such way reduces the model complexity and prevents multicollinearity. Now, it’s your turn!
Today, data science specialists are among the most sought-after in the labor market. Being able to find significant insights in a huge amount of information, they help companies and organizations to optimize the structure's work.  The field of data science is rapidly developing and the demand for talent is changing. We use job offerings to analyze the current demand for talent. After performing a  first analysis in 2017 , this article provides an update and more details on job openings, roles, required skills, locations and employers. We collect data over the last month from Indeed through their API. Indeed aggregates job openings from various websites and therefore provides a good starting point for an analysis.  Data science job offers in Switzerland: first sight We collect job openings for the search queries Data Analyst, Data Scientist, Machine Learning and Big Data. At the time of writing, there were 458 vacancies in the field of data science listed on Indeed for Switzerland. Most likely, not all jobs are captured by Indeed. Nevertheless, the dataset offers clear and structured information that allow us to analyze the market.  In order to get a better idea of different job types offered in the market, we will analyse the required level of experience, the required skills as well as the geographical distribution in the country. The bar plot shows the different job titles. Senior Data Scientist and Data Scientist are the most common job titles in this area. However, many jobs are listed with a job specific title rather than a general one.  Based on the job title,  we group jobs by the required experience level. The following plots points out that there is a high demand for experienced talents. More than 60% of job openings require middle-level specialists, while around quarter offers look for seniors. Interns and juniors make up less than 10% of the total number of vacancies.   Zurich is the Swiss data science center In a second step, we analyze the regional distribution of jobs. Not surprisingly, Zurich offers most positions, followed by Basel, Geneva (Genf), and Lausanne. The distribution by seniority seems equally distributed among cities - generally there is a high demand for people with some years of on-the-job experience. The majority of job offers for interns and juniors are found in Zürich. Both senior and lead data scientists are in high demand in Zürich and Basel, on the second stage follow Geneva and Lausanne. Strong demand for Python skills Let’s review the demand for specific skills, namely the number of occurrences of skills.Python is clearly leading among the programming languages with more than 400 mentions followed by R, Java, Scala, JavaScript, and C/C++. AWS, Spark, and Azure are the top 3 big data technologie, while Tableau and SAS head the visualization and analysis tools. Academia, Tech, Pharma and Finance hire data skills   There are about 260 companies in Switzerland offering jobs in the sphere of data science, that we captured in our dataset. Most of them belong to the IT, FMCG and pharmaceutical areas, as well as financial and digital spheres. We extracted the top companies with the most job offerings, and here they are. The size of the company name represents the number of job offerings.  Google, Siemens, and EPAM companies offer many data science jobs in IT and digital areas. Roche and Novartis are large pharmaceutical firms.  Credit Suisse is a famous financial holding. There are also hiring agencies like Myitjob or Oxygen Digital Recruitment. Johnson&Johnson is a giant FMCG company. EPFL, University of Basel, University of Bern and other educational establishments are also among the top employers of data talents. myitjobs was captured in the analysis - but it is just a job website and was misclassified by Indeed.  Summing up our analysis, we can see that there is substantial demand for individuals with experience, while fewer opportunities exist to acquire experience though entry positions or internships. Strong Python skills seem to be a must-have these days in the data science world. The domination of Python has amplified compared to 2 years ago when R or Matlab were mentioned more often.     
   Random Forest is a powerful ensemble learning method that can be applied to various prediction tasks, in particular classification and regression. The method uses an ensemble of decision trees as a basis and therefore has all advantages of decision trees, such as high accuracy, easy usage, and no necessity of scaling data. Moreover, it also has a very important additional benefit, namely perseverance to overfitting (unlike simple decision trees) as the trees are combined. In this tutorial, we will try to predict the value of diamonds from the Diamonds dataset (part of ggplot2) applying a Random Forest Regressor in R. We further visualize and analyze the obtained predictive model and look into the tuning of hyperparameters and the importance of available features. Loading and preparing data # Import the dataset diamond <-diamonds head(diamond) ## # A tibble: 6 x 10 ## carat cut color clarity depth table price x y z ## <dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl> ## 1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43 ## 2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31 ## 3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31 ## 4 0.290 Premium I VS2 62.4 58 334 4.2 4.23 2.63 ## 5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75 ## 6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48 The dataset contains information on 54,000 diamonds. It contains the price as well as 9 other attributes. Some features are in the text format, and we need to encode them to the numerical format. Let’s also drop the unnamed index column. # Convert the variables to numerical diamond$cut <- as.integer(diamond$cut) diamond$color <-as.integer(diamond$color) diamond$clarity <- as.integer(diamond$clarity) head(diamond) ## # A tibble: 6 x 10 ## carat cut color clarity depth table price x y z ## <dbl> <int> <int> <int> <dbl> <dbl> <int> <dbl> <dbl> <dbl> ## 1 0.23 5 2 2 61.5 55 326 3.95 3.98 2.43 ## 2 0.21 4 2 3 59.8 61 326 3.89 3.84 2.31 ## 3 0.23 2 2 5 56.9 65 327 4.05 4.07 2.31 ## 4 0.290 4 6 4 62.4 58 334 4.2 4.23 2.63 ## 5 0.31 2 7 2 63.3 58 335 4.34 4.35 2.75 ## 6 0.24 3 7 6 62.8 57 336 3.94 3.96 2.48 As we already mentioned, one of the benefits of the Random Forest algorithm is that it doesn’t require data scaling. So, to use this algorithm, we only need to define features and the target that we are trying to predict. We could potentially create numerous features by combining the available attributes. For simplicity, we will not do that now. If you are trying to build the most accurate model, feature creation is definitely a key part and substantial time should be invested in creating features (e.g. through interaction). # Create features and target X <- diamond %>% select(carat, depth, table, x, y, z, clarity, cut, color) y <- diamond$price Training the model and making predictions At this point, we have to split our data into training and test sets. As a training set, we will take 75% of all rows and use 25% as test data. # Split data into training and test sets index <- createDataPartition(y, p=0.75, list=FALSE) X_train <- X[ index, ] X_test <- X[-index, ] y_train <- y[index] y_test<-y[-index] # Train the model regr <- randomForest(x = X_train, y = y_train , maxnodes = 10, ntree = 10) Now, we have a pre-trained model and can predict values for the test data. We then compare the predicted value with the actual values in the test data and analyze the accuracy of the model. To make this comparison more illustrative, we will show it both in the forms of table and plot the price and the carat value # Make prediction predictions <- predict(regr, X_test) result <- X_test result['price'] <- y_test result['prediction']<- predictions head(result) ## # A tibble: 6 x 11 ## carat depth table x y z clarity cut color price prediction ## <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int> <int> <int> <int> <dbl> ## 1 0.24 62.8 57 3.94 3.96 2.48 6 3 7 336 881. ## 2 0.23 59.4 61 4 4.05 2.39 5 3 5 338 863. ## 3 0.2 60.2 62 3.79 3.75 2.27 2 4 2 345 863. ## 4 0.32 60.9 58 4.38 4.42 2.68 1 4 2 345 863. ## 5 0.3 62 54 4.31 4.34 2.68 2 5 6 348 762. ## 6 0.3 62.7 59 4.21 4.27 2.66 3 3 7 351 863. # Import library for visualization library(ggplot2) # Build scatterplot ggplot( ) + geom_point( aes(x = X_test$carat, y = y_test, color = 'red', alpha = 0.5) ) + geom_point( aes(x = X_test$carat , y = predictions, color = 'blue', alpha = 0.5)) + labs(x = "Carat", y = "Price", color = "", alpha = 'Transperency') + scale_color_manual(labels = c( "Predicted", "Real"), values = c("blue", "red")) The figure displays that predicted prices (blue scatters) coincide well with the real ones (red scatters), especially in the region of small carat values. But to estimate our model more precisely, we will look at Mean absolute error (MAE), Mean squared error (MSE), and R-squared scores. # Import library for Metrics library(Metrics) ## ## Attaching package: 'Metrics' ## The following objects are masked from 'package:caret': ## ## precision, recall print(paste0('MAE: ' , mae(y_test,predictions) )) ## [1] "MAE: 742.401258870433" print(paste0('MSE: ' ,caret::postResample(predictions , y_test)['RMSE']^2 )) ## [1] "MSE: 1717272.6547428" print(paste0('R2: ' ,caret::postResample(predictions , y_test)['Rsquared'] )) ## [1] "R2: 0.894548902990278" We obtain high error values (MAE and MSE). To improve the predictive power of the model, we should tune the hyperparameters of the algorithm. We can do this manually, but it will take a lot of time. In order to tune the parameters ntrees (number of trees in the forest) and maxnodes (maximum number of terminal nodes trees in the forest can have), we will need to build a custom Random Forest model to obtain the best set of parameters for our model and compare the output for various combinations of the parameters. Tuning the parameters # If training the model takes too long try setting up lower value of N N=500 #length(X_train) X_train_ = X_train[1:N , ] y_train_ = y_train[1:N] seed <-7 metric<-'RMSE' customRF <- list(type = "Regression", library = "randomForest", loop = NULL) customRF$parameters <- data.frame(parameter = c("maxnodes", "ntree"), class = rep("numeric", 2), label = c("maxnodes", "ntree")) customRF$grid <- function(x, y, len = NULL, search = "grid") {} customRF$fit <- function(x, y, wts, param, lev, last, weights, classProbs, ...) { randomForest(x, y, maxnodes = param$maxnodes, ntree=param$ntree, ...) } customRF$predict <- function(modelFit, newdata, preProc = NULL, submodels = NULL) predict(modelFit, newdata) customRF$prob <- function(modelFit, newdata, preProc = NULL, submodels = NULL) predict(modelFit, newdata, type = "prob") customRF$sort <- function(x) x[order(x[,1]),] customRF$levels <- function(x) x$classes # Set grid search parameters control <- trainControl(method="repeatedcv", number=10, repeats=3, search='grid') # Outline the grid of parameters tunegrid <- expand.grid(.maxnodes=c(70,80,90,100), .ntree=c(900, 1000, 1100)) set.seed(seed) # Train the model rf_gridsearch <- train(x=X_train_, y=y_train_, method=customRF, metric=metric, tuneGrid=tunegrid, trControl=control) Let’s visualize the impact of tuned parameters on RMSE. The plot shows how the model’s performance develops with different variations of the parameters. For values maxnodes: 80 and ntree: 900, the model seems to perform best. We would now use these parameters in the final model. plot(rf_gridsearch) Best parameters: rf_gridsearch$bestTune ## maxnodes ntree ## 5 80 1000 Defining and visualizing variables importance For this algorithm, we used all available diamond features, but some of them contain more predictive power than others. Let’s build the plot with features list on the y axis. On the X axis we’ll have incremental decrease in node impurities from splitting on the variable, averaged over all trees, it is measured by the residual sum of squares and therefore gives us a rough idea about the predictive power of the feature. Generally, it is important to keep in mind, that random forest does not allow for any causal interpretation. varImpPlot(rf_gridsearch$finalModel, main ='Feature importance') From the figure above you can see that the size of diamond (x,y,z refer to length, width, depth) and the weight (carat) contain the major part of the predictive power.
View all blog posts