TheoreticalEcology / machinelearning

Teaching Material for a Machine Learning course with Keras and Tensorflow in R
https://theoreticalecology.github.io/machinelearning/
Other
17 stars 5 forks source link

corrected small error and added explanation #38

Open D-Maar opened 8 months ago

D-Maar commented 8 months ago

mean_per_row = tf$reduce_mean(x, axis = 0L) does not correspond to mean_per_row = apply(x, 1, mean) but mean_per_row = tf$reduce_mean(x, axis = 1L) does

Also for tf matrices result = x - mean_per_row does not correspond to the same for R matrices, but tf$transpose(tf$transpose(x) - mean_per_row) does

Code:

library(tensorflow)
x=matrix(1:100, nrow =10L)
correct_mean_per_row =  apply(x, 1, mean)
wrong_TF = tf$reduce_mean(x, axis = 0L)
correct_TF = tf$reduce_mean(x, axis = 1L)
correct_mean_per_row
wrong_TF
correct_TF

do_something_R = function(x = matrix(0.0, 10L, 10L)){
  mean_per_row = apply(x, 1, mean)
  result = x - mean_per_row
  return(result)
}

do_something_TF_new = function(x = matrix(0.0, 10L, 10L)){
  x = tf$constant(x)  # Remember, this is a local copy!
  mean_per_row = tf$reduce_mean(x, axis = 1L)
  result = tf$transpose(x) - mean_per_row 
  return(tf$transpose(result)) 
}

do_something_TF_old = function(x = matrix(0.0, 10L, 10L)){
  x = tf$constant(x)  # Remember, this is a local copy!
  mean_per_row = tf$reduce_mean(x, axis = 0L)
  result = x - mean_per_row 
  return(result) 
}

x=matrix(1:100, nrow =5L)
do_something_R(x)
do_something_TF_new(x)
do_something_TF_old(x)