为了构建一个简单的 1 层神经网络,许多教程使用 sigmoid 函数作为激活函数。根据学术文章和其他在线资源,泄漏的 ReLU 是更好的选择;但是,我找不到改变我的代码片段以允许泄漏 ReLU 的方法。
我尝试if x > 0 then x else x/100了像激活函数这样的逻辑,然后对导数也一样。
是否因为输出层不能有 ReLU 而失败?我应该将第一层更改为 ReLU,然后添加一个 softmax 输出层吗?
import numpy as np
np.random.seed(1)
X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
y = np.array([[0,1,0,1]]).T
class NN:
def __init__(self, X, y):
self.X = X
self.y = y
self.W = np.random.uniform(-1, 1, (X.shape[1], 1))
self.b = np.random.uniform(-1, 1, (X.shape[1], 1))
def nonlin(self, x, deriv=False):
if deriv:
return x*(1-x)
return 1/(1+np.exp(-x))
def forward(self):
self.l1 = self.nonlin(np.dot(self.X, self.W + self.b))
self.errors = self.y - self.l1
print(abs(sum(self.errors)[0]))
def backward(self):
self.l1_delta = self.errors * nonlin(self.l1, True)
self.W += np.dot(self.X.T, self.l1_delta)
self.b += np.dot(self.X.T, self.l1_delta)
def train(self, epochs=20):
for _ in range(epochs):
self.forward()
self.backward()
nn = NN(X, y)
nn.train()

