class Buak:
def pai(self,x,y): # ไปข้างหน้า
return x+y
def yon(self,g): # ย้อนกลับ
return g, g
class Lop:
def pai(self,x,y):
return x-y
def yon(self,g):
return g, -g
class Khun:
def pai(self,x,y):
self.x = x
self.y = y
return x*y
def yon(self,g):
return g*self.y, g*self.x
class Han:
def pai(self,x,y):
self.x = x
self.y = y
return x/y
def yon(self,g):
return g/self.y, -g*self.x/self.y**2
lop = Lop()
khun = Khun()
han = Han()
a = 1
b = 2
c = 3
d = 4
e = lop.pai(a,b)
f = khun.pai(c,d)
x = han.pai(f,e)
print('e=%d, f=%d, x=%d'%(e,f,x))
gf,ge = han.yon(1)
gc,gd = khun.yon(gf)
ga,gb = lop.yon(ge)
print('ga=%d, gb=%d, gc=%d\ngd=%d, ge=%d, gf=%d'%(ga,gb,gc,gd,gf,ge))
e=-1, f=12, x=-12
ga=-12, gb=12, gc=-4
gd=-3, ge=-1, gf=-12
import numpy as np
class Exp:
def pai(self,x):
self.expx = np.exp(x)
return self.expx
def yon(self,g):
return g*self.expx
class Ln:
def pai(self,x):
self.x = x
return np.log(x)
def yon(self,g):
return g/self.x
class Sigmoid:
def pai(self,x):
self.h = 1/(1+np.exp(-x))
return self.h
def yon(self,g):
return g*(1.-self.h)*self.h
class Relu:
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)
class KhunW_BuakB:
def __init__(self,w,b):
self.w = w
self.b = b
self.gw = 0
self.gb = 0
def pai(self,x):
self.x = x
return self.w*x+self.b
def yon(self,g):
self.gw += g*self.x
self.gb += g
return g*self.w
f1 = KhunW_BuakB(2,1)
f2 = KhunW_BuakB(3,4)
x = 3
y = f1.pai(x)
print(y) # 3*2+1 = 7
z = f2.pai(y)
print(z) # 7*3+4 = 25
gy = f2.yon(1)
print(gy) # 1*3 = 3
print(f2.gw,f2.gb) # 1*7 = 7, 1
gx = f1.yon(gy)
print(gx) # 3*2 = 6
print(f1.gw,f1.gb) # 3*3 = 9, 3
class Affin:
def __init__(self,w,b):
self.w = w
self.b = b
self.gw = 0
self.gb = 0
def pai(self,X):
self.X = X
return np.dot(X,self.w) + self.b
def yon(self,g):
self.gw += np.dot(self.X.T,g)
self.gb += g.sum(0)
return np.dot(g,self.w.T)
af = Affin(np.random.randint(0,9,[3,4]),np.random.randint(0,9,4))
x = np.random.randint(0,9,[2,3])
print(x)
print(af.w)
print(af.b)
a = af.pai(x)
print(a)
gx = af.yon(np.ones([2,4]))
print(gx)
print(af.gw)
print(af.gb)
ได้
[[3 1 3]
[1 3 3]]
[[8 0 8 8]
[0 7 0 8]
[8 1 6 5]]
[7 3 5 2]
[[55 13 47 49]
[39 27 31 49]]
[[ 24. 15. 20.]
[ 24. 15. 20.]]
[[ 4. 4. 4. 4.]
[ 4. 4. 4. 4.]
[ 6. 6. 6. 6.]]
[ 2. 2. 2. 2.]
ติดตามอัปเดตของบล็อกได้ที่แฟนเพจ