国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

神經網絡(BP)算法Python實現及應用

2020-02-22 23:40:18
字體:
來源:轉載
供稿:網友

本文實例為大家分享了Python實現神經網絡算法及應用的具體代碼,供大家參考,具體內容如下

首先用Python實現簡單地神經網絡算法:

import numpy as np# 定義tanh函數def tanh(x):  return np.tanh(x)# tanh函數的導數def tan_deriv(x):  return 1.0 - np.tanh(x) * np.tan(x)# sigmoid函數def logistic(x):  return 1 / (1 + np.exp(-x))# sigmoid函數的導數def logistic_derivative(x):  return logistic(x) * (1 - logistic(x))class NeuralNetwork:  def __init__(self, layers, activation='tanh'):    """    神經網絡算法構造函數    :param layers: 神經元層數    :param activation: 使用的函數(默認tanh函數)    :return:none    """    if activation == 'logistic':      self.activation = logistic      self.activation_deriv = logistic_derivative    elif activation == 'tanh':      self.activation = tanh      self.activation_deriv = tan_deriv    # 權重列表    self.weights = []    # 初始化權重(隨機)    for i in range(1, len(layers) - 1):      self.weights.append((2 * np.random.random((layers[i - 1] + 1, layers[i] + 1)) - 1) * 0.25)      self.weights.append((2 * np.random.random((layers[i] + 1, layers[i + 1])) - 1) * 0.25)  def fit(self, X, y, learning_rate=0.2, epochs=10000):    """    訓練神經網絡    :param X: 數據集(通常是二維)    :param y: 分類標記    :param learning_rate: 學習率(默認0.2)    :param epochs: 訓練次數(最大循環次數,默認10000)    :return: none    """    # 確保數據集是二維的    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 k in range(epochs):      # 隨機抽取X的一行      i = np.random.randint(X.shape[0])      # 用隨機抽取的這一組數據對神經網絡更新      a = [X[i]]      # 正向更新      for l in range(len(self.weights)):        a.append(self.activation(np.dot(a[l], self.weights[l])))      error = y[i] - a[-1]      deltas = [error * self.activation_deriv(a[-1])]      # 反向更新      for l in range(len(a) - 2, 0, -1):        deltas.append(deltas[-1].dot(self.weights[l].T) * self.activation_deriv(a[l]))        deltas.reverse()      for i in range(len(self.weights)):        layer = np.atleast_2d(a[i])        delta = np.atleast_2d(deltas[i])        self.weights[i] += learning_rate * layer.T.dot(delta)  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.activation(np.dot(a, self.weights[l]))    return a

使用自己定義的神經網絡算法實現一些簡單的功能:

 小案例:

X:                  Y
0 0                 0
0 1                 1

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 女性| 武强县| 沂水县| 罗源县| 深泽县| 鲁甸县| 南川市| 定兴县| 公安县| 甘肃省| 探索| 南开区| 安庆市| 石台县| 潜江市| 襄樊市| 宁河县| 龙山县| 东平县| 保定市| 靖边县| 莱西市| 墨玉县| 焉耆| 县级市| 淮南市| 宁国市| 苍山县| 诏安县| 惠水县| 西和县| 平邑县| 遂平县| 昔阳县| 阿图什市| 五指山市| 望城县| 济宁市| 齐齐哈尔市| 广昌县| 灌南县|