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

 更新时间:2020年10月15日 10:08:50   作者:农大鲁迅  
这篇文章主要介绍了如何用Python 实现全连接神经网络(Multi-layer Perceptron),帮助大家更好的进行机器学习,感兴趣的朋友可以了解下

代码

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')

效果

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

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

相关文章

  • Python 序列化和反序列化库 MarshMallow 的用法实例代码

    Python 序列化和反序列化库 MarshMallow 的用法实例代码

    marshmallow(Object serialization and deserialization, lightweight and fluffy.)用于对对象进行序列化和反序列化,并同步进行数据验证。这篇文章主要介绍了Python 序列化和反序列化库 MarshMallow 的用法实例代码,需要的朋友可以参考下
    2020-02-02
  • Win10搭建Pyspark2.4.4+Pycharm开发环境的图文教程(亲测)

    Win10搭建Pyspark2.4.4+Pycharm开发环境的图文教程(亲测)

    本文主要介绍了Win10搭建Pyspark2.4.4+Pycharm开发环境的图文教程(亲测),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-02-02
  • python3 tkinter实现添加图片和文本

    python3 tkinter实现添加图片和文本

    这篇文章主要为大家详细介绍了python3 tkinter实现添加图片和文本,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-11-11
  • Django项目中包含多个应用时对url的配置方法

    Django项目中包含多个应用时对url的配置方法

    今天小编就为大家分享一篇Django项目中包含多个应用时对url的配置方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • Python jpg快速转png并调整大小方式

    Python jpg快速转png并调整大小方式

    这篇文章主要介绍了Python实现jpg快速转png并调整大小方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Python基于LightGBM进行时间序列预测

    Python基于LightGBM进行时间序列预测

    LightGBM是扩展机器学习系统。是一款基于GBDT(梯度提升决策树)算法的分布梯度提升框架。其设计思路主要集中在减少数据对内存与计算性能的使用上,以及减少多机器并行计算时的通讯代价。本文将通过LightGBM进行时间序列预测,感兴趣的可以了解一下
    2022-03-03
  • python中如何使用正则表达式的集合字符示例

    python中如何使用正则表达式的集合字符示例

    我们都知道,正则表达式可以很方便地对字符串进行匹配、查找、分割等操作,下面这篇文章主要给大家介绍了关于python中如何使用正则表达式的集合字符的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下。
    2017-10-10
  • python config文件的读写操作示例

    python config文件的读写操作示例

    这篇文章主要介绍了python config文件的读写操作,结合简单示例形式分析了Python针对config文件的设置、读取、写入相关操作技巧,需要的朋友可以参考下
    2019-09-09
  • Python3实现爬取简书首页文章标题和文章链接的方法【测试可用】

    Python3实现爬取简书首页文章标题和文章链接的方法【测试可用】

    这篇文章主要介绍了Python3实现爬取简书首页文章标题和文章链接的方法,结合实例形式分析了Python3基于urllib及bs4库针对简书网进行文章抓取相关操作技巧,需要的朋友可以参考下
    2018-12-12
  • python制作抽奖程序代码详解

    python制作抽奖程序代码详解

    在本篇内容里小编给大家整理了一篇关于python制作抽奖程序代码详解内容,需要的朋友们可以参考下。
    2021-01-01

最新评论