标准BP算法、累积BP算法Python实现

标准BP,累积BP算法原理及MATLAB自编写实现在这里

以下是自己编写的Python的代码,欢迎指正

标准BP算法:

import numpy as np

x=np.matrix(np.random.rand(3,2)) #输入层,随机生成3个样本,每个样本有2个神经元
y=np.matrix(np.random.rand(3,2)) #输出层,随机生成3个样本,每个样本有2个神经元
q=3
N=100000
k = 0.1

'''
q: 隐层单元数目
v: 输入层到隐层的权值
r: 隐层的阀值
w: 隐层到输出层的权值
h: 输出层的阀值
k: 学习率
'''

def fc_sigmod(x):
    return 1/(1+np.exp(-x))

def standard_BP(x0,y0,q,N,k):
    L=y0.shape[1]
    n=x0.shape[1]
    v=np.matrix(np.random.rand(n,q))
    r=np.matrix(np.random.rand(1,q))
    w=np.matrix(np.random.rand(q,L))
    h=np.matrix(np.random.rand(1,L))
    index=0
    y_hat = np.matrix(np.zeros((x0.shape[0],L)))
    iter=1
    while iter<N:
        A=np.dot(x[index],v)
        b=fc_sigmod(A-r)

        B=np.dot(b,w)
        # print(h)
        y_hat[index]=fc_sigmod(B-h)

        # E=0.5*np.dot(y[index]-y_hat[index],(y[index]-y_hat[index]).T)

        '以下对各个系数进行调整'
        g=np.multiply(np.multiply(y_hat[index],(1-y_hat[index])),y[index]-y_hat[index])
        e=np.multiply(np.multiply(b,(1-b)),(w*g.T).T)

        for i in range(n):
            for j in range(q):
                v[i,j]=v[i,j]+k*e[0,j]*x[index,i]
        r=r-k*e

        for i in range(q):
            for j in range(L):
                w[i,j]=w[i,j]+k*g[0,j]*b[0,i]
        h=h-k*g
        if index>=x0.shape[0]-1:
            index=index-x0.shape[0]+1
        index = index +1
        iter=iter+1
    print('输入层到隐层的权值为:')
    print(v)
    print('隐层的阀值为:')
    print(r)
    print('隐层到输出层的权值为:')
    print(w)
    print('输出层的阀值为:')
    print(h)
    print('样本y的值')
    print(y)
    print('训练后能得到y_hat的值')
    print(y_hat)

standard_BP(x,y,q,N,k)

在这里插入图片描述
我们看到训练后预测的y_hat值与原先的已经比较接近了。当然这里的标准BP算法实现比较简单~

累积BP算法:

import numpy as np

x=np.matrix(np.random.rand(3,2)) #输入层,随机生成3个样本,每个样本有2个神经元
y=np.matrix(np.random.rand(3,2)) #输出层,随机生成3个样本,每个样本有2个神经元
q=3
N=50000
k = 0.1

'''
q: 隐层单元数目
v: 输入层到隐层的权值
r: 隐层的阀值
w: 隐层到输出层的权值
h: 输出层的阀值
k: 学习率
'''

def fc_sigmod(x):
    return 1/(1+np.exp(-x))

