Tensorflow,根据另一个张量声明一个向量

时间:2018-04-01 16:54:24

标签: python tensorflow tensor

我是张量流的新手。

使用tensorflow,我想定义一个向量,它依赖于我的神经网络的输出来计算所需的成本函数:

# Build the neural network
X = tf.placeholder(tf.float32, shape=[None, n_inputs], name='X')
hidden = fully_connected(X, n_hidden, activation_fn=tf.nn.elu, weights_initializer=initializer)
logits = fully_connected(hidden, n_outputs, activation_fn=None, weights_initializer=initializer)
outputs = tf.nn.softmax(logits)

# Select a random action based on the probability
action = tf.multinomial(tf.log(outputs), num_samples=1)

# Define the target if the action chosen was correct and the cost function
y = np.zeros(n_outputs)
y[int(tf.to_float(action))] = 1.0
cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits)

要定义y,我需要action的值(介于0和9之间),这样我的向量y就是[0,0,0,1,0 ...],而索引为1时为#0; action& #34;

但是动作是张量而不是整数,所以我不能这样做!

此代码崩溃之前因为我无法将int应用于Tensor对象......

我该怎么办?

非常感谢

1 个答案:

答案 0 :(得分:0)

tf.one_hot()是您正在寻找的功能。

您必须执行以下操作:

action_indices = tf.cast(action, tf.int32)
y = tf.one_hot(action_indices)