30

I'm tring to use neuralnet for prediction.

Create some X:

x <- cbind(seq(1, 50, 1), seq(51, 100, 1))

Create Y:

y <- x[,1]*x[,2]

Give them a names

colnames(x) <- c('x1', 'x2')
names(y) <- 'y'

Make data.frame:

dt <- data.frame(x, y)

And now, I got error

model <- neuralnet(y~., dt, hidden=10, threshold=0.01)

error in terms.formula(formula) : '.' in formula and no 'data' argument

For example, in lm(linear model) this is worked.

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
luckyi
  • 465
  • 2
  • 6
  • 9
  • 5
    `neuralnet` is doing a lot os messing with the formula via non-exported function `neuralnet:::generate.initial.variables`. There is a bug in that function. I suggest you contact the maintainer and send them this example or a link to the question. – Gavin Simpson Jul 22 '13 at 18:28

3 Answers3

50

As my comment states, this looks like a bug in the non-exported function neuralnet:::generate.initial.variables. As a work around, just build a long formula from the names of dt, excluding y, e.g.

n <- names(dt)
f <- as.formula(paste("y ~", paste(n[!n %in% "y"], collapse = " + ")))
f

## gives
> f
y ~ x1 + x2

## fit model using `f`
model <- neuralnet(f, data = dt, hidden=10, threshold=0.01)

> model
Call: neuralnet(formula = f, data = dt, hidden = 10, threshold = 0.01)

1 repetition was calculated.

        Error Reached Threshold Steps
1 53975276.25     0.00857558698  1967
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
13

Offering a simpler alternative to the previous answer, you can create a formula from names of dt using reformulate():

f <- reformulate(setdiff(colnames(dt), "y"), response="y")

reformulate() doesn't require the use of paste() and automatically adds the terms together.

Megatron
  • 15,909
  • 12
  • 89
  • 97
-1

To expand a formula

f <- formula(terms(f, data= dt))

or even shorter

f <- formula(dt, f)

where f is the formula and dt is the data.


For instance, the original formula could be:

f <- as.formula("y ~ .")
Gorka
  • 1,971
  • 1
  • 13
  • 28