重要度采样 important sample及 MATLAB,python实现

2023-10-15 14:18

本文主要是介绍重要度采样 important sample及 MATLAB,python实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1实践

MATLAB:

% Demo Kalman + Sequential Importance Sampling for linear gaussian model
% use prior proposal and locally optimal proposalT=100;
sv=1;
sw=sqrt(1);
phi=0.95;% simulate data according to the model
x=zeros(1,T);
y=zeros(1,T);
x=randn(1);
for k=2:Tx(1,k)=phi*x(1,k-1)+sv.*randn(1);
end
y=x+sw.*randn(1,T);
plot(y)
% load simulatedstatesobs   data corresponding to lecture notes% number of samples/particles
N=1000;% exact inference using Kalman filter
mp=zeros(1,T);
mf=zeros(1,T);
vp=zeros(1,T);
vf=zeros(1,T);
my=zeros(1,T);
vy=zeros(1,T);
loglike=0;mp(1,1)=0;
vp(1,1)=1;
my(1,1)=mp(1,1);
vy(1,1)=vp(1,1)+sw^2;
loglike=-0.5*log(2*pi*vy(1,1))-0.5*(y(1,1)-my(1,1))^2/vy(1,1);for k=1:T% updatevf(1,k)=sw^2*vp(1,k)/(vp(1,k)+sw^2);mf(1,k)=vf(1,k)*(mp(1,k)/vp(1,k)+y(1,k)/sw^2);% predictif (k<T)mp(1,k+1)=phi*mf(1,k);vp(1,k+1)=phi^2*vf(1,k)+sv^2;my(1,k+1)=mp(1,k+1);vy(1,k+1)=vp(1,k+1)+sw^2;loglike=loglike-0.5*log(2*pi*vy(1,k+1))-0.5*(y(1,k+1)-my(1,k+1))^2/vy(1,k+1);end
end% prior proposal
xs1=zeros(T,N);
lw1=zeros(T,N);
w1=zeros(T,N);
wnorm1=zeros(T,N);
ess1=zeros(1,T);
xmean1=zeros(1,T);
xvar1=zeros(1,T);
varlogw1=zeros(1,T);% locally optimal proposal
xs2=zeros(T,N);
lw2=zeros(T,N);
w2=zeros(T,N);
wnorm2=zeros(T,N);
ess2=zeros(1,T);
xmean2=zeros(1,T);
xvar2=zeros(1,T);
varlogw2=zeros(1,T);% SIS using prior
for k=1:Tif (k==1)% sample particles initial distributionxs1(k,:)=randn(1,N);% compute log weights for numerical stabilitylw1(k,:)=-0.5*log(2*pi*sw^2).*ones(1,N)-0.5*(y(1,k)*ones(1,N)-xs1(k,:)).^2./sw^2;else% propagate particles according to prior xs1(k,:)=phi.*xs1(k-1,:)+sv.*randn(1,N);% compute log weights for numerical stabilitylw1(k,:)=lw1(k-1,:)-0.5*log(2*pi*sw^2).*ones(1,N)-0.5*(y(1,k)*ones(1,N)-xs1(k,:)).^2./sw^2;endvarlogw1(1,k)=var(lw1(k,:));lmax=max(lw1(k,:));w1(k,:)=exp(lw1(k,:)-lmax);  % correct only up to a multiplicative factor for unnormalized weightswnorm1(k,:)=w1(k,:)./sum(w1(k,:));% effective sample sizeess1(1,k)=1/sum(wnorm1(k,:).^2);% compute estimate of E(Xk|y1:k)xmean1(1,k)=sum(wnorm1(k,:).*xs1(k,:));% compute estimate of Var(Xk|y1:k)xvar1(1,k)=sum(wnorm1(k,:).*xs1(k,:).^2)-xmean1(1,k)^2;
end% SIS using optimal% variance locally optimal proposal
ss2=sw^2*sv^2/(sv^2+sw^2);
ss=sqrt(ss2);for k=1:Tif (k==1)% sample particles initial proposal; e.g p(x1|y1)xs2(k,:)=ss2*y(1,k)*ones(1,N)/sw^2+ss.*randn(1,N);% compute log weights for numerical stabilitylw2(k,:)=-0.5*log(2*pi*(sw^2+sv^2)).*ones(1,N)-0.5*(y(1,k)*ones(1,N)).^2./(sw^2+sv^2);else% propagate particles according to p(xk|xk-1,yk) xs2(k,:)=ss2.*(phi.*xs2(k-1,:)./sv^2+y(1,k)/sw^2)+ss.*randn(1,N);lw2(k,:)=lw2(k-1,:)-0.5*log(2*pi*(sw^2+sv^2)).*ones(1,N)-0.5*(y(1,k)*ones(1,N)-phi.*xs2(k-1,:)).^2./(sw^2+sv^2);endvarlogw2(1,k)=var(lw2(k,:));lmax=max(lw2(k,:));w2(k,:)=exp(lw2(k,:)-lmax);  % correct only up to a multiplicative factor for unnormalized weightswnorm2(k,:)=w2(k,:)./sum(w2(k,:));% effective sample sizeess2(1,k)=1/sum(wnorm2(k,:).^2);% compute estimate of E(Xk|y1:k)xmean2(1,k)=sum(wnorm2(k,:).*xs2(k,:));% compute estimate of Var(Xk|y1:k)xvar2(1,k)=sum(wnorm2(k,:).*xs2(k,:).^2)-xmean2(1,k)^2;
end% display ESS
figure(1)
plot(ess1,'r')
hold on
plot (ess2,'b')
print essprioroptimalhighsw -depsc
axis([1 T 0 N])
% display variance log weightsfigure(2)
subplot(2,1,1)
plot(varlogw1,'r');
subplot(2,1,2)
plot(varlogw2,'b');
print varlogweightprioroptimalhighsw -depsc% display absolute error exact conditional mean versus SIS
figure(3)
plot(abs(mf-xmean1),'r');
hold on
plot(abs(mf-xmean2),'b');
axis([1 T 0 5])
print errorxmeanprioroptkalman -depsc% display exact variance versus SIS
figure(4)
plot(xvar1,'r');
hold on
plot(xvar2,'b');
plot(vf,'c');
axis([1 T 0 3])
print vmeanprioroptkalman -depschold off

