手动实现BP神经

BP神经网络对于每个训练实例X,执行以下步骤:

1. 由输入层向前传(如下图所示)

2.根据误差反向传送

Oj为第j个神经元的输出值,Tj为输出层第j个神经元的真实值, Errj为第j个神经元计算后得到的误差。

Backpropagation的实例

然后手动实现BP神经网络

import numpy as np

class Function(object):
  '''
  程序中需要用到函数
  '''
  def tanh(self, x):
    return np.tanh(x)


  def tanh_deriv(self, x):
    return 1 - self.tanh(x) * self.tanh(x)


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


  def logistic_deriv(self, x):
    return self.logistic * (1 - self.logistic)


class NeuralNetwork(object):
  def __init__(self, layer, f, function='tanh'):
    if function == 'tanh':
      self.function = f.tanh
      self.function_deriv = f.tanh_deriv
    else:
      self.function = f.logistic
      self.function_deriv = f.logistic_deriv
    self.weights = []
    for i in range(1, len(layer) - 1):
      '''
      权重进行随机初始化
      '''
      self.weights.append((2 * (np.random.random((layer[i - 1] + 1, layer[i] + 1))) - 1) * 0.25)
      self.weights.append((2* np.random.random((layer[i] + 1, layer[i + 1])) - 1) * 0.25)

  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.function(np.dot(a, self.weights[l]))
    return a


  def fit(self, X, y, learn_rating=0.2, epochs=10000):
    X = np.atleast_2d(X)
    temp = np.ones([X.shape[0], X.shape[1] + 1])
    temp[:, 0:-1] = X
    X = temp
    y = np.array(y)
    for _ in range(epochs):
      i = np.random.randint(X.shape[0])
      o = [X[i]]
      for l in range(len(self.weights)):#正向传播
        o.append(self.function(np.dot(o[l], self.weights[l])))
      errors = [(y[i] - o[-1]) * self.function_deriv(o[-1])]
      for l in range(len(self.weights) - 1, 0, -1):#反向计算误差
        errors.append(errors[-1].dot(self.weights[l].T) * self.function_deriv(o[l]))
      errors.reverse()
      for l in range(len(self.weights)):#修改权重和偏移量
        layer = np.atleast_2d(o[l])
        error = np.atleast_2d(errors[l])
        self.weights[l] += learn_rating * layer.T.dot(error)

  

利用实现好的神经网络进行异或判断。

from bpnn import NeuralNetwork
from bpnn import Function
import numpy as np

nn = NeuralNetwork([2, 2, 1], Function(), '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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值