Brief R Tutorial

From Encog Machine Learning Framework
Jump to: navigation, search

This is a brief tutorial on the R Programming Language. This tutorial focuses on how to use R to accomplish the following tasks.

  • Define a function
  • Plot a function
  • Simplify an expression
  • Calculate the derivative of an expression

While there are many tutorials available on R I decided to write this tutorial to focus in on a few areas that I frequently use R in conjunction with Encog. I will use this article as a starting point for some of my books, which will now be using R.

Contents

Define a Function

Consider if we wanted to define the Sigmoid Activation Function in R. This would be the first step to plotting the sigmoid activation function. The following shows the sigmoid function defined in R.

sigmoid <- function(x) {
1 / ( 1 + exp(-x) )
}

Once the sigmoid function has been created it can easily be queried as follows.

sigmoid(0)

The above code would produce 0.5.

Plot a Function

The above function could easily be plotted with the following command.

plot(sigmoid,-5,5)

The -5 and 5 specify the range to plot over. This produces the following plot.

Sigmoid-r.png

If you would like to save your plot to a file, use the following. The plot will be saved to your documents directory.

png('test.png')
plot(sigmoid, xlim=c(-5,5), ylim=c(0,1))
dev.off()

The above code was used to produce the plot that you see here.

If you would like to plot two equations on the same graph, the following code can be used.

plot(sin,-pi,2*pi)
par(new=TRUE)
plot(cos,-pi,2*pi)

Simplify an Expression

Consider the following expression, which is trivial to simplify.

f(x) = 1x + 2x + 3x

To simplify this expression, use the following R code.

library(Ryacas)
Simplify( expression( 1*x + 2*x + 3*x))

To this, R will respond with the following.

expression(6 * x)

Determine the Derivative of an Expression

In neural network programming you often need to take the derivative of something. For example, to take the derivative of the Sigmoid Activation Function, you would use the following.

x <- Sym("x")
s <- expression(1 / (1+e^-x))
D(s,x)

This produces the following.

e^-x * log(e)/(1 + e^-x)^2
Personal tools