【问题标题】:What is the equivalent R code for this TensorFlow program in Python?这个 TensorFlow 程序在 Python 中的等效 R 代码是什么?
【发布时间】:2020-05-11 23:15:05
【问题描述】:

我正在学习在 R 中求解方程,并且我有兴趣通过 TensorFlow 来完成它(我已经知道如何使用 GA 和模拟退火来完成它)。 我正在 R 中为这个执行 Y = X + Z 并求解 Z 的 Python 程序构建等效代码(在 blog 中找到它)。我花了几个小时试图找到许多函数变体,在互联网博客和 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_step,因为我收到一个错误,指出它不是优化器的属性。我尝试过使用 tensorflow 和 keras 中的评估、编译和其他功能,但无法弄清楚如何做到这一点。

【问题讨论】:

    标签: python r tensorflow keras rstudio


    【解决方案1】:

    获取渐变相对容易,将它们应用于变量我不太清楚如何在 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...
    # )
    

    编辑:如果有人知道如何解决最后一步,请编辑/评论解决方案。

    【讨论】:

    • 感谢您在这里提供帮助@JacobJacox。我将尝试使用它并在此线程上更新。
    • 我无法让它工作。就像我在问题中提到的那样,我之前以类似的方式使用过 compile(object = yy, optimizer = optimizer, loss = deviation) 和 evaluate() ,但这些也需要 object 是模型类型,就像代码中的 Z .无论如何,感谢您的帮助
    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2019-02-12
    相关资源
    最近更新 更多