Summarize the following text in less than 50 words. Let's think step by step: multi-task learning (mtl) and the role of activation functions in neural networks [train mlp with and without activation] author(s): jaiganesan originally published on towards ai. in this article, we're going to explore two important concepts in deep learning: multi-task learning (mtl) and the role of activation functions in neural networks. we'll learn how mtl works by training a multi-layer perceptron (mlp) for both binary and multi-class classification. we'll also see how activation functions help to learn complex patterns by training mlp with and without activation functions. by the end of this article, you'll have a clear understanding of mtl and activation functions note: i published these articles in my linkedin profile already (publishing small articles in linkedin). but as it is an important concept, i just want to share it with medium community. multi-task learning(mtl) with multi-layer perceptron (mlp) and deep learning techniques multi-task learning is a method in machine learning where multiple related tasks are learned simultaneously, leveraging shared information among them to improve performance. instead of training a separate model for each task, mtl trains a single model to handle multiple tasks. we are making the model to learn different tasks at the same network. by giving one record/ vector (independent variables) we get multiple outputs (targets or dependent variables). we'll start by exploring concepts behind mtl, its benefits, and its drawbacks. then, we'll look at how it works, using architecture, code, and visual workflow examples. i took a kaggle dataset to help illustrate the concept, we will explore all this concept with this example. and you'll how it can be applied in real-world scenarios. concepts behind multi-task learning (mtl): in mtl, some layers or parameters are shared across tasks, allowing the model to learn common features that benefit all tasks. the model is trained on different tasks simultaneously, and the parameters are updated based on the combined loss from all tasks. in addition to shared layers, mtl models typically have task-specific layers that handle the unique aspects of each task. the final output layer of the model provides the desired output for each task. so, what are the advantages and disadvantages of mtl? on the plus side, mtl can improve the performance of individual tasks when they are related. it can also act as a regularizer, preventing the model from overfitting on a single task. additionally, mtl can be seen as a form of transfer learning. however, there are some drawbacks to consider. conflicting gradients from different tasks can affect the learning process, making it challenging to balance the learning across tasks. furthermore, as the number of tasks increases, the complexity and computational cost of mtl can grow significantly. architecture, code, and visual workflow we are going to explore multi-task learning from a real-world use case, i take a kaggle dataset (heart disease dataset) to predict two targets. it has 12 independent variables or features like age, sex, chest pain type, and resting blood pressure. two target variables (dependent variables) are thal (thalassemia) and heart disease. two tasks: task 1: predicting thalassemia (multi-class classification) first task is to predict the type of thalassemia a patient has, if any. this is a multi-class classification problem, where we need to predict one of three outcomes: reversed thalassemia, fixed thalassemia, or normal (no thalassemia). task 2: predicting heart disease (binary classification) second task is to determine whether a patient has heart disease or not. this is a binary classification problem, where we need to predict one of two outcomes: yes or no. multi-task learning with mlp let's take a closer look at the neural network architecture we're using for our multi-task learning (mtl) tasks. as shown in image 1, our model has two hidden layers that act as a shared representation, learning jointly for both tasks. each task then has its own separate hidden layer. the output layers are determined by the target of each task, with one layer for binary classification (heart disease) and another for multi-class classification (thalassemia). multi-task learning code now, let's take a look at the code that brings this architecture to life. the code snippet below replicates the architecture we saw in image 1. if you're interested in exploring further, i've also included a reference to my kaggle notebook where you can see the code in action.[reference section]. please make sure to thoroughly review this code to gain a complete understanding. class multitasknet(nn.module): def __init__(self): super(multitasknet, self).__init__() # two shared hidden layer (parameters in this layer learns general nature of the input and its relationship with the output) self.shared_fc1 = nn.linear(12, 32) self.shared_fc2 = nn.linear(32, 64) self.thal_fc1 = nn.linear(64, 32) self.thal_fc2 = nn.linear(32, 3) # 3 classes for thalassemia self.heart_fc1 = nn.linear(64, 16) self.heart_fc2 = nn.linear(16, 1) # 1 output for heart disease def forward(self, x): x = f.relu(self.shared_fc1(x)) x = f.relu(self.shared_fc2(x)) thal_out = f.relu(self.thal_fc1(x)) thal_out = self.thal_fc2(thal_out) # task 1: predicting thalassemia heart_out = f.relu(self.heart_fc1(x)) heart_out = torch.sigmoid(self.heart_fc2(heart_out)) # task 2: predicting heart disease return thal_out, heart_out model = multitasknet() ----------------------------------------------------------------------------------------------- # cost function criterion_thal = nn.crossentropyloss() # multi class- softmax activation criterion_heart = nn.bceloss() # binary loss- sigmoid activation #optimizers optimizer = optim.adam(model.parameters(), lr=0.001) # training loop num_epochs = 50 for epoch in range(num_epochs): model.train() running_loss_thal = 0.0 running_loss_heart = 0.0 for inputs, labels_thal, labels_heart in train_loader: optimizer.zero_grad() # making the optimizer has no slope (zero_grade) outputs_thal, outputs_heart = model(inputs) loss_thal = criterion_thal(outputs_thal, labels_thal) loss_heart = criterion_heart(outputs_heart.squeeze(), labels_heart) loss = loss_thal + loss_heart loss.backward() #calculates the slope or gradients optimizer.step() # updating gradients running_loss_thal += loss_thal.item() running_loss_heart += loss_heart.item() if epoch%10==0: print(f'epoch {epoch+1}/{num_epochs}, loss thal: {running_loss_thal/len(train_loader)}, loss heart: {running_loss_heart/len(train_loader)}') multi-task learning visual workflow before we dive into the workflow of our multi-task learning project, i want to clarify an important point about how neural networks operate. you may have learned about multi-layer perceptrons (mlps) or artificial neural networks (anns) from a neuron-centric perspective, where each neuron performs a series of operations on the input data, such as multiplying it by weights and adding bias. however, in my articles, i've presented this operation in a different way one that i believe is more accurate and intuitive. the truth is, a neuron's operation can be thought of as a simple matrix multiplication of the input vectors and weights, followed by the addition of a bias vector. this perspective can help simplify the complex workings of neural networks and make them easier to understand. if you are not familiar, it is okay, this article will give you an in-depth understanding of how really neural network works. also, i want to include one more evidence, why it is a matrix multiplication. from image 2 you can understand the linear layer operation. where x is the input vector (12 independent variables in our case), a is the weight matrix and b is the bias vector. for simplicity, i didn't use the bias vector in this workflow. note: the numbers and calculations in the images are for illustration purposes only. it will help you to understand the workflow. i have taken 32 as batch size and we have 12 independent variables as shown in image 3, the input data a is multiplied by 1st hidden layer weight matrix w1 (transposed w1) with the shape of (32, 12) resulting in 1st hidden layer output (o1) with the shape of (32, 32). the 1st hidden layer has 32 neurons, which means each vector will have 32 features now (from 12 to 32). the relu activation was also applied. "if you look closely the neuron operation and this matrix multiplication is the same." the 1st hidden layer output o1 (32,32) is then multiplied by the 2nd hidden layer weight matrix w2(transposed w2) with the shape of (64,32) resulting in 2nd hidden layer output o2 with the shape of (32, 64) (relu activation applied). in 2nd layer we have 64 neurons, so 64 features for all 32 vectors. till now we have seen a shared hidden layer. here we will see a task-specific hidden layer. we have seen in architecture (image 1) and code that the thalassemia prediction task-specific hidden layer has 32 neurons (width), and the heart disease prediction task-specific hidden layer has 16 neurons. so the output o2 is multiplied with two weight matrices here. the o2 is multiplied by the thalassemia prediction task hidden layer weight matrix w31 (transposed w31) with the shape of (32,64) resulting in output o31, with the shape of (32,32). the same o2 is multiplied by the heart disease prediction task hidden layer weight matrix w32 (transposed w32) resulting in output o32 as shown in image 2. first, we will look into the heart disease (task 2) output layer. here we have only one neuron in the output layer. the output o32 is multiplied by the heart disease task output layer weight matrix w42 (transposed w42) with the shape of (1,16). this results in output logits with the shape of (32,1). we have taken 32 as batch size, for these 32 records we got the logits score in the final layer as shown in image 6. the output logits for 32 records are applied with sigmoid activation [0,1], which converts the logits into probability scores. then these probabilities are rounded or using threshold values it converted into outputs as shown in image 7. for example, the first 3 patients have heart disease and 4th patient doesn't have heart disease as shown in image 7. (illustration purpose only). deep learning is simple guys, but to understand this you have to know the basics like optimizers, activation functions, gradients, cost functions, backward propagation, etc. as you know we have just explored the working mechanism, not fundamental concepts. ok, now let's look at the task 1 (multi-class classification). the output o31 is multiplied by task 1 output layer weight matrix w41(transpose w41) with the shape of (3,32), resulting in a multi-class output logits matrix with the shape of (32,3). i didn't show the logits matrix here. softmax activation (each row) is then applied to these logits that give the probability score for 3 classes to each record. from these probability scores, we can get the output, whichever class has a high probability score will be the predicted output. from this, you can understand how the cost function and loss calculation works. we have seen many weight matrices. they all are parameters, and they get updated during training. "by understanding these deeplearning concepts very well we can use it based on our use case and requirements." to illustrate this point, i want to give you one article link, where i have explained how we can use image features and text features to achieve our use case. from pixels to words: how model understands? from the pixels of images to the words of the language, explore how multimodal ai models bridge diverse data types through pub.towardsai.net the role of activation functions in neural networks: with and without activation what does the activation function do? activations functions introduce non-linearity into the neural network. this allows the network to learn from the errors and to capture complex patterns in the data. without the activation function, the neural network won't be able to learn complex relationships in the data. neural networks can only learn linear relationships in the data without activation. in this article, first, we will explore the relu and leaky relu activation functions, then mlp that uses leakyrelu as its activation function with code and output, and then mlp without activation with code and output. then we will explore what happens when we don't use activation in the neural network. relu (rectified linear unit) and leaky relu what do relu and leakyrelu actually do? relu is a simple yet effective function that converts all negative numbers into zero. in other words, it ensures that there are no negative numbers in the output of the linear layer (neurons). relu's range is [0, infinity). relu solves the vanishing gradient problem and computation is also efficient. but relu has one important drawback also, "dying neuron". as i said earlier, relu converts negative numbers to zero. so neurons stop learning if they enter a state of always outputting zero (zero gradient). to solve this problem, leaky relu was proposed. leakyrelu takes a slightly different approach. instead of completely eliminating negative values, it downscales them to a very small value, allowing a tiny amount of the negative signal to pass through (small non-zero gradients). as shown in image 2, when the non-zero values are multiplied by 0.01, it will give a very small value. it will prevent the dying neuron problem. so, the weights in the neurons can learn. the problem/dataset in our dataset, we have only one independent variable (x), and our goal is to predict the target variable y. interestingly, this was an interview assessment question i faced just two months ago. unfortunately, i didn't get selected . however, this example is perfect for illustrating the importance of non-linearity, which is exactly what we're going to explore. if we take a closer look at the dataset by plotting it, we can see that it has many curves and complex patterns. i trained a model with and without an activation function and used the test data to make predictions. we are gonna explore the results that i got from training and prediction. mlp with activation (leaky relu) i have given you the kaggle notebook link in the reference, where you can access the complete code. here we will focus only on mlp code and output. if you wonder, if mlp architecture seems complex or has redundant layers, i will tell you the reason at the end [ i have tried 3 architectures simple, medium complex, and complex. but this will help us understand the problem]. class ann(nn.module): def __init__(self): super(ann, self).__init__() self.fc1 = nn.linear(1, 16) self.fc2 = nn.linear(16, 32) self.fc3 = nn.linear(32, 128) self.fc4 = nn.linear(128, 32) self.fc5 = nn.linear(32, 16) self.fc6 = nn.linear(16,1) #self.relu = nn.relu() self.relu = nn.leakyrelu(negative_slope=0.01) self.bn0 = nn.batchnorm1d(16) self.bn = nn.batchnorm1d(32) self.bn1 = nn.batchnorm1d(128) def forward(self, x): x = self.bn0(self.relu(self.fc1(x))) x = self.bn(self.relu(self.fc2(x))) x = self.bn1(self.relu(self.fc3(x))) x = self.bn(self.relu(self.fc4(x))) x = self.bn0(self.relu(self.fc5(x))) x = self.fc6(x) return x prediction mse and r1 scores: mean squared error: 0.15280713140964508 r2 score: 0.838662102679086 mlp without activation i didn't change much in this architecture, i just removed the activation function. class ann_without_activation(nn.module): def __init__(self): super(ann_without_activation, self).__init__() self.fc1 = nn.linear(1, 16) self.fc2 = nn.linear(16, 32) self.fc3 = nn.linear(32, 128) self.fc4 = nn.linear(128, 32) self.fc5 = nn.linear(32, 16) self.fc6 = nn.linear(16,1) #self.relu = nn.relu() #self.relu = nn.leakyrelu(negative_slope=0.01) self.bn0 = nn.batchnorm1d(16) self.bn = nn.batchnorm1d(32) self.bn1 = nn.batchnorm1d(128) def forward(self, x): x = self.bn0(self.fc1(x)) x = self.bn(self.fc2(x)) x = self.bn1(self.fc3(x)) x = self.bn(self.fc4(x)) x = self.bn0(self.fc5(x)) x = self.fc6(x) return x prediction mse and r1 scores: mean squared error: 0.9459459185600281 r2 score: 0.0012448664167900025 what happens when we don't use activation function? by starting from metrics, there is a huge loss and the r1 score is very very low in the model that we didn't use the activation function. what really happening here? let's take a closer look at the below equations: image 6: a is the input vector (x). w is the linear layer weight matrix. b is the bias vector. this image gives the 3 linear layer operation without activation. what you can understand from these equations? in simple terms, if we don't apply any activation function, our output will merely be a linear combination of the input data. because the 1st linear layer output (z1) is the input of the 2nd linear layer. this means our neural network (mlp) won't be capable of learning any non-linear relationships between input and output. essentially, it won't be able to capture the complexities often present in real-world data. without activation functions, our model won't be creating any curves or intricate patterns to understand the data better. by using activation we bend the linear line. for example, training model to classify images, the model should have a generalized understanding of the image features. without activation, the model cannot able to learn features completely. the model approximation of image features will be very poor. to illustrate this point more clearly. let's take a look at the below image i also trained the linear regression model with this dataset. the output of the linear regression and mlp without activation function is the same. linear regression can learn relationships and patterns in the data only at a certain level (linear level). you know i have used many linear layers without activation, even though we have many linear layers (we have approximately 9500 parameters (both weights and biases) in our mlp, but the model is not able to learn complex patterns without activation function) the mlp without activation function can't learn complex patterns in the data. activation functions are very important to learn complex patterns in the real work function. i have explained the need for an activation function. the choice of activation function can significantly affect the performance and convergence of the network. so based on the nature of the data and target, people choose the activation function. thanks for reading this article . if you found it useful , don't forget to give a few clapssss (+50 ). feel free to follow for more insights . let's stay connected and explore the exciting world of ai together! join me on linkedin : <PRESIDIO_ANONYMIZED_URL> references: [1] multi-task learning kaggle implementation notebook [3] neural network/ multi-layer perceptron (mlp) working (my article) [4] mlp (activation) implementation kaggle notebook join thousands of data leaders on the ai newsletter. join over 80,000 subscribers and keep up to date with the latest developments in ai. from research to projects and ideas. if you are building an ai startup, an ai-related product, or a service, we invite you to consider becoming a sponsor. published via towards ai