Python实现的径向基(RBF)神经网络示例


Posted in Python onFebruary 06, 2018

本文实例讲述了Python实现的径向基(RBF)神经网络。分享给大家供大家参考,具体如下:

from numpy import array, append, vstack, transpose, reshape, \
         dot, true_divide, mean, exp, sqrt, log, \
         loadtxt, savetxt, zeros, frombuffer
from numpy.linalg import norm, lstsq
from multiprocessing import Process, Array
from random import sample
from time import time
from sys import stdout
from ctypes import c_double
from h5py import File
def metrics(a, b):
  return norm(a - b)
def gaussian (x, mu, sigma):
  return exp(- metrics(mu, x)**2 / (2 * sigma**2))
def multiQuadric (x, mu, sigma):
  return pow(metrics(mu,x)**2 + sigma**2, 0.5)
def invMultiQuadric (x, mu, sigma):
  return pow(metrics(mu,x)**2 + sigma**2, -0.5)
def plateSpine (x,mu):
  r = metrics(mu,x)
  return (r**2) * log(r)
class Rbf:
  def __init__(self, prefix = 'rbf', workers = 4, extra_neurons = 0, from_files = None):
    self.prefix = prefix
    self.workers = workers
    self.extra_neurons = extra_neurons
    # Import partial model
    if from_files is not None:
      w_handle = self.w_handle = File(from_files['w'], 'r')
      mu_handle = self.mu_handle = File(from_files['mu'], 'r')
      sigma_handle = self.sigma_handle = File(from_files['sigma'], 'r')
      self.w = w_handle['w']
      self.mu = mu_handle['mu']
      self.sigmas = sigma_handle['sigmas']
      self.neurons = self.sigmas.shape[0]
  def _calculate_error(self, y):
    self.error = mean(abs(self.os - y))
    self.relative_error = true_divide(self.error, mean(y))
  def _generate_mu(self, x):
    n = self.n
    extra_neurons = self.extra_neurons
    # TODO: Make reusable
    mu_clusters = loadtxt('clusters100.txt', delimiter='\t')
    mu_indices = sample(range(n), extra_neurons)
    mu_new = x[mu_indices, :]
    mu = vstack((mu_clusters, mu_new))
    return mu
  def _calculate_sigmas(self):
    neurons = self.neurons
    mu = self.mu
    sigmas = zeros((neurons, ))
    for i in xrange(neurons):
      dists = [0 for _ in xrange(neurons)]
      for j in xrange(neurons):
        if i != j:
          dists[j] = metrics(mu[i], mu[j])
      sigmas[i] = mean(dists)* 2
           # max(dists) / sqrt(neurons * 2))
    return sigmas
  def _calculate_phi(self, x):
    C = self.workers
    neurons = self.neurons
    mu = self.mu
    sigmas = self.sigmas
    phi = self.phi = None
    n = self.n
    def heavy_lifting(c, phi):
      s = jobs[c][1] - jobs[c][0]
      for k, i in enumerate(xrange(jobs[c][0], jobs[c][1])):
        for j in xrange(neurons):
          # phi[i, j] = metrics(x[i,:], mu[j])**3)
          # phi[i, j] = plateSpine(x[i,:], mu[j]))
          # phi[i, j] = invMultiQuadric(x[i,:], mu[j], sigmas[j]))
          phi[i, j] = multiQuadric(x[i,:], mu[j], sigmas[j])
          # phi[i, j] = gaussian(x[i,:], mu[j], sigmas[j]))
        if k % 1000 == 0:
          percent = true_divide(k, s)*100
          print(c, ': {:2.2f}%'.format(percent))
      print(c, ': Done')
    # distributing the work between 4 workers
    shared_array = Array(c_double, n * neurons)
    phi = frombuffer(shared_array.get_obj())
    phi = phi.reshape((n, neurons))
    jobs = []
    workers = []
    p = n / C
    m = n % C
    for c in range(C):
      jobs.append((c*p, (c+1)*p + (m if c == C-1 else 0)))
      worker = Process(target = heavy_lifting, args = (c, phi))
      workers.append(worker)
      worker.start()
    for worker in workers:
      worker.join()
    return phi
  def _do_algebra(self, y):
    phi = self.phi
    w = lstsq(phi, y)[0]
    os = dot(w, transpose(phi))
    return w, os
    # Saving to HDF5
    os_h5 = os_handle.create_dataset('os', data = os)
  def train(self, x, y):
    self.n = x.shape[0]
    ## Initialize HDF5 caches
    prefix = self.prefix
    postfix = str(self.n) + '-' + str(self.extra_neurons) + '.hdf5'
    name_template = prefix + '-{}-' + postfix
    phi_handle = self.phi_handle = File(name_template.format('phi'), 'w')
    os_handle = self.w_handle = File(name_template.format('os'), 'w')
    w_handle = self.w_handle = File(name_template.format('w'), 'w')
    mu_handle = self.mu_handle = File(name_template.format('mu'), 'w')
    sigma_handle = self.sigma_handle = File(name_template.format('sigma'), 'w')
    ## Mu generation
    mu = self.mu = self._generate_mu(x)
    self.neurons = mu.shape[0]
    print('({} neurons)'.format(self.neurons))
    # Save to HDF5
    mu_h5 = mu_handle.create_dataset('mu', data = mu)
    ## Sigma calculation
    print('Calculating Sigma...')
    sigmas = self.sigmas = self._calculate_sigmas()
    # Save to HDF5
    sigmas_h5 = sigma_handle.create_dataset('sigmas', data = sigmas)
    print('Done')
    ## Phi calculation
    print('Calculating Phi...')
    phi = self.phi = self._calculate_phi(x)
    print('Done')
    # Saving to HDF5
    print('Serializing...')
    phi_h5 = phi_handle.create_dataset('phi', data = phi)
    del phi
    self.phi = phi_h5
    print('Done')
    ## Algebra
    print('Doing final algebra...')
    w, os = self.w, _ = self._do_algebra(y)
    # Saving to HDF5
    w_h5 = w_handle.create_dataset('w', data = w)
    os_h5 = os_handle.create_dataset('os', data = os)
    ## Calculate error
    self._calculate_error(y)
    print('Done')
  def predict(self, test_data):
    mu = self.mu = self.mu.value
    sigmas = self.sigmas = self.sigmas.value
    w = self.w = self.w.value
    print('Calculating phi for test data...')
    phi = self._calculate_phi(test_data)
    os = dot(w, transpose(phi))
    savetxt('iok3834.txt', os, delimiter='\n')
    return os
  @property
  def summary(self):
    return '\n'.join( \
      ['-----------------',
      'Training set size: {}'.format(self.n),
      'Hidden layer size: {}'.format(self.neurons),
      '-----------------',
      'Absolute error  : {:02.2f}'.format(self.error),
      'Relative error  : {:02.2f}%'.format(self.relative_error * 100)])
