如何在Numpy中实现ReLU函数 [英] How to implement the ReLU function in Numpy

查看:30
本文介绍了如何在Numpy中实现ReLU函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个使用 ReLU 函数的简单神经网络.有人可以告诉我如何使用 numpy 实现该功能.

解决方案

有几种方法.

<预><代码>>>>x = np.random.random((3, 2)) - 0.5>>>X数组([[-0.00590765, 0.18932873],[-0.32396051, 0.25586596],[ 0.22358098, 0.02217555]])>>>np.maximum(x, 0)数组([[ 0. , 0.18932873],[0., 0.25586596],[ 0.22358098, 0.02217555]])>>>x * (x > 0)数组([[-0., 0.18932873],[-0., 0.25586596],[ 0.22358098, 0.02217555]])>>>(绝对(x) + x)/2数组([[ 0. , 0.18932873],[0., 0.25586596],[ 0.22358098, 0.02217555]])

如果使用以下代码对结果进行计时:

将 numpy 导入为 npx = np.random.random((5000, 5000)) - 0.5打印(最大方法:")%timeit -n10 np.maximum(x, 0)打印(乘法方法:")%timeit -n10 x * (x > 0)打印(绝对方法:")%timeit -n10 (abs(x) + x)/2

我们得到:

max 方法:10 个循环,最好的 3 个:每个循环 239 毫秒乘法:10 个循环,最好的 3 个:每个循环 145 毫秒绝对方法:10 个循环,最好的 3 个:每个循环 288 毫秒

所以乘法似乎是最快的.

I want to make a simple neural network which uses the ReLU function. Can someone give me a clue of how can I implement the function using numpy.

解决方案

There are a couple of ways.

>>> x = np.random.random((3, 2)) - 0.5
>>> x
array([[-0.00590765,  0.18932873],
       [-0.32396051,  0.25586596],
       [ 0.22358098,  0.02217555]])
>>> np.maximum(x, 0)
array([[ 0.        ,  0.18932873],
       [ 0.        ,  0.25586596],
       [ 0.22358098,  0.02217555]])
>>> x * (x > 0)
array([[-0.        ,  0.18932873],
       [-0.        ,  0.25586596],
       [ 0.22358098,  0.02217555]])
>>> (abs(x) + x) / 2
array([[ 0.        ,  0.18932873],
       [ 0.        ,  0.25586596],
       [ 0.22358098,  0.02217555]])

If timing the results with the following code:

import numpy as np

x = np.random.random((5000, 5000)) - 0.5
print("max method:")
%timeit -n10 np.maximum(x, 0)

print("multiplication method:")
%timeit -n10 x * (x > 0)

print("abs method:")
%timeit -n10 (abs(x) + x) / 2

We get:

max method:
10 loops, best of 3: 239 ms per loop
multiplication method:
10 loops, best of 3: 145 ms per loop
abs method:
10 loops, best of 3: 288 ms per loop

So the multiplication seems to be the fastest.

这篇关于如何在Numpy中实现ReLU函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