Theano HiddenLayer激活功能

A.M*_*.M. 11 python machine-learning neural-network theano

反正是有使用整流直线运动单元(RELU)作为隐藏层的,而不是激活功能tanh()sigmoid()在Theano?隐藏层的实现如下,据我在互联网上搜索,ReLU没有在Theano中实现.

class HiddenLayer(object):
  def __init__(self, rng, input, n_in, n_out, W=None, b=None, activation=T.tanh):
    pass
Run Code Online (Sandbox Code Playgroud)

nou*_*uiz 16

在Theano很容易做到relu:

switch(x<0, 0, x)
Run Code Online (Sandbox Code Playgroud)

要在你的情况下使用它,创建一个python函数,它将实现relu并将其传递给激活:

def relu(x):
    return theano.tensor.switch(x<0, 0, x)
HiddenLayer(..., activation=relu)
Run Code Online (Sandbox Code Playgroud)

有些人使用这个实现: x * (x > 0)

更新:较新的Theano版本有theano.tensor.nnet.relu(x)可用.


All*_*leo 8

更新: theano的最新版本具有ReLU的原生支持: T.nnet.relu,它应该优于自定义解决方案.

我决定比较解决方案的速度,因为它对NN非常重要.比较函数本身的速度和它的梯度,在第一种情况下switch是优选的,对于x*(x> 0),梯度更快.所有计算的梯度都是正确的.

def relu1(x):
    return T.switch(x<0, 0, x)

def relu2(x):
    return T.maximum(x, 0)

def relu3(x):
    return x * (x > 0)


z = numpy.random.normal(size=[1000, 1000])
for f in [relu1, relu2, relu3]:
    x = theano.tensor.matrix()
    fun = theano.function([x], f(x))
    %timeit fun(z)
    assert numpy.all(fun(z) == numpy.where(z > 0, z, 0))

Output: (time to compute ReLU function)
>100 loops, best of 3: 3.09 ms per loop
>100 loops, best of 3: 8.47 ms per loop
>100 loops, best of 3: 7.87 ms per loop

for f in [relu1, relu2, relu3]:
    x = theano.tensor.matrix()
    fun = theano.function([x], theano.grad(T.sum(f(x)), x))
    %timeit fun(z)
    assert numpy.all(fun(z) == (z > 0)

Output: time to compute gradient 
>100 loops, best of 3: 8.3 ms per loop
>100 loops, best of 3: 7.46 ms per loop
>100 loops, best of 3: 5.74 ms per loop
Run Code Online (Sandbox Code Playgroud)

最后,让我们比较如何计算梯度(最快的方法)

x = theano.tensor.matrix()
fun = theano.function([x], x > 0)
%timeit fun(z)
Output:
>100 loops, best of 3: 2.77 ms per loop
Run Code Online (Sandbox Code Playgroud)

因此theano为渐变生成了不理想的代码.恕我直言,今天的开关版本应该是首选.