首页 > 技术文章 > 用tensorflow求偏导

zhouyang209117 2018-01-16 17:40 原文

# coding:utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division

import tensorflow as tf

x = tf.placeholder(dtype=tf.float32)
y = tf.placeholder(dtype=tf.float32)

z = tf.multiply(x, x) + 3 * tf.multiply(x, y) + tf.multiply(y, y)
dx, dy = tf.gradients(z, [x, y])

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    dx_value, dy_value = sess.run([dx, dy], feed_dict={x: 1,  y: 2})
    print("dz/dx={}".format(dx_value))
    print("dz/dy={}".format(dy_value))

推荐阅读