我只想计算两个矩阵的MSE值。我定义了一个像这样的函数:
def calDeltaY(self, Y, Y_):
sum = 0.0
for row in range(self.nm):
for col in range(self.nu):
if 1 == self.r[row][col]:
sum += (Y[row][col] - Y_[row][col])*(Y[row][col] - Y_[row][col])
print('calDeltaY: {0}.{1} !'.format(row, col))
return sum
我使用1 == self.r[row][col]
仅计算定义了值的元素。然后我构建了tensorflow模型来使用此功能:
def build_model(self):
self.Y_ = tf.placeholder(shape=[self.nm, self.nu], dtype=tf.float32, name='Y_')
self.X = tf.Variable(tf.truncated_normal(shape=[self.nm, self.n], mean=0.0, stddev=0.01, seed=1.0), dtype=tf.float32, name='X')
self.UT = tf.Variable(tf.truncated_normal(shape=[self.n, self.nu], mean=0.0, stddev=0.01, seed=1.0), dtype=tf.float32, name='X')
self.Y = tf.matmul(self.X, self.UT)
self.L = self.calDeltaY(self.Y, self.Y_)
# self.L = tf.reduce_sum((self.Y - self.Y_)*(self.Y - self.Y_))
self.J = self.L + self.lanmeda*tf.reduce_sum(self.X**2) + self.lanmeda*tf.reduce_sum(self.UT**2)
self.train_step = tf.train.AdamOptimizer(learning_rate=0.001, beta1=0.9,
beta2=0.999, epsilon=1e-08, use_locking=False,
name='Adam').minimize(self.J)
但是我发现当我调用build_model函数时,代码行self.L = self.calDeltaY(self.Y, self.Y_)
将被实际执行。如果我改用self.L = tf.reduce_sum((self.Y - self.Y_)*(self.Y - self.Y_))
,它将只定义计算图而不执行实际计算。
在tensorflow模型中似乎只能使用tensorflow本机函数。如何在张量流模式下使用用户定义的函数?