Understanding Multidimensional nnet

I am trying to understand the code behind nnet. I am currently getting different results when I split the polynomial factor into binary columns instead of using the formula method.

library(nnet)

set.seed(123)
y <- class.ind(iris$Species)
x <- as.matrix(iris[,1:4])
fit1 <- nnet(x, y, size = 3, decay = .1)

# weights:  27
#initial  value 164.236516 
#iter  10 value 102.567531
#iter  20 value 58.229722
#iter  30 value 39.720137
#iter  40 value 25.049530
#iter  50 value 23.671837
#iter  60 value 23.602392
#iter  70 value 23.601927
#final  value 23.601926 
#converged

pred1 <- predict(fit1, iris[,1:4])
rowSums(head(pred1))
[1] 1.032197661 1.033700173 1.032750746 1.034229149 1.032052937 1.032539980

set.seed(123)
fit2 <- nnet(Species ~ ., data = iris, size = 3, decay = .1)

# weights:  27
#initial  value 158.508573 
#iter  10 value 37.167558
#iter  20 value 26.815839
#iter  30 value 23.746418
#iter  40 value 23.698182
#iter  50 value 23.697907
#final  value 23.697907 
#converged

pred2 <- predict(fit2, iris[,1:4])
rowSums(head(pred2))
1 2 3 4 5 6 
1 1 1 1 1 1 

I know that I can simply use the latter approach (method formula), but I want to understand why the results differ from each other when the same method of factor separation appears in the source code nnet.formula.

+4
source share
1 answer

As @ user20650 noted, the argument softmaxis different. Inside nnet.formulathere is a section:

if (length(lev) == 2L) {
    y <- as.vector(unclass(y)) - 1
    res <- nnet.default(x, y, w, entropy = TRUE, ...)
    res$lev <- lev
}
else {
    y <- class.ind(y)
    res <- nnet.default(x, y, w, softmax = TRUE, ...)
    res$lev <- lev
}

Here softmaxset to TRUE. Putting it in a call nnetfixes the problem and they now match.

fit <- nnet(x, y, size = 3, decay = .1, softmax = TRUE)
pred <- predict(fit, iris[,1:4])
rowSums(head(pred))
+1

All Articles