本文通过对relu激活函数的剖析,学习类的创建与实例化,数组与列表的区别,copy函数的用法等知识,均在注释中有所提及:
import numpy as np
class ReLU:
def __init__(self):
self.mask = None
def forward(self, x):
r'''
ReLU激活函数的前向传播。
Parameter:
- x: numpy.array, (B, d1, d2, ..., dk)
Return:
- y: numpy.array, (B, d1, d2, ..., dk)
'''
########## Begin ##########
self.mask = (x <= 0)#true=1,false=0
# print(self.mask)
out = x.copy() #out[0]=x,将另一个对象关联到这个对象的副本,关联到[0]的位置,也就是副本的位置
out[self.mask] = 0
return out#总是输出out[1]
########## End ##########
# print(ReLU(4))
# john=ReLU()
# john.out=4
# john.forward(john.out)
x= np.array([[-2, -1, 0], [1, 2 ,3 ]]).astype(np.float32)#把二维列表转化成数组,float32数位越高浮点数的精度越高
# x=([[-2, -1, 0], [1, 2, 3]])#'<=' not supported between instances of 'list' and 'int'
print(ReLU().forward(x))