[英]Construct a tensor of tf.Variable objects
My cost function involves the matrix 我的成本函数涉及矩阵
T=[[1.0-a,b],[a,1.0-b]]
I can define 我可以定义
import numpy as np
import tensorflow as tf
a=0.3
b=0.4
T = tf.Variable([[1.0-a,b],[a,1.0-b]]
and this works well in the optimization, but then I am saying that I have four variables: 1-a,b,a,1-b (the gradient has four elements). 这在优化中效果很好,但是我要说的是我有四个变量:1-a,b,a,1-b(渐变包含四个元素)。 On the other hand, I would like my variables to be two: a and b (the gradient has two elements).
另一方面,我希望变量为两个:a和b(渐变具有两个元素)。
I thought of doing something like 我想到做类似的事情
var = tf.Variable([a,b])
T = tf.constant([[1.0-var[0],var[1]],[var[0],1.0-var[1]]])
but this does not work, outputing the following: 但这不起作用,输出以下内容:
TypeError: List of Tensors when single Tensor expected
So how can I construct a tensor made of tf.Variable objects? 那么如何构造由tf.Variable对象组成的张量?
Thank you. 谢谢。
I think what you need is: 我认为您需要的是:
import tensorflow as tf
a = tf.Variable(0.3)
b = tf.Variable(0.4)
T = tf.convert_to_tensor([[1.0 - a, b], [a, 1.0 - b]]
Initialise T as a placeholder. 初始化T为占位符。
T = tf.placeholder(tf.float32, [2, 2])
When starting your session, compute T and pass it in through a feed_dict
: 开始会话时,计算T并将其通过
feed_dict
:
with tf.Session() as sess:
a, b = .3, .4
inp = np.array([[1 - a, b], [a, 1 - b]])
sess.run(optimizer, feed_dict={T : inp})
Where optimizer
is the node that minimizes your cost function. optimizer
是使成本函数最小化的节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.