不确定为什么我的代码无效。下面的代码生成错误:
ValueError: Initializer for variable while_7/Variable/ is from inside a control-flow construct, such as a loop or conditional. When creating a variable inside a loop or conditional, use a lambda as the initializer.
需要快速修复此循环.. 对于每个tf.while_loop,索引为“i”。如果距离矩阵dist [,i]< = caliper的最小值则输出第一个最小值索引;即(y,i)。然后设置dist [y,] = [None,None,None,None]。 鉴于示例matix“myx”,“myy”; while循环应该输出匹配对indx [[0,None],[1,5],[2,4],[3,None]]
import math
import numpy as np
import tensorflow as tf
myx=np.array([2.4,0.2,0.5,1.6])
myy=np.array([10.1,3.2,7.5,8.6,1,0.1,11,18])
Xxx=np.transpose(np.repeat(myx[:, np.newaxis], myy.size , axis=1))
Yyy=np.repeat(myy[:, np.newaxis], myx.size , axis=1)
X = tf.placeholder(tf.float64, shape=(myy.size,myx.size))
Y = tf.placeholder(tf.float64, shape=(myy.size,myx.size))
# define a caliper
calp=tf.constant(0.5,tf.float64)
with tf.device('/cpu:0'):
dist = tf.abs(tf.subtract(X,Y))
# Use an explicit shape for `i`.
i = tf.placeholder(dtype='int64', shape=[])
# Add a second unused argument to `condition()`.
def condition(i, *arg):
return i <= myx.size-1
# Add a second unused argument to `b()`.
def b(i, temp_pr, _):
tfslic = dist[0:myy.size, i]
# Drop the `axis` argument from `tf.reduce_min()`
minVal=tf.reduce_min(tfslic)
y = tf.cond(
tf.less_equal(minVal, calp),
# Reshape the output of `tf.argmin()` to be a scalar.
lambda: tf.argmin(tfslic, 0),
# Explicitly convert the false-branch value to `tf.int64`.
lambda: tf.constant(99999, dtype=tf.int64))
### Need to drop the matched one ###
#newdist=tf.stack([dist[0:y], dist[y:myx.size-1]])
### Need to save every match 2 dim
'''
:::::::::::::PROBLEM START HERE:::::::::::
For each tf.while_loop, with index "i"
if the minimum value of distance matrix dist[,i] <= caliper
then output the first min value index. i.e. (y,i)
Then set dist[y,]=[None, None, None, None]
Given the example matix "myx","myy";
The while loop should output match pair indx [[0,None],[1,5],[2,4],[3,None]]
'''
varDist=tf.Variable(temp_pr)
temp_af = tf.cond(
tf.less_equal(minVal, calp),
lambda: tf.assign(varDist[y,],[9999.,9999.,9999.,9999.]),
lambda: tf.Variable(dist))
return i+1, y, temp_af
# Add a dummy initial value for the second loop variable.
# Rename the first return value to `i_out` to avoid clashing with `i` above.
i_out, r, dist= tf.while_loop(condition, b, [i, dist, tf.constant(0, dtype=tf.int64)])
#mypair=tf.stack([i_out-1,r],0)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
dmat = sess.run(dist, feed_dict={X:Xxx, Y: Yyy,i:0})
sess.close()
print(dmat)