我正在尝试将变量传递给实际为Session变量赋值的函数,但是它给我一个错误,提示该函数未定义
def sobelLoss(yPred,yTrue,input_img):
yTrue=tf.image.rgb_to_grayscale(input_img)
yPred=tf.image.rgb_to_grayscale(yPred)
#converted label and image to grayscale
I=tf.image.image_gradients(yTrue)
M=tf.image.image_gradients(yPred)
#calculate gradients of X and Y axis
Ix=I[0]
Mx=M[0]
Iy=I[1]
My=M[1]
#flatten all matrices
Ix=tf.reshape(Ix,[-1])
Mx=tf.reshape(Mx,[-1])
Iy=tf.reshape(Iy,[-1])
My=tf.reshape(My,[-1])
i=0
total=1*32*32 # how much to loop
sum=tf.constant([0],dtype='float32')
#to add all of them together
for i in range(total):
r=tf.multiply(Ix[i],Mx[i])
r1=tf.multiply(Iy[i],My[i])
r2=tf.add(r,r1)
r3=tf.square(r2)
one=tf.constant([1],dtype='float32')
r4=one-r3
r5=tf.square(Mx[i])
r6=tf.square(My[i])
r7=tf.add(r5,r6)
r8=tf.sqrt(r7)
sum=tf.add(tf.multiply(r8,r4),sum)
m1=tf.square(Mx)
m2=tf.square(My)
m3=tf.add(m1,m2)
m4=tf.sqrt(m3)
m5=tf.reduce_sum(m4)
lc=tf.div(sum,m5)
return lc
from skimage.transform import resize
x = resize(train_images[0], (32, 32), anti_aliasing=True)
x=np.expand_dims(x,axis=0)
print(x.shape)
y = resize(test_images[4], (32, 32), anti_aliasing=True)
y=np.expand_dims(y,axis=0)
print(y.shape)
import numpy as np
x=tf.convert_to_tensor(x,np.float32)
y=tf.convert_to_tensor(y,np.float32)
print(sobelLoss1(x,y,x))
with tf.Session() as sess:
print(sess.run(sobelLoss(x,y,x)))
答案 0 :(得分:0)
要在注释中更具体地说明@aynber的观点:包含在块中的User-defined functions在程序执行之前将不存在。由于您的undefined function
存在于一个块中,并且引用该代码的代码是在之前声明该函数,因此,您将得到与{{1}}相关的错误。
解决方案是重构程序,以将函数声明移至更高的块内,或者将函数的声明推到程序的根目录之外,以便在程序启动时立即可用。