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 相关文章推荐
Flask入门教程实例:搭建一个静态博客
Mar 27 Python
Python编程中实现迭代器的一些技巧小结
Jun 21 Python
Python使用Srapy框架爬虫模拟登陆并抓取知乎内容
Jul 02 Python
tensorflow学习笔记之简单的神经网络训练和测试
Apr 15 Python
python抓取京东小米8手机配置信息
Nov 13 Python
Django组件content-type使用方法详解
Jul 19 Python
利用ImageAI库只需几行python代码实现目标检测
Aug 09 Python
如何在VSCode上轻松舒适的配置Python的方法步骤
Oct 28 Python
django数据模型(Model)的字段类型解析
Dec 25 Python
Python3.9 beta2版本发布了,看看这7个新的PEP都是什么
Jun 10 Python
什么是python类属性
Jun 10 Python
python 基于UDP协议套接字通信的实现
Jan 22 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(3)
2006/10/09 PHP
php下将XML转换为数组
2010/01/01 PHP
PHP显示今天、今月、上月、今年的起点/终点时间戳的代码
2011/05/25 PHP
php实现在服务器上创建目录的方法
2015/03/16 PHP
[原创]php常用字符串输出方法分析(echo,print,printf及sprintf)
2016/07/09 PHP
Jquery升级新版本后选择器的语法问题
2010/06/02 Javascript
jquery.cvtooltip.js 基于jquery的气泡提示插件
2010/11/19 Javascript
页面实时更新时间的JS实例代码
2013/12/18 Javascript
JavaScript中实现最高效的数组乱序方法
2014/10/11 Javascript
javascript实现简单的省市区三级联动
2015/05/14 Javascript
JavaScript事件类型中UI事件详解
2016/01/14 Javascript
Angularjs实现多图片上传预览功能
2018/07/18 Javascript
解决bootstrap中下拉菜单点击后不关闭的问题
2018/08/10 Javascript
Js跳出两级循环方法代码实例
2020/09/22 Javascript
[31:00]2014 DOTA2华西杯精英邀请赛5 24 NewBee VS iG
2014/05/25 DOTA
Python内置的HTTP协议服务器SimpleHTTPServer使用指南
2016/03/30 Python
python 2.7.14安装图文教程
2018/04/08 Python
wxpython多线程防假死与线程间传递消息实例详解
2019/12/13 Python
Django choices下拉列表绑定实例
2020/03/13 Python
pytorch 计算ConvTranspose1d输出特征大小方式
2020/06/23 Python
pycharm 使用tab跳出正在编辑的括号(){}{}等问题
2021/02/26 Python
使用CSS3编写类似iOS中的复选框及带开关的按钮
2016/04/11 HTML / CSS
Application Cache未缓存文件无法访问无法加载问题
2014/05/31 HTML / CSS
FILA斐乐中国官方商城:意大利运动品牌
2017/01/25 全球购物
英国手工制作的现代与经典的沙发和床:Love Your Home
2020/09/26 全球购物
活动邀请函范文
2014/01/19 职场文书
班级德育工作实施方案
2014/02/21 职场文书
篝火晚会策划方案
2014/05/16 职场文书
迁户口计划生育证明
2014/10/19 职场文书
酒店工程部岗位职责
2015/02/12 职场文书
2015年家长学校工作总结
2015/04/22 职场文书
2015教师个人德育工作总结
2015/07/22 职场文书
2016教师学习党章心得体会
2016/01/15 职场文书
安全责任协议书范本
2016/03/23 职场文书
Nginx解决403 forbidden的完整步骤
2021/04/01 Servers
python字符串的一些常见实用操作
2022/04/06 Python