Python中这个TensorFlow程序的等效R代码是什么?

Python中这个TensorFlow程序的等效R代码是什么?,python,r,tensorflow,keras,rstudio,Python,R,Tensorflow,Keras,Rstudio,我正在学习用R来解方程,我对通过TensorFlow(我已经知道如何使用GA和模拟退火)来解方程感兴趣。 我正在为这个python程序构建R中的等效代码,该程序执行Y=X+Z并求解Z(在本文中找到)。我花了几个小时试图找到许多功能的变体,在互联网博客和CRAN文档中搜索它们 import tensorflow as tf x = tf.constant([[1., 2.]]) y = tf.constant([[12., 4.]]) Z = tf.Variable(tf.zeros([1, 2]

我正在学习用R来解方程,我对通过TensorFlow(我已经知道如何使用GA和模拟退火)来解方程感兴趣。 我正在为这个python程序构建R中的等效代码,该程序执行Y=X+Z并求解Z(在本文中找到)。我花了几个小时试图找到许多功能的变体,在互联网博客和CRAN文档中搜索它们

import tensorflow as tf
x = tf.constant([[1., 2.]])
y = tf.constant([[12., 4.]])
Z = tf.Variable(tf.zeros([1, 2]))

yy = tf.add(x, Z)
deviation = tf.square(y - yy)

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(deviation)

init = tf.global_variables_initializer()
sess = tf.Session();
sess.run(init)
for i in range(5000):
 sess.run(train_step)
print(sess.run(Z))
以下是我迄今为止开发的R代码,在此过程中尝试了该程序的多种变体:

library(tensorflow)
x = tf$constant(c(1.,2.))
y = tf$constant(c(12,4))
Z = tf$Variable(tf$zeros(2,1))
yy = tf$add(x, Z)
deviation = tf$square(y - yy)

train_step = tf$optimizers$Adam(0.01)

现在我无法将minimize()函数添加到train_步骤中,因为我得到一个错误,该错误表示它不是优化器的属性。我曾尝试使用tensorflow和keras中的evaluate、compile和其他函数,但没有弄清楚如何做到这一点。

获取梯度相对容易,将它们应用于变量我无法弄清楚如何在tf$variable上做到这一点。。也许这仍然有帮助:

library(tensorflow)


optimizer <- tf$keras$optimizers$Adam(0.001)

x = tf$constant(c(1.,2.))
y = tf$constant(c(12,4))
Z = tf$Variable(tf$zeros(2,1))

with(tf$GradientTape() %as% tape, {
  yy = tf$add(x, Z)
  deviation = tf$square(y - yy)
})

grads <- tape$gradient(deviation,Z)
grads
tf.Tensor([-22.  -4.], shape=(2,), dtype=float32)
## now for adam part i cannot figure out how to apply it, usually you do:
# optimizer$apply_gradients(
#   purrr::transpose(list(grads, Z)) ## where Z would be model variables...
# )
库(tensorflow)

优化器感谢您在这里提供帮助@jacojacox。我将尝试使用此线程并对此线程进行更新。我无法使其正常工作。正如我在问题中提到的,我在前面以类似的方式使用了compile(object=yy,optimizer=optimizer,loss=develope)和evaluate(),但它们也需要对象是模型类型,就像代码中的Z一样。无论如何,谢谢你的帮助