BP神经网络(python代码)

神经网络是深度学习的基础。个人理解神经网络就是可以拟合任何一种广义线性模型的结构,本文主要记录python代码的学习笔记。

BP神经网络原理(待补充,可以详见《数据挖掘概念与技术》P258页)

伪代码:


代码中使用的随机梯度下降,伪代码是使用整体数据做梯度下降。

# coding=utf-8
import numpy as np

def tanh(x):
    return np.tanh(x)

def tanh_deriv(x):
    return 1.0- np.tanh(x)*np.tanh(x)

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

def logistic_derivative(x):
    return logistic(x)*(1-logistic(x))

class NeuralNetwork:
    def __init__(self,layers,activation='tanh'):
        """

        """
        if activation == 'logistic':
            self.activation = logistic
            self.activation_deriv = logistic_derivative
        elif activation=='tanh':
            self.activation = tanh
            self.activation_deriv=tanh_deriv

        self.weights=[]
        self.weights.append((2*np.random.random((layers[0]+1,layers[1]))-1)*0.25)
        for i in range(2,len(layers)):
            self.weights.append((2*np.random.random((layers[i-1],layers[i]))-1)*0.25)
            #self.weights.append((2*np.random.random((layers[i]+1,layers[i+1]))-1)*0.25)

    def fit(self,X,y,learning_rate=0.2,epochs=10000):
        X = np.atleast_2d(X)
            # atlest_2d函数:确认X至少二位的矩阵
        temp = np.ones([X.shape[0],X.shape[1]+1])
            #初始化矩阵全是1(行数,列数+1是为了有B这个偏向)
        temp[:,0:-1]=X
            #行全选,第一列到倒数第二列
        X=temp
        y=np.array(y)
            #数据结构转换
        for k in range(epochs):
                # 抽样梯度下降epochs抽样
            i = np.random.randint(X.shape[0])
            a = [X[i]]

            for l in range(len(self.weights)):
                a.append(self.activation(np.dot(a[l],self.weights[l])))
                # 向前传播,得到每个节点的输出结果
            error = y[i]-a[-1]
                # 最后一层错误率
            deltas=[error*self.activation_deriv(a[-1])]

            for l in range(len(a)-2,0,-1):
                deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_deriv(a[l]))
            deltas.reverse()
            for i in range(len(self.weights)):
                layer = np.atleast_2d(a[i])
                delta = np.atleast_2d(deltas[i])
                self.weights[i] +=learning_rate*layer.T.dot(delta)

    def predict(self,x):
        x=np.array(x)
        temp= np.ones(x.shape[0]+1)
        temp[0:-1]=x
        a = temp
        for l in range(0,len(self.weights)):
            a=self.activation(np.dot(a,self.weights[l]))
        return(a)


下面为测试“异或”数据的代码:
因为输入是2个特征的所以输入层为2,隐藏层我随意定义了12,输出层为1(因为结果为0或1所以1位就够定义了。)


from BPNN import NeuralNetwork
import numpy as np

nn = NeuralNetwork([2,12,1],'tanh')
x = np.array([[0,0],[0,1],[1,0],[1,1]])
y = np.array([0,1,1,0])
nn.fit(x,y)
for i in [[0,0],[0,1],[1,0],[1,1]]:
    print(i,nn.predict(i))

代码结果:

([0, 0], array([-0.00917032]))
([0, 1], array([ 0.99785397]))
([1, 0], array([ 0.9979288]))
([1, 1], array([ 0.01522156]))


特别感谢:彭亮的指点,给了我很大的帮助。



  • 11
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
BP神经网络是一种常用的人工神经网络,用于解决各种分类和预测问题。Python是一门流行的编程语言,它提供了一个灵活的环境,可以轻松地构建和实现BP神经网络。 在Python中实现BP神经网络代码可以分为三个主要部分:输入层、隐藏层和输出层。输入层用来接收数据,隐藏层用于处理数据并生成预测,输出层用于将预测结果输出。 以下是一个简单的BP神经网络Python代码实现: ``` python import numpy as np class BP: def __init__(self, in_dim, out_dim, hidden_dim): self.in_dim = in_dim self.out_dim = out_dim self.hidden_dim = hidden_dim self.weights1 = np.random.rand(self.in_dim, self.hidden_dim) self.biases1 = np.random.rand(self.hidden_dim) self.weights2 = np.random.rand(self.hidden_dim, self.out_dim) self.biases2 = np.random.rand(self.out_dim) def sigmoid(self, x): return 1/(1 + np.exp(-x)) def forward(self, X): self.Z1 = np.dot(X, self.weights1) + self.biases1 self.A1 = self.sigmoid(self.Z1) self.Z2 = np.dot(self.A1, self.weights2) + self.biases2 self.A2 = self.sigmoid(self.Z2) def derivative_sigmoid(self, x): return x*(1-x) def backward(self, X, y, lr): error = y - self.A2 delta2 = error*self.derivative_sigmoid(self.A2) self.weights2 += lr*np.dot(self.A1.T, delta2) self.biases2 += lr*np.sum(delta2, axis=0) delta1 = np.dot(delta2, self.weights2.T)*self.derivative_sigmoid(self.A1) self.weights1 += lr*np.dot(X.T, delta1) self.biases1 += lr*np.sum(delta1, axis=0) def train(self, X, y, lr=0.01, epochs=1000): for i in range(epochs): self.forward(X) self.backward(X, y, lr) def predict(self, X): self.forward(X) return self.A2 ``` 在上述Python代码中,我们通过使用NumPy库来创建一个BP神经网络。与其他神经网络相似,我们有一些参数,如输入维度,隐藏维度和输出维度等等。我们使用NumPy来生成随机权重和偏置。我们使用sigmoid函数作为激活函数。前向传递使用dot函数来计算权重和输入的乘积,使用sigmoid激活函数计算输出,反向传递使用误差来反向调整权重和偏差。在训练神经网络时,我们通过迭代来调整权重和偏差并降低误差。通过对BP神经网络的训练和预测,我们可以处理各种分类和预测问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值