
【pythonでニューラルネットワーク#8】線形変換と活性化関数と損失関数
記事の目的
pythonで線形変換と活性化関数と損失関数を実装していきます。ここにある全てのコードは、コピペで再現することが可能です。
目次
1 それぞれの関数



2 線形変換の実装

# In[1]
import numpy as np
np.random.seed(1)
# In[2]
class Optimizer:
def step(self, lr):
self.w -= lr * self.dw
self.b -= lr * self.db
class Linear(Optimizer):
def __init__(self, x_n, y_n):
self.w = np.random.randn(x_n, y_n) * np.sqrt(2/x_n)
self.b = np.zeros(y_n)
def forward(self, x):
self.x = x
self.y = np.dot(x, self.w) + self.b
return self.y
def backward(self, dy):
self.dw = np.dot(self.x.T, dy)
self.db = np.sum(dy, axis=0)
self.dx = np.dot(dy, self.w.T)
return self.dx
# In[3]
x = np.random.randn(5,10)
x
# In[4]
model = Linear(10, 3)
y1 = model.forward(x)
y1
# In[5]
model.backward(np.ones((5,3))).shape
# In[6]
model.dw
# In[7]
model.db
3 活性化関数の実装

# In[8]
class Relu:
def forward(self, x):
self.x = x
y = np.where(self.x <= 0, 0, self.x)
return y
def backward(self, dy):
dx =dy * np.where(self.x <= 0, 0, 1)
return dx
# In[9]
y1
# In[10]
relu = Relu()
# In[11]
y2 = relu.forward(y1)
y2
# In[12]
relu.backward(1)
4損失関数の実装

# In[13]
class CELoss:
def forward(self, x, t):
self.t = t
self.y = np.exp(x)/np.sum(np.exp(x), axis=1, keepdims=True) # ソフトマックス関数
L = -np.sum(t*np.log(self.y+1e-7)) / len(self.y)
return L
def backward(self):
dx = self.y - self.t
return dx
# In[14]
y2
# In[15]
t = np.zeros((5,3))
t[0,0], t[1,0], t[2,2], t[3,2], t[4,0] = np.ones(5)
t
# In[16]
loss = CELoss()
# In[17]
loss.forward(y2,t)
# In[18]
loss.backward()