Tensorflow: How to make a custom activation function with only python?
<p>So in Tensorflow it is possible to make your own activation function. But it is quite complicated, you have to write it in C++ and recompile the whole of tensorflow <a href="https://www.quora.com/Is-it-possible-to-add-new-activation-functions-to-TensorFlow-Theano-Torch-How" rel="nofollow">[1]</a> <a href="https://www.tensorflow.org/versions/r0.11/how_tos/adding_an_op/index.html" rel="nofollow">[2]</a>.</p>

<p>Is there a simpler way?</p>

<p><strong>Yes There is!</strong></p>

<p><strong>Credit:</strong>
It was hard to find the information and get it working but here is an example copying from the principles and code found <a href="https://github.com/tensorflow/tensorflow/issues/1095" rel="nofollow">here</a> and <a href="https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342" rel="nofollow">here</a>.</p>

<p><strong>Requirements:</strong>
Before we start, there are two requirement for this to be able to succeed. First you need to be able to write your activation as a function on numpy arrays. Second you have to be able to write the derivative of that function either as a function in Tensorflow (easier) or in the worst case scenario as a function on numpy arrays. </p>

<p><strong>Writing Activation function:</strong></p>

<p>So let's take for example this function which we would want to use an activation function:</p>

<pre><code>def spiky(x):
    r = x % 1
    if r &lt;= 0.5:
        return r
    else:
        return 0
</code></pre>

<p>Which look as follows:
<a href="http://i.stack.imgur.com/gTUBr.png" rel="nofollow"><img src="http://i.stack.imgur.com/gTUBr.png" alt="Spiky Activation"></a></p>

<p>The first step is making it into a numpy function, this is easy:</p>

<pre><code>import numpy as np
np_spiky = np.vectorize(spiky)
</code></pre>

<p>Now we should write its derivative.</p>

<p><strong>Gradient of Activation:</strong>
In our case it is easy, it is 1 if x mod 1 &lt; 0.5 and 0 otherwise. So:</p>

<pre><code>def d_spiky(x):
    r = x % 1
    if r &lt;= 0.5:
        return 1
    else:
        return 0
np_d_spiky = np.vectorize(d_spiky)
</code></pre>

<p>Now for the hard part of making a TensorFlow function out of it.</p>

<p><strong>Making a numpy fct to a tensorflow fct:</strong>
We will start by making np_d_spiky into a tensorflow function. There is a function in tensorflow <code>tf.py_func(func, inp, Tout, stateful=stateful, name=name)</code> <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/script_ops.html" rel="nofollow">[doc]</a> which transforms any numpy function to a tensorflow function, so we can use it:</p>

<pre><code>import tensorflow as tf
from tensorflow.python.framework import ops

np_d_spiky_32 = lambda x: np_d_spiky(x).astype(np.float32)


def tf_d_spiky(x,name=None):
    with ops.op_scope([x], name, "d_spiky") as name:
        y = tf.py_func(np_d_spiky_32,
                        [x],
                        [tf.float32],
                        name=name,
                        stateful=False)
        return y[0]
</code></pre>

<p><code>tf.py_func</code> acts on lists of tensors (and returns a list of tensors), that is why we have <code>[x]</code> (and return <code>y[0]</code>). The <code>stateful</code> option is to tell tensorflow whether the function always gives the same output for the same input (stateful = False) in which case tensorflow can simply the tensorflow graph, this is our case and will probably be the case in most situations. One thing to be careful of at this point is that numpy used <code>float64</code> but tensorflow uses <code>float32</code> so you need to convert your function to use <code>float32</code> before you can convert it to a tensorflow function otherwise tensorflow will complain. This is why we need to make <code>np_d_spiky_32</code> first. </p>

<p><strong>What about the Gradients?</strong> The problem with only doing the above is that even though we now have <code>tf_d_spiky</code> which is the tensorflow version of <code>np_d_spiky</code>, we couldn't use it as an activation function if we wanted to because tensorflow doesn't know how to calculate the gradients of that function. </p>

<p><strong>Hack to get Gradients:</strong> As explained in the sources mentioned above, there is a hack to define gradients of a function using <code>tf.RegisterGradient</code> <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html#RegisterGradient" rel="nofollow">[doc]</a> and <code>tf.Graph.gradient_override_map</code> <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html" rel="nofollow">[doc]</a>. Copying the code from <a href="https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342" rel="nofollow">harpone</a> we can modify the <code>tf.py_func</code> function to make it define the gradient at the same time:</p>

<pre><code>def py_func(func, inp, Tout, stateful=True, name=None, grad=None):

    # Need to generate a unique name to avoid duplicates:
    rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))

    tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
    g = tf.get_default_graph()
    with g.gradient_override_map({"PyFunc": rnd_name}):
        return tf.py_func(func, inp, Tout, stateful=stateful, name=name)
</code></pre>

<p>Now we are almost done, the only thing is that the grad function we need to pass to the above py_func function needs to take a special form. It needs to take in an operation, and the previous gradients before the operation and propagate the gradients backward after the operation.</p>

<p><strong>Gradient Function:</strong> So for our spiky activation function that is how we would do it:</p>

<pre><code>def spikygrad(op, grad):
    x = op.inputs[0]

    n_gr = tf_d_spiky(x)
    return grad * n_gr  
</code></pre>

<p>The activation function has only one input, that is why <code>x = op.inputs[0]</code>. If the operation had many inputs, we would need to return a tuple, one gradient for each input. For example if the operation was <code>a-b</code>the gradient with respect to <code>a</code> is <code>+1</code> and with respect to <code>b</code> is <code>-1</code> so we would have <code>return +1*grad,-1*grad</code>. Notice that we need to return tensorflow functions of the input, that is why need <code>tf_d_spiky</code>, <code>np_d_spiky</code> would not have worked because it cannot act on tensorflow tensors. Alternatively we could have written the derivative using tensorflow functions:</p>

<pre><code>def spikygrad2(op, grad):
    x = op.inputs[0]
    r = tf.mod(x,1)
    n_gr = tf.to_float(tf.less_equal(r, 0.5))
    return grad * n_gr  
</code></pre>

<p><strong>Combining it all together:</strong> Now that we have all the pieces, we can combine them all together:</p>

<pre><code>np_spiky_32 = lambda x: np_spiky(x).astype(np.float32)

def tf_spiky(x, name=None):

    with ops.op_scope([x], name, "spiky") as name:
        y = py_func(np_spiky_32,
                        [x],
                        [tf.float32],
                        name=name,
                        grad=spikygrad)  # &lt;-- here's the call to the gradient
        return y[0]
</code></pre>

<p>And now we are done. And we can test it.</p>

<p><strong>Test:</strong></p>

<pre><code>with tf.Session() as sess:

    x = tf.constant([0.2,0.7,1.2,1.7])
    y = tf_spiky(x)
    tf.initialize_all_variables().run()

    print(x.eval(), y.eval(), tf.gradients(y, [x])[0].eval())
</code></pre>

<blockquote>
  <p>[ 0.2 0.69999999  1.20000005  1.70000005] [ 0.2 0. 0.20000005  0.] [ 1.  0.  1.  0.]</p>
</blockquote>

<p><strong>Success!</strong></p>

python tensorflow custom-build activation-function