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, , [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)
奈落之渊,发表在 2018-7-21 16:04:19