簡體   English   中英

('試圖更新張量',<tf.tensor: shape="()," dtype="float32," numpy="3.0"> )</tf.tensor:>

[英]('Trying to update a Tensor ', <tf.Tensor: shape=(), dtype=float32, numpy=3.0>)

我正在嘗試運行此處顯示的示例:

https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Optimizer

但它給了我這個錯誤:

我正在使用 linux 和 python 3

import tensorflow as tf
import numpy as np
var1=tf.constant(3.0)
var2=tf.constant(3.0)

# Create an optimizer with the desired parameters.
opt = tf.keras.optimizers.SGD(learning_rate=0.1)
# `loss` is a callable that takes no argument and returns the value
# to minimize.
loss = lambda: 3 * var1 * var1 + 2 * var2 * var2
# In graph mode, returns op that minimizes the loss by updating the listed
# variables.
opt_op = opt.minimize(loss, var_list=[var1, var2])
opt_op.run()
# In eager mode, simply call minimize to update the list of variables.
opt.minimize(loss, var_list=[var1, var2])




---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-1-f7fa46c26670> in <module>()
     12 # In graph mode, returns op that minimizes the loss by updating the listed
     13 # variables.
---> 14 opt_op = opt.minimize(loss, var_list=[var1, var2])
     15 opt_op.run()
     16 # In eager mode, simply call minimize to update the list of variables.

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py in apply_grad_to_update_var(var, grad)
    592       """Apply gradient to variable."""
    593       if isinstance(var, ops.Tensor):
--> 594         raise NotImplementedError("Trying to update a Tensor ", var)
    595 
    596       apply_kwargs = {}

NotImplementedError: ('Trying to update a Tensor ', <tf.Tensor: shape=(), dtype=float32, numpy=3.0>)

正如@xdurch0 所建議的那樣,使用 tf.Variable 代替 tf.constant。

請檢查下面的工作示例代碼。

import tensorflow as tf

import numpy as np
var1=tf.Variable(3.0)
var2=tf.Variable(3.0)

opt = tf.keras.optimizers.SGD(learning_rate=0.1)
# `loss` is a callable that takes no argument and returns the value
# to minimize.
loss = lambda: 3 * var1 * var1 + 2 * var2 * var2
# In graph mode, returns op that minimizes the loss by updating the listed
# variables.
#opt_op = opt.minimize(loss, var_list=[var1, var2])
#opt_op.run()
# In eager mode, simply call minimize to update the list of variables.
opt.minimize(loss, var_list=[var1, var2])
opt.variables()

Output

<function <lambda> at 0x7efdebc7f048>
[<tf.Variable 'SGD/iter:0' shape=() dtype=int64, numpy=1>]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM