How to do it...

After the initial installation and setup, we can start building deep learning models by simply loading the TensorFlow library into the R environment:

  1. Let's start by simulating some dummy data:
x_data = matrix(runif(1000*2),nrow = 1000,ncol = 1)
y_data = matrix(runif(1000),nrow = 1000,ncol = 1)
  1. Now, we need to initialize some TensorFlow variables; that is, the weights and biases:
W <- tf$Variable(tf$random_uniform(shape(1L), -1.0, 1.0))
b <- tf$Variable(tf$zeros(shape(1L)))
  1. Now, let's define the model:
y_hat <- W * x_data + b
  1. Then, we need to define the loss function and optimizer:
loss <- tf$reduce_mean((y_hat - y_data) ^ 2)
optimizer <- tf$train$GradientDescentOptimizer(0.5)
train <- optimizer$minimize(loss)
  1. Next, we launch the computation graph and initialize the TensorFlow variables:
sess = tf$Session()
sess$run(tf$global_variables_initializer())
  1. We train the model to fit the training data:
for (step in 1:201) {
sess$run(train)
if (step %% 20 == 0)
cat(step, "-", sess$run(W), sess$run(b), " ")
}

Finally, we close the session:

sess$close()

Here are the results of every 20th iteration:

It is important that we close the session because resources are not released until we close it.
..................Content has been hidden....................

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