Binary Classification using Keras in R

Binary Classification using Keras in RDerrick MwitiBlockedUnblockFollowFollowingFeb 13Many packages in Python also have an interface in R.

Keras by RStudio is the R implementation of the Keras Python package.

Most of the functions are the same as in Python.

The only difference is mostly in language syntax such as variable declaration.

In this tutorial, we’ll use the Keras R package to see how we can solve a classification problem.

We’ll use the Kyphosis dataset to build a classification model.

Kyphosis is a medical condition that causes a forward curving of the back—so we’ll be classifying whether kyphosis is present or absent.

We’ll get started by started by loading in the TidyVerse library that will provide us with the function to read in the dataset.

We’ll now import Keras so that we can access the Keras functions then read in the Kyphosis dataset.

We can quickly check the head in order to get a glimpse into the dataset that we’re working with.

We’ll be working to predict the Kyphosis column.

The first thing we’ll do is convert the Kyphosis column into zeros and ones since the machine learning model will only accept numerical figures.

In order to achieve this, we’ll use the fastDummies library that will help us in creating the dummy variables.

In the process, we’ll remove the first dummy variable to avoid the dummy variable trap, as we have seen in previous machine learning tutorials.

After that, we’ll check to make sure the head of the data that has been generated.

We can see that the previous Kyphosis column is still in our dataset.

We’ll now work to remove it so that we’re left only with the one we just generated.

After that, we can then check its head.

We’re going to use the Caret library to prepare the data for our classification model.

We’ll first create the index that we shall use to split the data into a training and testing set.

We’ve created an index that will use 70% of the data on training and the other 30% for a test set.

The next step is to prepare the data for Keras by scaling it.

We’ll use the scale function to achieve this.

We’ll then use the to_categorical function on the labels to ensure that they’re categorical.

We’ll perform a similar transformation on the test set and the test set labels.

The next step is to define our model.

We’ll use keras_model_sequential() to initialize the model.

This is similar to the Sequential function in Keras Python.

We’ll then define dense layers using the popular relu activation function.

We also add drop-out layers to fight overfitting in our model.

Similar to Keras in Python, we then add the output layer with the sigmoid activation function.

The next step is to compile the model using the binary_crossentropy loss function.

This is because we’re solving a binary classification problem.

We’ll use the adam optimizer for gradient descent and use accuracy for the metrics.

We then fit our model to the training and testing set.

Our model will run on 100 epochs using a batch size of 5 and a 30% validation split.

We can now look at our model’s summary.

________________________________________________________________________________Layer (type) Output Shape Param # ================================================================================dense_3 (Dense) (None, 256) 1024 ________________________________________________________________________________dropout_3 (Dropout) (None, 256) 0 ________________________________________________________________________________dense_4 (Dense) (None, 128) 32896 ________________________________________________________________________________dropout_4 (Dropout) (None, 128) 0 ________________________________________________________________________________dense_5 (Dense) (None, 2) 258 ================================================================================Total params: 34,178Trainable params: 34,178Non-trainable params: 0The next thing we can do is evaluate the model.

We’ll check the training loss and its accuracy.

We can also visualize these results using a graph.

We’ll start with visualizing the model loss.

The model accuracy can be visualized in a similar manner.

From the model loss graph, we notice that the training loss goes down but the testing loss is up.

We’d have to tune the parameters further to ensure the testing loss is decreasing, too.

In the model accuracy we notice that the training accuracy is also higher than the testing accuracy.

Let’s now move forward to make predictions using the predict_classes Keras function.

At this point, we can print the confusion matrix.

This will help us see how many predictions are being made correctly, and otherwise.

At this point, we might be interested in saving our model for future use.

In order for this to happen, we need to install h5py.

R Keras will use it to save the model.

Let’s now proceed to show how we can save the model and load it.

R Keras allows us to build deep learning models just like we would using Keras in Python.

This makes it very easy for someone who has used Keras in any language to transition smoothly between other languages.

You can learn more about R Keras from its official site.

Introductory Tutorials For Machine LearningIf you are just getting started in machine learning or looking to brush up your skills, this book is for you.

leanpub.

comEditor’s Note: Ready to dive into some code?.Check out Fritz on GitHub.

You’ll find open source, mobile-friendly implementations of the popular machine and deep learning models along with training scripts, project templates, and tools for building your own ML-powered iOS and Android apps.

Join us on Slack for help with technical problems, to share what you’re working on, or just chat with us about mobile development and machine learning.

And follow us on Twitter and LinkedIn for all the latest content, news, and more from the mobile machine learning world.

.

. More details

Leave a Reply