import numpy as np
import matplotlib.pyplot as plt
from unagi import chan
class Sigmoid(Chan):
def pai(self,a):
self.h = 1/(1+np.exp(-a))
return self.h
def yon(self,g):
return g*(1.-self.h)*self.h
def plot(f):
a = np.linspace(-5,5,201)
h = f.pai(a)
plt.axes(aspect=1,xticks=range(-5,6),yticks=range(-5,6))
plt.plot(a,h,'#eeaaaa',lw=3)
plt.grid(ls=':')
plt.show()
plot(Sigmoid())
plot(Relu())
class Relu(Chan):
def pai(self,x):
self.krong = (x>0)
return np.where(self.krong,x,0)
def yon(self,g):
return np.where(self.krong,g,0)
plot(Relu())
class Lrelu(Chan):
def __init__(self,a=0.01):
self.a = a
def pai(self,x):
self.krong = (x>0)
return x*np.where(self.krong,1,self.a)
def yon(self,g):
return g*np.where(self.krong,1,self.a)
plot(Lrelu(0.1))
class Prelu(Chan):
def __init__(self,m,a=0.25):
self.param = [Param(np.ones(m)*a)]
def pai(self,x):
self.krong = (x>0)
self.x = x
return x*np.where(self.krong,1,self.param[0].kha)
def yon(self,g):
self.param[0].g += (self.x*(self.krong==0)).sum(0)
return g*np.where(self.krong,1,self.param[0].kha)
plot(Prelu(1,0.25))
class Elu(Chan):
def __init__(self,a=1):
self.a = a
def pai(self,x):
self.krong = (x>0)
self.h = np.where(self.krong,x,self.a*(np.exp(x)-1))
return self.h
def yon(self,g):
return g*np.where(self.krong,1,(self.h+self.a))
plot(Elu(1))
class Selu(Chan):
a = 1.6732632423543772848170429916717
l = 1.0507009873554804934193349852946
def pai(self,x):
self.krong = (x>0)
self.h = self.l*np.where(self.krong,x,self.a*(np.exp(x)-1))
return self.h
def yon(self,g):
return g*self.l*np.where(self.krong,1,(self.h+self.a))
plot(Selu())
class Tanh(Chan):
def pai(self,x):
self.h = np.tanh(x)
return self.h
def yon(self,g):
return g*(1-self.h**2)
plot(Tanh())
class Softsign(Chan):
def pai(self,x):
self.abs_x_1 = np.abs(x)+1
return x/self.abs_x_1
def yon(self,g):
return g/self.abs_x_1**2
plot(Softsign())
class Softplus(Chan):
def pai(self,x):
self.exp_x = np.exp(x)
return np.log(1+self.exp_x)
def yon(self,g):
return g*self.exp_x/(1+self.exp_x)
plot(Softplus())
chue = [u'ReLU',u'LReLU(0.1)',u'PReLU(0.25)',u'ELU(1)',u'SELU',u'softplus',u'sigmoid',u'tanh',u'softsign']
plt.figure(figsize=[7,5])
for i,f in enumerate([Relu(),Lrelu(0.1),Prelu(1,0.25),Elu(1),Selu(),Softplus(),Sigmoid(),Tanh(),Softsign()]):
a = np.linspace(-4,4,201)
h = f.pai(a)
plt.subplot(331+i,aspect=1,xlim=[-4,4],xticks=range(-5,6),yticks=range(-5,6))
plt.title(chue[i])
plt.plot(a,h,color=np.random.random(3),lw=2)
plt.grid(ls='--')
plt.tight_layout()
plt.show()
ติดตามอัปเดตของบล็อกได้ที่แฟนเพจ