I have made an machine learning application that will train a randomforest model on some uploaded data, and give a prediction of a specified single obsevation based on some selected inputs widgets
, once an actionbutton()
is pressed.
Both the function for training of the model "randomForest()
" and function for prediction "predict()
" is run, everytime the actionbutton()
is pressed.
I have come to realize that this is not very effecient use of the computational power, since the randomForest()
function usually does not need to be run more than once, and can take a while to run depending on the size of the uploaded dataset and model specifications.
To fix this issue, I have create another actionbutton()
which sole purpose is to train the model, so it dont have to be retrained everytime I want to make a prediction. Once a model is trained, it is saved as a 'model object'.
The predict()
function requires a 'model object' as an input, which is where the problem arise. I can't seem to figure out how to refer to the 'model object' in such a way that the prediction function can accept it as an input.
This is how I create the model object by the press of an actionbutton
:
model <- observeEvent(input$trainmodel,{
df <- selected_df()
model <- randomForest(eval(parse(text=paste(names(df)[1],"~ ."))), data = df, ntree = 500, mtry = 5, importance = TRUE)
})
And this is roughly how I refer to the 'model object' in the reactive()
code chunk of the predict()
function.
model <- model()
Prediction <- predict(model,test)
However, this doesn't seem to work as I get the error message:
Warning: Error in model: could not find function "model"
Keep in mind that all of this works if I define the 'model object' inside the reactive()
bracket, but this would ofcourse cause the very problem I was trying to fix in the first place.
So my question is:
How do I specify the model object, so it can be used in other functions such as predict()
?
------------------------------EDIT-----------------------------------
Is it possible that the problem is caused by the fact that both the dataframe and the model object is defined in the model()
functionen?
-If so, how do I fix that? I need the dataframe defined to train the model.