“neuralnet” function in R – Error in neurons[[i]] %*% weights[[i]]

Below is an error that I came across while executing “neuralnet” package in R for the first time.

Error message:
Error in neurons[[i]] %*% weights[[i]] :  requires numeric/complex matrix/vector arguments

Reason:
Neuralnet package cannot handle categorical inputs. All categorical input variables need to be converted to dummy variables before they can be passed to neuralnet. This is not handled automatically by the package.

Fix:
Dummy coding can be done using function given below.

var1.matrix input.data

Using model.matrix function, a new matrix var1.matrix is created. The new matrix is then added as an additional component to the input dataset.

For example, assume there was a “Gender” column having values “Male” and “Female” originally.

$ Gender                          : Factor w/ 2 levels “Female”,”Male”: 2 2 2 1 2 2 1 2 2 1 …

After the conversion, two more dummy variables will be added as below.

$ GenderFemale                 : num  0 0 0 1 0 0 1 0 0 1 …
$ GenderMale                      : num  1 1 1 0 1 1 0 1 1 0 …

These new variables can be used as input to the neuralnet function to overcome the error.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s