如何获取列表包含张量中的每个元素?

时间:2017-01-13 15:17:12

标签: python tensorflow

我正在学习tf.contrib.opt.ScipyOptimizerInterface并正在制作一个限制的演示,每个重量都是非负的。

# -*- coding: utf-8 -*-
import tensorflow as tf

vector = tf.constant([.021,.046,.013], name='vector')
wt = tf.Variable([1./3,1./3,1./3], 'wt')

loss = -tf.reduce_sum(tf.multiply(vector,wt,'loss'))
equalities = [tf.reduce_sum(wt) - 1.]
inequalities = [wt[0],wt[1],wt[2]]

optimizer = tf.contrib.opt.ScipyOptimizerInterface(loss, var_list=[wt], equalities=equalities, inequalities=inequalities, method='SLSQP')

with tf.Session() as session:
  session.run(tf.global_variables_initializer())
  optimizer.minimize(session)

ScipyOptimizerInterface

  

equalities:可选的等式约束标量张量列表   被保持等于零。 inequalities:不平等的可选列表   约束标量张量保持非负。

如何将inequalities = [wt[0],wt[1],wt[2]]更改为inequalities = [wt[i] for i in range(tf.size(weight))]

1 个答案:

答案 0 :(得分:1)

您可以使用以下方式进行设置:

inequalities = [wt[i] for i in range(wt.get_shape()[0])]