def predict(test_data):
  mu = File('rbf-mu-212243-2400.hdf5', 'r')['mu'].value
  sigmas = File('rbf-sigma-212243-2400.hdf5', 'r')['sigmas'].value
  w = File('rbf-w-212243-2400.hdf5', 'r')['w'].value
  n = test_data.shape[0]
  neur = mu.shape[0]
  mu = transpose(mu)
  mu.reshape((n, neur))
  phi = zeros((n, neur))
  for i in range(n):
    for j in range(neur):
      phi[i, j] = multiQuadric(test_data[i,:], mu[j], sigmas[j])
  os = dot(w, transpose(phi))
  savetxt('iok3834.txt', os, delimiter='\n')
  return os

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python中使用第三方库xlrd来写入Excel文件示例
Apr 05 Python
Python入门教程之if语句的用法
May 14 Python
python 判断是否为正小数和正整数的实例
Jul 23 Python
基于python select.select模块通信的实例讲解
Sep 21 Python
基于pycharm导入模块显示不存在的解决方法
Oct 13 Python
python构建基础的爬虫教学
Dec 23 Python
Python-ElasticSearch搜索查询的讲解
Feb 25 Python
python的mysql数据库建立表与插入数据操作示例
Sep 30 Python
python计算无向图节点度的实例代码
Nov 22 Python
Python使用Socket实现简单聊天程序
Feb 28 Python
Python 实现将numpy中的nan和inf,nan替换成对应的均值
Jun 08 Python
Python3爬虫中识别图形验证码的实例讲解
Jul 30 Python
python实现淘宝秒杀聚划算抢购自动提醒源码
Jun 23 #Python
初探TensorFLow从文件读取图片的四种方式
Feb 06 #Python
用十张图详解TensorFlow数据读取机制(附代码)
Feb 06 #Python
Python实现matplotlib显示中文的方法详解
Feb 06 #Python
Python实现自动上京东抢手机
Feb 06 #Python
Python获取指定文件夹下的文件名的方法
Feb 06 #Python
TensorFlow如何实现反向传播
Feb 06 #Python
You might like
php中使用$_REQUEST需要注意的一个问题
2013/05/02 PHP
ThinkPHP模板之变量输出、自定义函数与判断语句用法
2014/11/01 PHP
解决安装WampServer时提示缺少msvcr110.dll文件的问题
2017/07/09 PHP
jquery select操作的日期联动实现代码
2009/12/06 Javascript
jquery 使用点滴函数代码
2011/05/20 Javascript
网页前端优化之滚动延时加载图片示例
2013/07/13 Javascript
jquery插件jquery倒计时插件分享
2013/12/27 Javascript
javascript中定义私有方法说明(private method)
2014/01/27 Javascript
DOM基础教程之使用DOM + Css
2015/01/20 Javascript
jquery实现网页的页面平滑滚动效果代码
2015/11/02 Javascript
javascript实现下拉提示选择框
2015/12/29 Javascript
浅谈React 属性和状态的一些总结
2016/11/21 Javascript
URL中“#” “?” &“”号的作用浅析
2017/02/04 Javascript
JavaScript实现二维坐标点排序效果
2017/07/18 Javascript
angular中的cookie读写方法
2017/08/02 Javascript
js时间戳与日期格式之间相互转换
2017/12/11 Javascript
微信小程序分享功能之按钮button 边框隐藏和点击隐藏
2018/06/14 Javascript
cocos2dx+lua实现橡皮擦功能
2018/12/20 Javascript
如何在Vue中抽离接口配置文件
2019/10/31 Javascript
JS实现页面数据懒加载
2020/02/13 Javascript
同时安装Python2 & Python3 cmd下版本自由选择的方法
2017/12/09 Python
详解windows python3.7安装numpy问题的解决方法
2018/08/13 Python
解决python中画图时x,y轴名称出现中文乱码的问题
2019/01/29 Python
Django获取该数据的上一条和下一条方法
2019/08/12 Python
python GUI库图形界面开发之PyQt5中QMainWindow, QWidget以及QDialog的区别和选择
2020/02/26 Python
jupyter notebook 添加kernel permission denied的操作
2020/04/21 Python
法国在线宠物店:zooplus.fr
2018/02/23 全球购物
庆元旦广播稿
2014/02/10 职场文书
3的组成教学反思
2014/04/30 职场文书
团代会宣传工作方案
2014/05/08 职场文书
民族团结演讲稿范文
2014/08/27 职场文书
关于读书的演讲稿600字
2014/08/27 职场文书
自我查摆剖析材料
2014/10/11 职场文书
第28个世界无烟日活动总结
2015/02/10 职场文书
运动会开幕式新闻稿
2015/07/17 职场文书
virtualenv隔离Python环境的问题解析
2022/06/21 Python