In this article I will introduce you to classification in R. We will use the Iris data
set to perform this classification. The Iris data set is a classic data set that is
often used to demonstrate machine learning. This data set provides four measurements
for three different iris species. Data such as this typically comes in a CSV File. The
iris CSV file looks something like this.
You can download the above file here.
By default R expects to find files in your home directory. You can also specify a full path. We will now load the iris dataset. Of course, R has the iris dataset build into the variables iris and iris3. However, we will assume that you might want to use your own dataset. Therefore I will demonstrate how to load the iris.csv file. The following command is used to load the Iris data set.
You can also load the data right over the web.
Now that the iris data set is loaded, you can display the entire data set just by entering the variable name.
You can also use the summary function to provide a very useful summary of the iris data.
It is often useful to break the data into training and validation sets. This allows you to validate the SVM or ANN on data that it was never trained with. The Iris dataset has 150 elements in it. For our training set we will sample 100 elements from this 150 element set. This is done with the following commands.
It is very important to note that the above vectors are only indexes, and not the actual data. To obtain the actual data you must use one of the following commands.
I will now show you how to train a support vector for the Iris data set. First, we must tell R that we are using SVM’s.
Next, we create a radial basis function (RBF) that will be used during training. This will be used as the kernel function.
Next we train the SVM.
Next we get the fitted values for this iris SVM.
Test on the validation set with probabilities as output. The -5 means to remove the 5th column, which is species. We are trying to predict species.
This produces output similar to the following.
The above shows the predictions for the first 10 elements of the validation set. The numbers you see are probabilities. As you can see each line has one column with the maximum probability. These samples are all Iris-setosa. I only show ten rows, so there is not much variety. If you run the above command in R, you will see the other species as well.
I will now show you how to do exactly the same thing using an Artificial Neural Network. First, we must tell R that we are using ANN’s.
The neural network requires that the species be normalized using one-of-n normalization. We will normalize between 0 and 1. This can be done with the following command.
We can now train a neural network for the training data.
Now we can test the output from the neural network.
The new series of books will cover R, as well as the usual Java and C#. You can pledge ($7) at Kickstarter and pre-order and support this project.