【问题标题】:Teaching neural network Xor function教学神经网络异或函数
【发布时间】:2018-03-14 13:13:03
【问题描述】:

我想用 3 层来教我的神经网络异或: 1. 具有 2 个神经元的输入层完全连接到具有 2 个神经元的下一个单个隐藏层 具有单个输出神经元的第三输出层。我将使用 sigmoid 激活函数和梯度下降。

我的问题是: 1.应该如何制定停止函数:我知道我们可以检查迭代次数或检查误差是否小于某个可接受的误差,但是应该如何计算这个误差?公式是什么?只有在输出层上计算的误差?在教授一个样本的单程过程中? 2.偏差值可以小于1但大于0吗?一些描述告诉它应该始终为 1,但其他描述可以是此范围内的随机数。

【问题讨论】:

    标签: machine-learning neural-network artificial-intelligence


    【解决方案1】:

    这是一个带有反向传播的隐藏层网络,可以对其进行定制,以运行带有 relu、sigmoid 和其他激活的实验。经过多次实验,得出的结论是,使用 relu 的网络性能更好,更快地达到收敛,而使用 sigmoid 的损失值波动。发生这种情况是因为“the gradient of sigmoids becomes increasingly small as the absolute value of x increases”。

    import numpy as np
    import matplotlib.pyplot as plt
    from operator import xor
    
    class neuralNetwork():
        def __init__(self):
            # Define hyperparameters
            self.noOfInputLayers = 2
            self.noOfOutputLayers = 1
            self.noOfHiddenLayerNeurons = 2
    
            # Define weights
            self.W1 = np.random.rand(self.noOfInputLayers,self.noOfHiddenLayerNeurons)
            self.W2 = np.random.rand(self.noOfHiddenLayerNeurons,self.noOfOutputLayers)
    
        def relu(self,z):
            return np.maximum(0,z)
    
        def sigmoid(self,z):
            return 1/(1+np.exp(-z))
    
        def forward (self,X):
            self.z2 = np.dot(X,self.W1)
            self.a2 = self.relu(self.z2)
            self.z3 = np.dot(self.a2,self.W2)
            yHat = self.relu(self.z3)
            return yHat
    
        def costFunction(self, X, y):
            #Compute cost for given X,y, use weights already stored in class.
            self.yHat = self.forward(X)
            J = 0.5*sum((y-self.yHat)**2)
            return J
    
        def costFunctionPrime(self,X,y):
            # Compute derivative with respect to W1 and W2
            delta3 = np.multiply(-(y-self.yHat),self.sigmoid(self.z3))
            djw2 = np.dot(self.a2.T, delta3)
            delta2 = np.dot(delta3,self.W2.T)*self.sigmoid(self.z2)
            djw1 = np.dot(X.T,delta2)
    
            return djw1,djw2
    
    
    if __name__ == "__main__":
    
        EPOCHS = 6000
        SCALAR = 0.01
    
        nn= neuralNetwork()    
        COST_LIST = []
    
        inputs = [ np.array([[0,0]]), np.array([[0,1]]), np.array([[1,0]]), np.array([[1,1]])]
    
        for epoch in xrange(1,EPOCHS):
            cost = 0
            for i in inputs:
                X = i #inputs
                y = xor(X[0][0],X[0][1])
                cost += nn.costFunction(X,y)[0]
                djw1,djw2 = nn.costFunctionPrime(X,y)
                nn.W1 = nn.W1 - SCALAR*djw1
                nn.W2 = nn.W2 - SCALAR*djw2
            COST_LIST.append(cost)
    
        plt.plot(np.arange(1,EPOCHS),COST_LIST)
        plt.ylim(0,1)
        plt.xlabel('Epochs')
        plt.ylabel('Loss')
        plt.title(str('Epochs: '+str(EPOCHS)+', Scalar: '+str(SCALAR)))
        plt.show()
    
        inputs = [ np.array([[0,0]]), np.array([[0,1]]), np.array([[1,0]]), np.array([[1,1]])]
        print "X\ty\ty_hat"
        for inp in inputs:
            print (inp[0][0],inp[0][1]),"\t",xor(inp[0][0],inp[0][1]),"\t",round(nn.forward(inp)[0][0],4)
    

    最终结果:

    X       y       y_hat
    (0, 0)  0       0.0
    (0, 1)  1       0.9997
    (1, 0)  1       0.9997
    (1, 1)  0       0.0005
    

    训练后得到的权重为:

    nn.w1

    [ [-0.81781753  0.71323677]
      [ 0.48803631 -0.71286155] ]
    

    nn.w2

    [ [ 2.04849235]
      [ 1.40170791] ]
    

    我发现以下 youtube 系列对理解神经网络非常有帮助:Neural networks demystified

    我知道的很少,也可以在这个答案中解释。如果您想更好地了解神经网络,那么我建议您通过以下链接:[cs231n: Modeling one neuron][4]

    【讨论】:

    • 成本函数是如何计算的?单样本训练?只涉及输出神经元?
    猜你喜欢
    • 1970-01-01
    • 2011-05-10
    • 2014-05-29
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2018-10-19
    • 2016-07-11
    • 2022-01-21
    相关资源
    最近更新 更多