簡體   English   中英

Tensorflow 漸變膠帶返回 無

[英]Tensorflow Gradient Tape returning None

我將 TensorFlow 1.14.0 與 Python(3.6.8)一起使用。 我正在嘗試使用 tensorflow_probability 的 lbfgs 優化器實現( 文檔/示例)。

如果我運行文檔中提供的示例代碼,它可以正常工作。 我嘗試對我自己的代碼遵循相同的過程,該代碼使用tf.GradientTape()方法來計算目標 function。 這樣做時,漸變會以None類型返回。

我不明白為什么一個工作,但另一個沒有。

編輯:我意識到使用漸變運行 Eager Execution 是行不通的,所以我調整了示例以便能夠以 Eager Execution 運行。

急切執行的非工作示例(使用 GradientTape)

import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp

tf.enable_eager_execution()

# A high-dimensional quadratic bowl.
ndims = 3
minimum = np.ones([ndims], dtype='float64')
scales = np.arange(ndims, dtype='float64') + 1.0

# The objective function and the gradient.
def quadratic(x):
    with tf.GradientTape() as g:
        value = tf.reduce_sum(scales * (x - minimum) ** 2)
    grads = g.gradient(value, x)
    print('Gradients: ')
    print(grads)
    return value, grads

start = np.arange(ndims, 0, -1, dtype='float64')
optim_results = tfp.optimizer.lbfgs_minimize(quadratic, initial_position=start, num_correction_pairs=10,tolerance=1e-8)

print('results')
print(optim_results)
# Check that the search converged
assert(optim_results.converged)
# Check that the argmin is close to the actual value.
np.testing.assert_allclose(optim_results.position, minimum)

你需要看x。 對於此上下文管理器中的操作,至少需要監視其中一個輸入。

with tf.GradientTape() as g:
    g.watch(x)
    value = tf.reduce_sum(scales * (x - minimum) ** 2)

暫無
暫無

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

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