最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何用Python 實現(xiàn)全連接神經(jīng)網(wǎng)絡(luò)(Multi-layer Perceptron)

 更新時間:2020年10月15日 10:08:50   作者:農(nóng)大魯迅  
這篇文章主要介紹了如何用Python 實現(xiàn)全連接神經(jīng)網(wǎng)絡(luò)(Multi-layer Perceptron),幫助大家更好的進(jìn)行機(jī)器學(xué)習(xí),感興趣的朋友可以了解下

代碼

import numpy as np

# 各種激活函數(shù)及導(dǎo)數(shù)
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):
  """多層感知機(jī),BP 算法訓(xùn)練"""

  def __init__(self,
         layers,
         activation='tanh',
         epochs=20, batch_size=1, learning_rate=0.01):
    """
    :param layers: 網(wǎng)絡(luò)層結(jié)構(gòu)
    :param activation: 激活函數(shù)
    :param epochs: 迭代輪次
    :param learning_rate: 學(xué)習(xí)率 
    """
    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):
  """分類器畫圖函數(shù),可畫出樣本點(diǎn)和決策邊界
  :param pred_func: predict函數(shù)
  :param X: 訓(xùn)練集X
  :param y: 訓(xùn)練集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')

效果

更多機(jī)器學(xué)習(xí)代碼,請訪問 https://github.com/WiseDoge/plume

以上就是如何用Python 實現(xiàn)全連接神經(jīng)網(wǎng)絡(luò)(Multi-layer Perceptron)的詳細(xì)內(nèi)容,更多關(guān)于Python 實現(xiàn)全連接神經(jīng)網(wǎng)絡(luò)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python中安裝庫的常用方法介紹

    Python中安裝庫的常用方法介紹

    大家好,本篇文章主要講的是Python中安裝庫的常用方法介紹,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2022-01-01
  • Python對象中__del__方法起作用的條件詳解

    Python對象中__del__方法起作用的條件詳解

    今天小編就為大家分享一篇Python對象中__del__方法起作用的條件詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • 在Linux下調(diào)試Python代碼的各種方法

    在Linux下調(diào)試Python代碼的各種方法

    這篇文章主要介紹了在Linux下調(diào)試Python代碼的各種方法,用于編程后的debug工作,需要的朋友可以參考下
    2015-04-04
  • python jieba庫的基本使用

    python jieba庫的基本使用

    這篇文章主要介紹了python jieba庫的基本使用,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-03-03
  • Python閉包思想與用法淺析

    Python閉包思想與用法淺析

    這篇文章主要介紹了Python閉包思想與用法,結(jié)合實例形式簡單分析了Python閉包的概念、原理、使用方法與相關(guān)操作注意事項,需要的朋友可以參考下
    2018-12-12
  • django實現(xiàn)更改數(shù)據(jù)庫某個字段以及字段段內(nèi)數(shù)據(jù)

    django實現(xiàn)更改數(shù)據(jù)庫某個字段以及字段段內(nèi)數(shù)據(jù)

    這篇文章主要介紹了django實現(xiàn)更改數(shù)據(jù)庫某個字段以及字段段內(nèi)數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • django實現(xiàn)同一個ip十分鐘內(nèi)只能注冊一次的實例

    django實現(xiàn)同一個ip十分鐘內(nèi)只能注冊一次的實例

    下面小編就為大家?guī)硪黄猟jango實現(xiàn)同一個ip十分鐘內(nèi)只能注冊一次的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-11-11
  • Pytorch閱讀文檔中的flatten函數(shù)

    Pytorch閱讀文檔中的flatten函數(shù)

    PyTorch提供了一個非常方便的函數(shù)flatten()來完成這個任務(wù),本文將介紹Pytorch閱讀文檔中的flatten函數(shù),并提供一些示例代碼,感興趣的朋友一起看看吧
    2023-11-11
  • python中httpx庫的詳細(xì)使用方法及案例詳解

    python中httpx庫的詳細(xì)使用方法及案例詳解

    httpx 是一個現(xiàn)代化的 Python HTTP 客戶端庫,支持同步和異步請求,功能強(qiáng)大且易于使用,它比 requests 更高效,支持 HTTP/2 和異步操作,以下是 httpx 的詳細(xì)使用方法,感興趣的小伙伴跟著小編一起來看看吧
    2025-02-02
  • 給我一面國旗 python幫你實現(xiàn)

    給我一面國旗 python幫你實現(xiàn)

    這篇文章主要為大家詳細(xì)介紹了Python之給我一面國旗的實現(xiàn)代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-09-09

最新評論

永和县| 新巴尔虎右旗| 宁津县| 兴隆县| 且末县| 汾西县| 富阳市| 平和县| 三门峡市| 隆德县| 永靖县| 财经| 深泽县| 东辽县| 额济纳旗| 大埔县| 孟津县| 常州市| 彩票| 酒泉市| 曲阜市| 平阴县| 黄浦区| 白城市| 和田县| 南靖县| 西城区| 定边县| 广德县| 盐池县| 徐汇区| 潼南县| 鄂托克旗| 略阳县| 江阴市| 屯昌县| 牙克石市| 鲁甸县| 塘沽区| 都昌县| 个旧市|