Below are the solutions to these exercises on “Data Transformation.”

#################### # # # Exercise 1 # # # #################### X = tf$placeholder(tf$float32, name = "X") Y = tf$placeholder(tf$float32, name = "Y") #################### # # # Exercise 2 # # # #################### W = tf$Variable(0.0, name = "weights") b = tf$Variable(0.0, name = "bias") init_op = tf$global_variables_initializer() #################### # # # Exercise 3 # # # #################### pred = tf$add(tf$multiply(X, W),b) #################### # # # Exercise 4 # # # #################### mse = tf$square(Y - pred, name = "mse") #################### # # # Exercise 5 # # # #################### optimizer = tf$train$GradientDescentOptimizer(learning_rate = 0.01)$minimize(mse) #################### # # # Exercise 6 # # # #################### with(tf$Session() %as% sess, { sess$run(init_op) for( i in 1:1000){ for (j in 1:nrow(data)){ sess$run(optimizer,feed_dict = dict(X=data$hp[j], Y=data$mpg[j])) #if (i %% 50 == 0 ){ # print(loss) #} } } w_value = sess$run(W) b_value = sess$run(b) print(c(w_value, b_value)) })

## [1] -0.73256224 0.05747981

#################### # # # Exercise 7 # # # #################### x = seq(-5, 5, 0.01) y = w_value * x + b_value plot(data) lines(x, y)

#################### # # # Exercise 8 # # # #################### U = tf$Variable(0.0, name = "weights_X_2") init_op = tf$global_variables_initializer() pred = tf$add(tf$multiply(tf$pow(X,2),U),tf$add(tf$multiply(X,W),b)) mse = tf$square(Y - pred, name = "mse") optimizer = tf$train$GradientDescentOptimizer(learning_rate = 0.01)$minimize(mse) #################### # # # Exercise 9 # # # #################### with(tf$Session() %as% sess, { sess$run(init_op) for( i in 1:1000){ for (j in 1:nrow(data)){ sess$run(optimizer,feed_dict = dict(X=data$hp[j], Y=data$mpg[j])) } } w_value = sess$run(W) b_value = sess$run(b) u_value = sess$run(U) print(c(u_value, w_value, b_value)) })

## [1] 0.2904002 -1.0501314 -0.2581100

#################### # # # Exercise 10 # # # #################### x = seq(-5, 5, 0.01) y = u_value * x^2 + w_value * x + b_value plot(data) lines(x, y)

## Leave a Reply