def acc_BP(x,y,q,N,k):
    L=y.shape[1]
    n=x.shape[1]
    v=np.matrix(np.random.rand(n,q))
    r=np.matrix(np.random.rand(1,q))
    w=np.matrix(np.random.rand(q,L))
    h=np.matrix(np.random.rand(1,L))
    b=np.matrix(np.zeros((x.shape[0],q)))
    g=np.matrix(np.zeros((x.shape[0],n)))
    e=np.matrix(np.zeros((x.shape[0],q)))

    y_hat = np.matrix(np.zeros((x.shape[0],L)))
    iter=1
    while iter<N:
        for index in range(x.shape[0]):
            A=np.dot(x[index],v)
            b[index]=fc_sigmod(A-r)

            B = np.dot(b[index],w)
            y_hat[index]=fc_sigmod(B-h)

            g[index]=np.multiply(np.multiply(y_hat[index],(1-y_hat[index])),y[index]-y_hat[index])
            e[index]=np.multiply(np.multiply(b[index],(1-b[index])),(w*g[index].T).T)
        #以下对各个系数进行调整
        #对上述的一些系数调整至取均值
        b_bar=b.mean(axis=0)
        g_bar=g.mean(axis=0)
        e_bar=e.mean(axis=0)
        x_bar=x.mean(axis=0)

        for i in range(n):
            for j in range(q):
                v[i,j]=v[i,j]+k*e_bar[0,j]*x_bar[0,i]
        r=r-k*e_bar

        for i in range(q):
            for j in range(L):
                w[i,j]=w[i,j]+k*g_bar[0,j]*b_bar[0,i]
        h=h-k*g_bar
        iter=iter+1
    print('输入层到隐层的权值为:')
    print(v)
    print('隐层的阀值为:')
    print(r)
    print('隐层到输出层的权值为:')
    print(w)
    print('输出层的阀值为:')
    print(h)
    print('样本y的值')
    print(y)
    print('训练后能得到y_hat的值')
    print(y_hat)

acc_BP(x,y,q,N,k)

在这里插入图片描述
这里训练后得到的效果不是很好,和自己先前用Matlab写的累积BP算法一样,训练后得到的y_hat值不是很准确.要想获得更加准确的模型,可以考虑一下几个因素

  • 隐层和输出层的激活函数的选取(我们这里选取的都是sigmod函数)
  • 学习因子
  • 迭代次数
  • 增加隐层单元数目
  • 设置多隐层(我们这里只设置了一个隐层)
  • 7
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
标准BP算法是一种常用的神经网络训练算法,它通过反向传播误差来更新神经网络的权重和偏置,从而实现神经网络的训练。下面是Python实现标准BP算法的步骤: 1. 初始化神经网络的权重和偏置,可以使用随机数进行初始化。 2. 对于每个训练样本,进行前向传播计算输出值,并计算误差。 3. 对于每个输出层神经元,计算其误差项。 4. 对于每个隐藏层神经元,计算其误差项。 5. 根据误差项和学习率更新神经网络的权重和偏置。 下面是一个简单的Python实现标准BP算法的代码,其中使用了numpy库进行矩阵计算: ``` import numpy as np def sigmoid(x): return 1.0 / (1 + np.exp(-x)) class NeuralNetwork: def __init__(self, input_dim, hidden_dim, output_dim): self.input_dim = input_dim self.hidden_dim = hidden_dim self.output_dim = output_dim self.W1 = np.random.randn(input_dim, hidden_dim) self.b1 = np.random.randn(hidden_dim) self.W2 = np.random.randn(hidden_dim, output_dim) self.b2 = np.random.randn(output_dim) def forward(self, X): self.z1 = np.dot(X, self.W1) + self.b1 self.a1 = sigmoid(self.z1) self.z2 = np.dot(self.a1, self.W2) + self.b2 self.a2 = sigmoid(self.z2) return self.a2 def backward(self, X, y, output): self.output_error = y - output self.output_delta = self.output_error * sigmoid(self.z2) * (1 - sigmoid(self.z2)) self.hidden_error = np.dot(self.output_delta, self.W2.T) self.hidden_delta = self.hidden_error * sigmoid(self.z1) * (1 - sigmoid(self.z1)) self.W2 += np.dot(self.a1.T, self.output_delta) self.b2 += np.sum(self.output_delta, axis=0) self.W1 += np.dot(X.T, self.hidden_delta) self.b1 += np.sum(self.hidden_delta, axis=0) def train(self, X, y, epochs, learn_rate): for i in range(epochs): output = self.forward(X) self.backward(X, y, output) if i % 1000 == 0: print("Epoch:", i, "Loss:", np.mean(np.abs(self.output_error))) print("Final Loss:", np.mean(np.abs(self.output_error))) X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([[0], [1], [1], [0]]) nn = NeuralNetwork(2, 3, 1) nn.train(X, y, 10000, 0.1) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值