【译】Effective TensorFlow Chapter9——使用Python ops进行内核设计和高级可视化

本文翻译自: 《Prototyping kernels and advanced visualization with Python ops》, 若有侵权请联系删除,仅限于学术交流,请勿商用。若有谬误,请联系指出。python

TensorFlow中的内核操做彻底用C ++编写,以提升效率。可是用C++编写TensorFlow内核的话可能会很是痛苦。所以,在花费数小时实现属于本身的内核以前,你也许须要先实现一个操做的原型,尽管这样的效率会很低。经过tf.py_func()你能够将任何一个python源代码转换为TensorFlow的操做。git

举个例子而言,这里有一个用python本身实现的ReLU非线性激活函数,经过tf.py_func()转换为TensorFlow操做的例子:github

import numpy as np
import tensorflow as tf
import uuid

def relu(inputs):
    # Define the op in python
    def _relu(x):
        return np.maximum(x, 0.)

    # Define the op's gradient in python
    def _relu_grad(x):
        return np.float32(x > 0)

    # An adapter that defines a gradient op compatible with TensorFlow
    def _relu_grad_op(op, grad):
        x = op.inputs[0]
        x_grad = grad * tf.py_func(_relu_grad, [x], tf.float32)
        return x_grad

    # Register the gradient with a unique id
    grad_name = "MyReluGrad_" + str(uuid.uuid4())
    tf.RegisterGradient(grad_name)(_relu_grad_op)

    # Override the gradient of the custom op
    g = tf.get_default_graph()
    with g.gradient_override_map({"PyFunc": grad_name}):
        output = tf.py_func(_relu, [inputs], tf.float32)
    return output
复制代码

经过TensorFlow的gradient checker,你能够确认这些梯度是否计算正确:canvas

x = tf.random_normal([10])
y = relu(x * x)

with tf.Session():
    diff = tf.test.compute_gradient_error(x, [10], y, [10])
    print(diff)
复制代码

compute_gradient_error()数值化地计算梯度,返回与理论上的梯度的差异,咱们所指望的是一个很是小的差异。 注意到咱们的这种实现是很是低效率的,这仅仅在实现模型原型的时候起做用,由于python代码并不能并行化并且不能在GPU上运算(致使速度很慢)。一旦你肯定了你的idea,你就须要用C++重写其内核。 在实践中,咱们通常在Tensorboard中用python操做进行可视化。若是你是在构建一个图片分类模型,并且想要在训练过程当中可视化你的模型预测,那么TF容许你经过tf.summary.image()函数进行图片的可视化。app

image = tf.placeholder(tf.float32)
tf.summary.image("image", image)
复制代码

可是这仅仅是可视化了输入的图片,为了可视化其预测结果,你还必须找一个方法在图片上添加预测标识,固然这在现有的tensorflow操做中是不存在的。一个更简单的方法就是经过python将预测标志绘制到图片上,而后再封装它。dom

import io
import matplotlib.pyplot as plt
import numpy as np
import PIL
import tensorflow as tf

def visualize_labeled_images(images, labels, max_outputs=3, name="image"):
    def _visualize_image(image, label):
        # Do the actual drawing in python
        fig = plt.figure(figsize=(3, 3), dpi=80)
        ax = fig.add_subplot(111)
        ax.imshow(image[::-1,...])
        ax.text(0, 0, str(label),
          horizontalalignment="left",
          verticalalignment="top")
        fig.canvas.draw()

        # Write the plot as a memory file.
        buf = io.BytesIO()
        data = fig.savefig(buf, format="png")
        buf.seek(0)

        # Read the image and convert to numpy array
        img = PIL.Image.open(buf)
        return np.array(img.getdata()).reshape(img.size[0], img.size[1], -1)

    def _visualize_images(images, labels):
        # Only display the given number of examples in the batch
        outputs = []
        for i in range(max_outputs):
            output = _visualize_image(images[i], labels[i])
            outputs.append(output)
        return np.array(outputs, dtype=np.uint8)

    # Run the python op.
    figs = tf.py_func(_visualize_images, [images, labels], tf.uint8)
    return tf.summary.image(name, figs)
复制代码

请注意,由于summary一般只评估一次(并非每步都执行),所以能够在实践中可使用而没必要担忧效率。ide

相关文章
相关标签/搜索