微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在python中实现基于FFT的基于FFT的核密度估计器,并将其与SciPy实现进行比较

我需要代码来做二维核密度估计(KDE),我发现SciPy实现太慢了.所以,我已经编写了一个基于FFT的实现,但有些事情让我很困惑. (FFT实现还强制执行周期性边界条件,这就是我想要的.)

该实现基于从样本创建简单的直方图,然后使用高斯进行卷积.这是执行此操作的代码,并将其与SciPy结果进行比较.

from numpy import *
from scipy.stats import *
from numpy.fft import *
from matplotlib.pyplot import *
from time import clock

ion()

#ParaMETERS
N   = 512   #number of histogram bins; want 2^n for maximum FFT speed?
nSamp   = 1000  #number of samples if using the ranom variable
h   = 0.1   #width of gaussian
wh  = 1.0   #width and height of square domain

#VARIABLES FROM ParaMETERS
rv  = uniform(loc=-wh,scale=2*wh)   #random variable that can generate samples
xyBnds  = linspace(-1.0,1.0,N+1)  #boundaries of histogram bins
xy  = (xyBnds[1:] + xyBnds[:-1])/2      #centers of histogram bins
xx,yy = meshgrid(xy,xy)

#DEFINE SAMPLES,TWO OPTIONS
#samples = rv.rvs(size=(nSamp,2))
samples = array([[0.5,0.5],[0.2,0.2]])

#DEFinitioNS FOR FFT IMPLEMENTATION
ker = exp(-(xx**2 + yy**2)/2/h**2)/h/sqrt(2*pi) #Gaussian kernel
fKer = fft2(ker) #DFT of kernel

#FFT IMPLEMENTATION
stime = clock()
#generate normalized histogram. Note sure why .T is needed:
hst = histogram2d(samples[:,0],samples[:,1],bins=xyBnds)[0].T / (xy[-1] - xy[0])**2
#convolve histogram with kernel. Not sure why fftshift is neeed:
KDE1 = fftshift(ifft2(fft2(hst)*fKer))/N
etime = clock()
print "FFT method time:",etime - stime

#DEFinitioNS FOR NON-FFT IMPLEMTATION FROM SCIPY
#points to sample the KDE at,in a form gaussian_kde likes:
grid_coords = append(xx.reshape(-1,1),yy.reshape(-1,axis=1)

#NON-FFT IMPLEMTATION FROM SCIPY
stime = clock()
KDEfn = gaussian_kde(samples.T,bw_method=h)
KDE2 = KDEfn(grid_coords.T).reshape((N,N))
etime = clock()
print "SciPy time:",etime - stime

#PLOT FFT IMPLEMENTATION RESULTS
fig = figure()
ax = fig.add_subplot(111,aspect='equal')
c = contour(xy,xy,KDE1.real)
clabel(c)
title("FFT Implementation Results")

#PRINT SCIPY IMPLEMENTATION RESULTS
fig = figure()
ax = fig.add_subplot(111,KDE2)
clabel(c)
title("SciPy Implementation Results")

上面有两组样本. 1000个随机点用于基准测试并被注释掉;这三点是用于调试的.

后一种情况的结果图是在这文章的最后.

这是我的问题:

>我可以避免直方图的.T和KDE1的fftshift吗?我不确定他们为什么需要它们,但是如果没有它们,高斯人就会出现在错误的地方.
>如何为SciPy定义标量带宽?高斯在两种实现中具有不同的宽度.
>沿着同样的路线,为什么SciPy实现中的高斯不是径向对称的,即使我给了gaussian_kde一个标量带宽?
>我如何实现SciPy中可用于FFT代码的其他带宽方法

(请注意,在1000个随机点的情况下,FFT代码比SciPy代码快〜390倍.)

最佳答案
正如您已经注意到的那样,您所看到的差异是由带宽和缩放因素造成的.

认情况下,如果您对细节感到好奇,gaussian_kde会使用Scott’s rule. Dig into the code选择带宽.下面的代码片段是从我写的quite awhile ago to do something similar到你正在做的事情. (如果我没记错的话,那个特定版本有一个明显的错误,它确实不应该使用scipy.signal进行卷积,但带宽估计​​和规范化是正确的.)

# Calculate the covariance matrix (in pixel coords)
cov = np.cov(xyi)

# Scaling factor for bandwidth
scotts_factor = np.power(n,-1.0 / 6) # For 2D

#---- Make the gaussian kernel -------------------------------------------

# First,determine how big the gridded kernel needs to be (2 stdev radius) 
# (do we need to convolve with a 5x5 array or a 100x100 array?)
std_devs = np.diag(np.sqrt(cov))
kern_nx,kern_ny = np.round(scotts_factor * 2 * np.pi * std_devs)

# Determine the bandwidth to use for the gaussian kernel
inv_cov = np.linalg.inv(cov * scotts_factor**2) 

卷积后,网格然后被标准化:

# normalization factor to divide result by so that units are in the same
# units as scipy.stats.kde.gaussian_kde's output.  (Sums to 1 over infinity)
norm_factor = 2 * np.pi * cov * scotts_factor**2
norm_factor = np.linalg.det(norm_factor)
norm_factor = n * dx * dy * np.sqrt(norm_factor)

# normalize the result
grid /= norm_factor

希望这有助于澄清一些事情.

至于你的其他问题:

Can I avoid the .T for the histogram and the fftshift for KDE1? I’m
not sure why they’re needed,but the gaussians show up in the wrong
places without them.

我可能会误读你的代码,但我认为你只是有转置因为你从点坐标到索引坐标(即从< x,y>到< y,x>).

Along the same lines,why are the gaussians in the SciPy
implementation not radially symmetric even though I gave gaussian_kde
a scalar bandwidth?

这是因为scipy使用输入x,y点的完全协方差矩阵来确定高斯核.您的公式假定x和y不相关. gaussian_kde测试并使用结果中x和y之间的相关性.

How Could I implement the other bandwidth methods available in SciPy
for the FFT code?

我会留下那个让你弄明白的. :)但这并不难.基本上,你不是改变scotts_factor,而是改变公式,并有一些其他的标量因子.其他一切都是一样的.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


