(‘Пытаюсь обновить тензор’, )

#python #tensorflow

#python #тензорный поток

Вопрос:

Я пытаюсь запустить показанный здесь пример:

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>)
 

Комментарии:

1. Вам нужно использовать tf.Variable , а не constant .

Ответ №1:

Как было предложено @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()
 

Вывод

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