use*_*545 15 machine-learning linear-gradients tensorflow
鉴于我有一个线性模型如下,我想得到关于W和b的梯度向量.
# tf Graph Input
X = tf.placeholder("float")
Y = tf.placeholder("float")
# Set model weights
W = tf.Variable(rng.randn(), name="weight")
b = tf.Variable(rng.randn(), name="bias")
# Construct a linear model
pred = tf.add(tf.mul(X, W), b)
# Mean squared error
cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*n_samples)
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试这样的事情,其中成本是一个函数,cost(x,y,w,b)
我只想要相对于渐变w and b
:
grads = tf.gradients(cost, tf.all_variable())
Run Code Online (Sandbox Code Playgroud)
我的占位符也将包括在内(X和Y).即使我确实得到了一个渐变,[x,y,w,b]
我怎么知道渐变中哪个元素属于每个参数,因为它只是一个没有名称的列表,哪个参数与衍生物有关?
Pri*_*ham 28
引用文档 tf.gradients
在xs中构造ys wrt x之和的符号偏导数.
所以,这应该工作:
dc_dw, dc_db = tf.gradients(cost, [W, b])
Run Code Online (Sandbox Code Playgroud)
这里,tf.gradients()
将cost
第二个参数中每个张量的wrt 的梯度作为相同顺序的列表返回.
阅读tf.gradients以获取更多信息.
归档时间: |
|
查看次数: |
20793 次 |
最近记录: |