我最近重新拾起了计算机视觉,借助Python的opencv还有face_recognition库写了个简单的图像识别demo,额外定制了一些内容,原本想打包成exe然后发给朋友,不过在这当中遇到了许多小问题,都解决了,记录一下踩过的坑。 1、Pyinstaller打包过程当中出现warning,跟d
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Pooling在中文当中的意思是“池化”,在神经网络当中非常常见,通常用的比较多的一种是Max Pooling,具体操作如下图: 结合图像理解,相信你也会大概明白其中的本意。不过Pooling并不是只可以选取2x2的窗口大小,即便是3x3,
记得大一学Python的时候,有一个题目是判断一个数是否是复数。当时觉得比较复杂不好写,就琢磨了一个偷懒的好办法,用异常处理的手段便可以大大程度帮助你简短代码(偷懒)。以下是判断整数和复数的两段小代码: 相信看到这里,你也有所顿悟,能拓展出更多有意思的方法~
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic histogram2. 数据分布与密度信息显示 Control rug and density on seaborn histogram3. 带箱形图的直方图 Histogram with a boxplot on t
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic violinplot2. 小提琴图样式自定义 Custom seaborn violinplot3. 小提琴图颜色自定义 Control color of seaborn violinplot4. 分组小提琴图 Group
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic density plot2. 核密度图的区间控制 Control bandwidth of density plot3. 多个变量的核密度图绘制 Density plot of several variables4. 边
首先 import tensorflow as tf tf.argmax(tenso,n)函数会返回tensor中参数指定的维度中的最大值的索引或者向量。当tensor为矩阵返回向量,tensor为向量返回索引号。其中n表示具体参数的维度。 以实际例子为说明: import tensorflow a
seaborn学习笔记章节 seaborn是一个基于matplotlib的Python数据可视化库。seaborn是matplotlib的高级封装,可以绘制有吸引力且信息丰富的统计图形。相对于matplotlib,seaborn语法更简洁,两者关系类似于numpy和pandas之间的关系,seabo
Python ConfigParser教程显示了如何使用ConfigParser在Python中使用配置文件。 文章目录 1 介绍1.1 Python ConfigParser读取文件1.2 Python ConfigParser中的节1.3 Python ConfigParser从字符串中读取数据
1. 处理Excel 电子表格笔记(第12章)(代码下载) 本文主要介绍openpyxl 的2.5.12版处理excel电子表格,原书是2.1.4 版,OpenPyXL 团队会经常发布新版本。不过不用担心,新版本应该在相当长的时间内向后兼容。如果你有新版本,想看看它提供了什么新功能,可以查看Open