How to do it...

In this recipe, we will use a pre-made dnn_regressor estimator. Let's get started and build and train a deep learning estimator model:

  1. We need to execute some steps before building an estimator neural network. First, we need to create a vector of feature names:
features_set <- setdiff(names(dummy_data_estimator), "target")

Here, we construct the feature columns according to the Estimator API. The feature_columns() function is a constructor for feature columns, which defines the expected shape of the input to the model:

feature_cols <- feature_columns(
column_numeric(features_set)
)
  1. Next, we define an input function so that we can select feature and response variables:
estimator_input_fn <- function(data_,num_epochs = 1) {
input_fn(data_, features = features_set, response = "target",num_epochs = num_epochs )
}
  1. Let's construct an estimator regressor model:
regressor <- dnn_regressor(
feature_columns = feature_cols,
hidden_units = c(5, 10, 8),
label_dimension = 1L,
activation_fn = "relu"
)
  1. Next, we need to train the regressor we built in the previous step:
train(regressor, input_fn = estimator_input_fn(data_ = dummy_data_estimator))
  1. Similar to what we did for the training data, we need to simulate some test data and evaluate the model's performance:
x_data_test_df <- as.data.frame( matrix(rnorm(100*784), nrow = 100, ncol = 784))
y_data_test_df <- as.data.frame(matrix(rnorm(100), nrow = 100, ncol = 1))

We need to change the column name of the response variable, just like we did for the training data:

colnames(y_data_test_df)<- c("target")

We bind the x and y data together for the test data:

dummy_data_test_df <- cbind(x_data_test_df,y_data_test_df)

Now, we generate predictions for the test dataset using the regressor model we built previously:

predictions <- predict(regressor, input_fn = estimator_input_fn(dummy_data_test_df), predict_keys = c("predictions"))

Next, we evaluate the model's performance on the test dataset:

evaluation <- evaluate(regressor, input_fn = estimator_input_fn(dummy_data_test_df))
evaluation

In the next section, you will gain a comprehensive understanding of the steps we implemented here.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset