如何在 GPU 上的数组上运行 expit 函数?

问题描述

我正在尝试对基于简单神经网络的手写数字识别应用程序进行基准测试。它目前使用 Numpy 作为矩阵,并使用 scipy 的 expit 函数进行激活。尽管如此(非常基本的网络),我想在 GPU 上运行这整个事情,因此决定使用 Cupy 库。

很遗憾,我无法让 expit 函数在 GPU 上运行。我不断收到一条错误消息,指出“未实现”。

self.activation_function = lambda x: scipy.special.expit(x)

错误信息

TypeError:operand type(s) all returned NotImplemented from array_ufunc(,'call',array([[ 0.96079161],[1.37400426], [-0.46329254]])): 'ndarray'

解决方法

我今天刚遇到完全相同的问题,您可以尝试使用 CuPy 的 User-Defined Kernels 定义函数。

对于sigmoid函数:

import cupy as cp

expit = cp.ElementwiseKernel(
        'float64 x','float64 y','y = 1 / (1 + exp(-x))','expit')

>>> x = cp.arange(10,dtype=np.float64).reshape(2,5)
>>> expit(x)
array([[0.5,0.73105858,0.88079708,0.95257413,0.98201379],[0.99330715,0.99752738,0.99908895,0.99966465,0.99987661]])

>>> scipy.special.expit(x.get())
array([[0.5,0.7310586,0.880797,0.98201376],[0.9933072,0.9975274,0.999089,0.99966466,0.9998766 ]],dtype=float32)