Tensorflow 封装的 python 函数为什么不能优化?

import tensorflow as tf
import numpy as np
import scipy.misc

def my_function (image):
entro = 0.0
entro_array = np.zeros (1, dtype = np.float32)
pixel_num = np.zeros (256)
matrix = image.astype (np.int32)
for i in range (matrix.shape [0]):
for j in range (matrix.shape [1]):
pixel = matrix [i, j]
pixel_num [pixel] = pixel_num [pixel] + 1
pixel_num = pixel_num / (matrix.shape [0] * matrix.shape [1])

for i in range (len (pixel_num)):
    if pixel_num > 0.0 and pixel_num < 1.0:
        entro = entro - pixel_num * np.log2 (pixel_num)
entro_array [0] = entro
return entro_array

x = scipy.misc.imread (“36.bmp”, 0).astype (np.float32)
x = tf.reshape (x, [-1, 50, 50, 1])
w = tf.Variable (tf.random_normal ([3, 3, 1, 1], stddev=1))
x = tf.clip_by_value (tf.nn.conv2d (x, w, strides = [1, 1, 1, 1], padding = “SAME”), 0, 255)
x = tf.reshape (x, [50, 50])

y = tf.reduce_sum (tf.py_func (my_function, [x], [tf.float32])) # 调用自定义 op,但是为什么不能优化呢?如果无法优化,那么自定义函数还有什么意义?

train_op = tf.train.GradientDescentOptimizer (0.001).minimize (-y)

with tf.Session () as sess:
sess.run (tf.global_variables_initializer ())
sess.run (train_op)
out =sess.run (y)

image


奈落之渊,发表在 2018-7-21 16:04:19

不是不能优化,自己定义的函数和 TF 自带的函数是不一样的。最近 TF 出了一个把 python 语句转化成 TF 语句的方法,你可以去看看


so。 发表于 2018-7-28 23:13:10

想想 AD 的原理。想要能够被优化,要么需要给定导数函数,要么导数可以通过几个已知导数的函数合并算出来。

tf.* 都有定义导数,可是 my_function 并没有哦。可以考虑用 RegisterGradient 注册一个~


舟 3332 发表于 2018-8-6 23:59:42