如何用Python 实现全连接神经网络(Multi-layer Perceptron)


Posted in Python onOctober 15, 2020

代码

import numpy as np

# 各种激活函数及导数
def sigmoid(x):
  return 1 / (1 + np.exp(-x))


def dsigmoid(y):
  return y * (1 - y)


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


def dtanh(y):
  return 1.0 - y ** 2


def relu(y):
  tmp = y.copy()
  tmp[tmp < 0] = 0
  return tmp


def drelu(x):
  tmp = x.copy()
  tmp[tmp >= 0] = 1
  tmp[tmp < 0] = 0
  return tmp


class MLPClassifier(object):
  """多层感知机,BP 算法训练"""

  def __init__(self,
         layers,
         activation='tanh',
         epochs=20, batch_size=1, learning_rate=0.01):
    """
    :param layers: 网络层结构
    :param activation: 激活函数
    :param epochs: 迭代轮次
    :param learning_rate: 学习率 
    """
    self.epochs = epochs
    self.learning_rate = learning_rate
    self.layers = []
    self.weights = []
    self.batch_size = batch_size

    for i in range(0, len(layers) - 1):
      weight = np.random.random((layers[i], layers[i + 1]))
      layer = np.ones(layers[i])
      self.layers.append(layer)
      self.weights.append(weight)
    self.layers.append(np.ones(layers[-1]))

    self.thresholds = []
    for i in range(1, len(layers)):
      threshold = np.random.random(layers[i])
      self.thresholds.append(threshold)

    if activation == 'tanh':
      self.activation = tanh
      self.dactivation = dtanh
    elif activation == 'sigomid':
      self.activation = sigmoid
      self.dactivation = dsigmoid
    elif activation == 'relu':
      self.activation = relu
      self.dactivation = drelu

  def fit(self, X, y):
    """
    :param X_: shape = [n_samples, n_features] 
    :param y: shape = [n_samples] 
    :return: self
    """
    for _ in range(self.epochs * (X.shape[0] // self.batch_size)):
      i = np.random.choice(X.shape[0], self.batch_size)
      # i = np.random.randint(X.shape[0])
      self.update(X[i])
      self.back_propagate(y[i])

  def predict(self, X):
    """
    :param X: shape = [n_samples, n_features] 
    :return: shape = [n_samples]
    """
    self.update(X)
    return self.layers[-1].copy()

  def update(self, inputs):
    self.layers[0] = inputs
    for i in range(len(self.weights)):
      next_layer_in = self.layers[i] @ self.weights[i] - self.thresholds[i]
      self.layers[i + 1] = self.activation(next_layer_in)

  def back_propagate(self, y):
    errors = y - self.layers[-1]

    gradients = [(self.dactivation(self.layers[-1]) * errors).sum(axis=0)]

    self.thresholds[-1] -= self.learning_rate * gradients[-1]
    for i in range(len(self.weights) - 1, 0, -1):
      tmp = np.sum(gradients[-1] @ self.weights[i].T * self.dactivation(self.layers[i]), axis=0)
      gradients.append(tmp)
      self.thresholds[i - 1] -= self.learning_rate * gradients[-1] / self.batch_size
    gradients.reverse()
    for i in range(len(self.weights)):
      tmp = np.mean(self.layers[i], axis=0)
      self.weights[i] += self.learning_rate * tmp.reshape((-1, 1)) * gradients[i]

测试代码

import sklearn.datasets
import numpy as np

def plot_decision_boundary(pred_func, X, y, title=None):
  """分类器画图函数,可画出样本点和决策边界
  :param pred_func: predict函数
  :param X: 训练集X
  :param y: 训练集Y
  :return: None
  """

  # Set min and max values and give it some padding
  x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
  y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
  h = 0.01
  # Generate a grid of points with distance h between them
  xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
  # Predict the function value for the whole gid
  Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
  Z = Z.reshape(xx.shape)
  # Plot the contour and training examples
  plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
  plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral)

  if title:
    plt.title(title)
  plt.show()


def test_mlp():
  X, y = sklearn.datasets.make_moons(200, noise=0.20)
  y = y.reshape((-1, 1))
  n = MLPClassifier((2, 3, 1), activation='tanh', epochs=300, learning_rate=0.01)
  n.fit(X, y)
  def tmp(X):
    sign = np.vectorize(lambda x: 1 if x >= 0.5 else 0)
    ans = sign(n.predict(X))
    return ans

  plot_decision_boundary(tmp, X, y, 'Neural Network')

效果

如何用Python 实现全连接神经网络(Multi-layer Perceptron)

如何用Python 实现全连接神经网络(Multi-layer Perceptron)

更多机器学习代码,请访问 https://github.com/WiseDoge/plume

以上就是如何用Python 实现全连接神经网络(Multi-layer Perceptron)的详细内容,更多关于Python 实现全连接神经网络的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python创建临时文件夹的方法
Jul 06 Python
12步教你理解Python装饰器
Feb 25 Python
TensorFlow变量管理详解
Mar 10 Python
实例分析python3实现并发访问水平切分表
Sep 29 Python
pandas中DataFrame修改index、columns名的方法示例
Aug 02 Python
Python pandas自定义函数的使用方法示例
Nov 20 Python
django配置app中的静态文件步骤
Mar 27 Python
详解python logging日志传输
Jul 01 Python
python 使用递归的方式实现语义图片分割功能
Jul 16 Python
Python调用ffmpeg开源视频处理库,批量处理视频
Nov 16 Python
浅谈Python类的单继承相关知识
May 12 Python
python自动计算图像数据集的RGB均值
Jun 18 Python
python 实现非极大值抑制算法(Non-maximum suppression, NMS)
Oct 15 #Python
解决pip安装的第三方包在PyCharm无法导入的问题
Oct 15 #Python
python实现粒子群算法
Oct 15 #Python
如何将anaconda安装配置的mmdetection环境离线拷贝到另一台电脑
Oct 15 #Python
Python3.7安装PyQt5 运行配置Pycharm的详细教程
Oct 15 #Python
python利用faker库批量生成测试数据
Oct 15 #Python
如何利用python检测图片是否包含二维码
Oct 15 #Python
You might like
php设计模式 Command(命令模式)
2011/06/26 PHP
利用curl抓取远程页面内容的示例代码
2013/07/23 PHP
php读取富文本的时p标签会出现红线是怎么回事
2014/05/13 PHP
PHP网页游戏学习之Xnova(ogame)源码解读(一)
2014/06/23 PHP
php中FTP函数ftp_connect、ftp_login与ftp_chmod用法
2014/11/18 PHP
js 全兼容可高亮二级缓冲折叠菜单
2010/06/04 Javascript
瀑布流布局并自动加载实现代码
2013/03/12 Javascript
简述JavaScript对传统文档对象模型的支持
2015/06/16 Javascript
阿里巴巴技术文章分享 Javascript继承机制的实现
2016/01/14 Javascript
JQuery解析XML的方法小结
2016/04/02 Javascript
jQuery实现表格行和列的动态添加与删除方法【测试可用】
2016/08/01 Javascript
JavaScript中setTimeout的那些事儿
2016/11/14 Javascript
nodejs的压缩文件模块archiver用法示例
2017/01/18 NodeJs
React Native实现地址挑选器功能
2017/10/24 Javascript
基于模板引擎Jade的应用(详解)
2017/12/12 Javascript
React组件中的this的具体使用
2018/02/28 Javascript
jquery 实现拖动文件上传加载进度条功能
2018/03/18 jQuery
深入浅析Vue.js中 computed和methods不同机制
2018/03/22 Javascript
用JS实现根据当前时间随机生成流水号或者订单号
2018/05/31 Javascript
webpack4 入门最简单的例子介绍
2018/09/05 Javascript
Echart折线图手柄触发事件示例详解
2018/12/16 Javascript
layui的layedit富文本赋值方法
2019/09/18 Javascript
详解VUE中的插值( Interpolation)语法
2020/10/18 Javascript
python 文件操作api(文件操作函数)
2016/08/28 Python
降低python版本的操作方法
2020/09/11 Python
python中scipy.stats产生随机数实例讲解
2021/02/19 Python
医学专业毕业生推荐信
2013/11/14 职场文书
拾金不昧的表扬信
2014/01/16 职场文书
服务生自我鉴定
2014/01/22 职场文书
中学生自我评价范文
2014/02/08 职场文书
党员教师一句话承诺
2014/05/30 职场文书
平安家庭示范户事迹
2014/06/02 职场文书
建筑结构施工求职信
2014/07/11 职场文书
见习报告的格式
2014/11/04 职场文书
建筑工程材料员岗位职责
2015/04/11 职场文书
2016年学校“6﹒26国际禁毒日”宣传活动总结
2016/04/05 职场文书