【问题标题】:Can I get the gradient of a tensor with respect to the input without applying the input?我可以在不应用输入的情况下获得张量相对于输入的梯度吗?
【发布时间】:2018-04-10 13:52:30
【问题描述】:

例如,我需要计算cross_entropy 相对于x 的梯度,但我需要对梯度函数应用另一个值。

即:

f'(x)|x = x_t

我认为tf.gradients() 函数只会在x = x 处给出渐变。 那么 tensorflow 是否提供了这些功能?

【问题讨论】:

    标签: python tensorflow machine-learning tensor tensorflow-gradient


    【解决方案1】:

    tf.gradients 的结果是一个 tensor(一般的张量列表),而不是一个 float 值。在某种程度上,这个张量一个函数:它可以在任何点进行计算。客户端只需要提供所需的输入值。

    例子:

    features = 3
    n_samples = 10
    hidden = 1
    
    X = tf.placeholder(dtype=tf.float32, shape=[n_samples, features])
    Y = tf.placeholder(dtype=tf.float32, shape=[n_samples])
    
    W = tf.Variable(np.ones([features, hidden]), dtype=tf.float32, name="weight")
    b = tf.Variable(np.ones([hidden]), dtype=tf.float32, name="bias")
    
    pred = tf.add(tf.matmul(X, W), b)
    cost = tf.reduce_mean(tf.pow(pred - Y, 2))
    
    dc_dw, dc_db = tf.gradients(cost, [W, b])
    
    session.run(tf.global_variables_initializer())
    
    # Let's compute `dc_dw` at `ones` matrix.
    print(dc_dw.eval(feed_dict={X: np.ones([n_samples, features]), 
                                Y: np.ones([n_samples])}))
    

    【讨论】:

    • 非常感谢。但实际上我需要更新一个新的变量x_t,它的初始值为x,根据导数。其实我最初的想法是保留原图只是添加一个新的节点x_t,现在看来不可能了。我想我需要对我的模型做很多修改才能实现这个目标。
    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多