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将数组的元素导出到变量中(unpacking)
Oct 27 Python
python 创建弹出式菜单的实现代码
Jul 11 Python
Java及python正则表达式详解
Dec 27 Python
python3+PyQt5实现自定义流体混合窗口部件
Apr 24 Python
使用python爬取B站千万级数据
Jun 08 Python
详解python中init方法和随机数方法
Mar 13 Python
在linux下实现 python 监控usb设备信号
Jul 03 Python
如何通过python实现人脸识别验证
Jan 17 Python
Django Model中字段(field)的各种选项说明
May 19 Python
Python实现删除某列中含有空值的行的示例代码
Jul 20 Python
python 6种方法实现单例模式
Dec 15 Python
Python利用capstone实现反汇编
Apr 06 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 socket方式提交的post详解
2008/07/19 PHP
php数据结构与算法(PHP描述) 快速排序 quick sort
2012/06/21 PHP
php5.3中连接sqlserver2000的两种方法(com与ODBC)
2012/12/29 PHP
php下载远程大文件(获取远程文件大小)的实例
2017/06/17 PHP
PHP 实现人民币小写转换成大写的方法及大小写转换函数
2017/11/17 PHP
PHP连续签到功能实现方法详解
2019/12/04 PHP
javaScript 判断字符串是否为数字的简单方法
2009/07/25 Javascript
javascript中的=等号个数问题两个跟三个有什么区别
2013/10/23 Javascript
js显示文本框提示文字的方法
2015/05/07 Javascript
jquery实现平滑的二级下拉菜单效果
2015/08/26 Javascript
仅一个form表单 js实现注册信息依次填写提交功能
2016/06/12 Javascript
深入浅析JavaScript中的scrollTop
2016/07/11 Javascript
JS原型与原型链的深入理解
2017/02/15 Javascript
jQuery实现Select下拉列表进行状态选择功能
2017/03/30 jQuery
webstorm中配置Eslint的两种方式及差异比较详解
2018/10/19 Javascript
nodemon实现Typescript项目热更新的示例代码
2019/11/19 Javascript
[03:22]DSPL第一期精彩集锦:酷炫到底!
2014/11/07 DOTA
浅谈python为什么不需要三目运算符和switch
2016/06/17 Python
python 全文检索引擎详解
2017/04/25 Python
Python使用QRCode模块生成二维码实例详解
2017/06/14 Python
python构建基础的爬虫教学
2018/12/23 Python
妙用itchat! python实现久坐提醒功能
2019/11/25 Python
python tkinter的消息框模块(messagebox,simpledialog)
2020/11/07 Python
联想法国官方网站:Lenovo法国
2018/10/18 全球购物
东南亚排名第一的服务市场:kaodim
2019/03/28 全球购物
蒂娜商店:Tiina the Store
2019/12/07 全球购物
Java方面的关于数组和继承的笔面试题
2015/09/18 面试题
实习教师个人的自我评价
2013/11/08 职场文书
售后服务科岗位职责范文
2013/11/13 职场文书
2015年学校信息技术工作总结
2015/05/25 职场文书
初中英语教学随笔
2015/08/15 职场文书
《领导干部从政道德启示录》学习心得体会
2016/01/20 职场文书
CSS3常见动画的实现方式
2021/04/14 HTML / CSS
vue中利用mqtt服务端实现即时通讯的步骤记录
2021/07/01 Vue.js
十大经典日本动漫排行榜 海贼王第三,犬夜叉仅第八
2022/03/18 日漫
解决MySQL报“too many connections“错误
2022/04/19 MySQL