如何用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 从远程服务器下载日志文件的程序
Feb 10 Python
使用python 获取进程pid号的方法
Mar 10 Python
Python类的用法实例浅析
May 27 Python
Pycharm学习教程(3) 代码运行调试
May 03 Python
Django实现简单分页功能的方法详解
Dec 05 Python
对python opencv 添加文字 cv2.putText 的各参数介绍
Dec 05 Python
python批量图片处理简单示例
Aug 06 Python
python数组循环处理方法
Aug 26 Python
Python实现多线程/多进程的TCP服务器
Sep 03 Python
解决Python3.8用pip安装turtle-0.0.2出现错误问题
Feb 11 Python
python矩阵运算,转置,逆运算,共轭矩阵实例
May 11 Python
Pycharm添加虚拟解释器报错问题解决方案
Oct 13 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
浅析ThinkPHP中的pathinfo模式和URL重写
2014/01/06 PHP
PHP 匿名函数与注意事项详细介绍
2016/11/26 PHP
用js实现下载远程文件并保存在本地的脚本
2008/05/06 Javascript
input+select(multiple) 实现下拉框输入值
2009/05/21 Javascript
JS 获取span标签中的值的代码 支持ie与firefox
2009/08/24 Javascript
Jquery截取中文字符串的实现代码
2010/12/22 Javascript
jquery清空textarea等输入框实现代码
2013/04/22 Javascript
jquery ajax 简单范例(界面+后台)
2013/11/19 Javascript
jQuery异步验证用户名是否存在示例代码
2014/05/21 Javascript
BootStrap实现树形目录组件代码详解
2016/06/21 Javascript
JavaScript 限制文本框不可输入英文单双引号的方法
2016/12/20 Javascript
JS闭包与延迟求值用法示例
2016/12/22 Javascript
Bootstrap3 内联单选和多选框
2016/12/29 Javascript
easyui-datagrid特殊字符不能显示的处理方法
2017/04/12 Javascript
实现图片首尾平滑轮播(JS原生方法—节流)
2017/10/17 Javascript
JS排序算法之希尔排序与快速排序实现方法
2017/12/12 Javascript
使用JS代码实现俄罗斯方块游戏
2018/08/03 Javascript
ionic+html5+API实现双击返回键退出应用
2019/09/17 Javascript
Node.js 在本地生成日志文件的方法
2020/02/07 Javascript
[01:01:36]Optic vs paiN 2018国际邀请赛小组赛BO2 第一场 8.19
2018/08/21 DOTA
python3+PyQt5实现自定义流体混合窗口部件
2018/04/24 Python
python切片的步进、添加、连接简单操作示例
2019/07/11 Python
关于阿里云oss获取sts凭证 app直传 python的实例
2019/08/20 Python
Python 实现将数组/矩阵转换成Image类
2020/01/09 Python
Python如何在DataFrame增加数值
2020/02/14 Python
Python读取Excel数据并生成图表过程解析
2020/06/18 Python
完美解决TensorFlow和Keras大数据量内存溢出的问题
2020/07/03 Python
Python 通过爬虫实现GitHub网页的模拟登录的示例代码
2020/08/17 Python
Python基于pillow库实现生成图片水印
2020/09/14 Python
体育纪念品、亲笔签名的体育收藏品:Steiner Sports
2020/07/31 全球购物
品管员岗位职责
2013/11/10 职场文书
小学生期末自我鉴定
2014/01/19 职场文书
聚美优品励志广告词
2014/03/14 职场文书
工作评语大全
2014/04/26 职场文书
授权委托书(完整版)
2014/09/10 职场文书
Python基础之元类详解
2021/04/29 Python