计算函数梯度时出现问题

时间:2019-05-10 11:14:28

标签: tensorflow gradients

我想使用TensorFlow将向量与另一个向量区分开。我无法编写和可视化输出(只是在TensorFlow上开始了我的旅程)

我正在附上我尝试过的代码段。

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

x = np.linspace(-np.pi, np.pi, 120) 
y = np.sinh(x) 

plt.plot(x,y)
plt.axhline(color="gray", zorder=-1)
plt.axvline(color="gray", zorder=-1)
plt.show()

X = tf.constant(x, dtype=tf.float32)
Y = tf.constant(y, dtype=tf.float32)
gradient = tf.gradients(Y, X)

init = tf.global_variables_initializer()
with tf.Session() as sess:
     sess.run(init)

我无法输出渐变。我还尝试了一个渐变的占位符,但无法弄清楚该怎么做。

1 个答案:

答案 0 :(得分:0)

您的Y不依赖于X。按照它们的定义方式,它们只是两个独立的张量。这可能就是您想要的:

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

x_data = np.linspace(-np.pi, np.pi, 120) 
y_data = np.sinh(x_data) 

plt.plot(x_data, y_data)
plt.axhline(color="gray", zorder=-1)
plt.axvline(color="gray", zorder=-1)
plt.show() # <-- shows image

x = tf.constant(x_data, dtype=tf.float32)
y = tf.math.sinh(x) # <-- `y` is a function of `x`
grads = tf.gradients(y, x)

# init = tf.global_variables_initializer() # <-- No need, you don't have variables here
with tf.Session() as sess:
    print(sess.run(grads)) # <-- prints long array