python:

# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 21:19:55 2019@author: win10
"""import numpy as np
from scipy import stats
from numpy.random import randn,random
import matplotlib.pyplot as pltdef gaussian_particles(mean,std,N):particles = np.empty((N,1))particles[:, 0] = mean + (randn(N) * std)return particlesdef predict(particles, d, std, dt=1.):N = len(particles)degradation = (d * dt) + (randn(N) * std)return degradationdef update(particles, weights, z, R):weights.fill(1.)weights = weights*stats.norm(z, R).pdf(particles)weights += 1.e-100weights /= sum(weights)def simple_resample(particles, weights):N = len(particles)cumulative_sum = np.cumsum(weights)cumulative_sum[-1] = 1.indexes = np.searchsorted(cumulative_sum, random(N))# resample according to indexesparticles[:] = particles[indexes]weights.fill(1.0 / N)def neff(weights):return 1. / np.sum(np.square(weights))def estimate(particles, weights):'''returns the mean and variance of the weighted particles.'''mean = np.average(particles, weights=weights, axis = 0)var  = np.average((particles - mean)**2, weights=weights, axis = 0)return mean, varif __name__ == '__main__':N = 100 # Number of particlesx_0 = 0.1 #initial statex_N = 0.001  # Noise covariance in the systemx_R = 0.001  # Noise covariance in the measurementT = 10 # Time stepsd = 0.001 # very simple State update model# Initial particles, gaussian distributedparticles = gaussian_particles(x_0,x_N,N)weights = np.zeros(N)true_state = [0.1]for t in range(T):# measurement. We just add some random sensor noisetrue_state.append(true_state[t] + 0.001)z = true_state[t] + (randn(N) * x_R)# predict particlespred_z = predict(particles, d, x_N)# updated Observationz_updated = particles + (randn(N) * x_R)# incorporate measurements and update our belief- posteriorupdate(particles, weights, z=z, R=x_R)# resample if number of effective particles drops below N/2if neff(weights) < N/2:simple_resample(particles, weights)mu, var = estimate(particles, weights)plt.plot(np.arange(len(true_state)), true_state)

参考:
1 Gaussian Process with Particle Filter - Part 2 python 源码;
2 Oxford 课站 含MATLAB code;
3 豆瓣 粒子群滤波总结

这篇关于重要度采样 important sample及 MATLAB,python实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/218254

相关文章

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文