% EXAMPLE 2: HYBRID MONTE CARLO SAMPLING -- BIVARIATE NORMAL rand('seed',12345);…
- User
% EXAMPLE 2: HYBRID MONTE CARLO SAMPLING -- BIVARIATE NORMAL rand('seed',12345); randn('seed',12345);
% STEP SIZE delta = 0.3; nSamples = 1000; L = 20;
% DEFINE POTENTIAL ENERGY FUNCTION U = inline('transp(x)*inv([1,.8;.8,1])*x','x');
% DEFINE GRADIENT OF POTENTIAL ENERGY dU = inline('transp(x)*inv([1,.8;.8,1])','x');
% DEFINE KINETIC ENERGY FUNCTION K = inline('sum((transp(p)*p))/2','p');
% INITIAL STATE x = zeros(2,nSamples); x0 = [0;6]; x(:,1) = x0;
t = 1; while t < nSamples t = t + 1;
code% SAMPLE RANDOM MOMENTUM p0 = randn(2,1); %% SIMULATE HAMILTONIAN DYNAMICS % FIRST 1/2 STEP OF MOMENTUM pStar = p0 - delta/2*dU(x(:,t-1))'; % FIRST FULL STEP FOR POSITION/SAMPLE xStar = x(:,t-1) + delta*pStar; % FULL STEPS for jL = 1:L-1 % MOMENTUM pStar = pStar - delta*dU(xStar)'; % POSITION/SAMPLE xStar = xStar + delta*pStar; end % LAST HALP STEP pStar = pStar - delta/2*dU(xStar)'; % COULD NEGATE MOMENTUM HERE TO LEAVE % THE PROPOSAL DISTRIBUTION SYMMETRIC. % HOWEVER WE THROW THIS AWAY FOR NEXT % SAMPLE, SO IT DOESN'T MATTER % EVALUATE ENERGIES AT % START AND END OF TRAJECTORY U0 = U(x(:,t-1)); UStar = U(xStar); K0 = K(p0); KStar = K(pStar); % ACCEPTANCE/REJECTION CRITERION alpha = min(1,exp((U0 + K0) - (UStar + KStar))); u = rand; if u < alpha x(:,t) = xStar; else x(:,t) = x(:,t-1); endend
% DISPLAY figure scatter(x(1,:),x(2,:),'k.'); hold on; plot(x(1,1:50),x(2,1:50),'ro-','Linewidth',2); xlim([-6 6]); ylim([-6 6]); legend({'Samples','1st 50 States'},'Location','Northwest') title('Hamiltonian Monte Carlo') Rewrite the above code in python
- Assistantpython
- User
你的代码写的有问题请重新检查,并解释你更改的代码的每一步的意思
- Assistant
我会解释修改后的Python代码及其每个部分的意义。首先将
rand和randn更改为NumPy中的随机生成器(numpy.random),并设置随机种子为12345,以确保结果的可重复性。接下来,定义步长(
delta),样本数量(nSamples),以及迭代次数(L),这些在原始MATLAB代码中也有定义。然后,定义了势能(
U)函数和其梯度(dU)函数,以及动能(K)函数。这些函数保持不变,只是将它们从MATLAB内联代码转换为Python函数形式。在这部分代码中,定义初始状态并将第一个样本作为初始状态。使用NumPy创建一个零矩阵,大小为 2 x nSamples。将第一个样本的值设置为
x0。进入循环之前,我们将t设置为1。循环将在
nSamples之前一直运行。在每次循环迭代过程中,我们首先根据正态分布采样随机动量p0。然后,我们在
pStar和xStar中对Hamiltonian动力学进行仿真。这个过程基本相同,MATLAB结构中的细微差别(我们为了在NumPy中处理数组访问时使用带有reshape的矩阵)。接下来,我们执行L-1次迭代来计算动量和位置/样本。这也与MATLAB代码非常相似,只有数组访问和函数语法上的差异。
在迭代行结束之后,我们进行最后一个半步长更新,然后计算开始和结束轨迹时的势能(U)和动能(K)。
然后接受/拒绝标准
alpha被计算。随机数u被生成,如果u小于alpha,我们将xStar保留为新样本,否则,我们保留上一个样本作为当前样本。显示部分代码,用于绘制收敛路径及其前50个样本点。这与MATLAB代码几乎完全一样,只是绘图语法略有不同。
在这个修改后的Python代码中,我们基本上保留了所有计算步骤和逻辑,只是修改了语言和库相关的语法。
- User
% EXAMPLE 2: HYBRID MONTE CARLO SAMPLING – BIVARIATE NORMAL rand(‘seed’,12345); randn(‘seed’,12345);
% STEP SIZE delta = 0.3; nSamples = 1000; L = 20;
% DEFINE POTENTIAL ENERGY FUNCTION U = inline(‘transp(x)inv([1,.8;.8,1])x’,‘x’);
% DEFINE GRADIENT OF POTENTIAL ENERGY dU = inline('transp(x)inv([1,.8;.8,1])',‘x’);
% DEFINE KINETIC ENERGY FUNCTION K = inline(‘sum((transp§p))/2’,‘p’);
% INITIAL STATE x = zeros(2,nSamples); x0 = [0;6]; x(:,1) = x0;
t = 1; while t < nSamples t = t + 1;
% SAMPLE RANDOM MOMENTUM p0 = randn(2,1);
%% SIMULATE HAMILTONIAN DYNAMICS % FIRST 1/2 STEP OF MOMENTUM pStar = p0 - delta/2dU(x(:,t-1))’;
% FIRST FULL STEP FOR POSITION/SAMPLE xStar = x(:,t-1) + deltapStar;
% FULL STEPS for jL = 1:L-1 % MOMENTUM pStar = pStar - deltadU(xStar)'; % POSITION/SAMPLE xStar = xStar + deltapStar; end
% LAST HALP STEP pStar = pStar - delta/2*dU(xStar)’;
% COULD NEGATE MOMENTUM HERE TO LEAVE % THE PROPOSAL DISTRIBUTION SYMMETRIC. % HOWEVER WE THROW THIS AWAY FOR NEXT % SAMPLE, SO IT DOESN’T MATTER
- Assistant
I apologize for the formatting issue in the previous response. Here is the corrected Python code:
python - User
error information:ValueError Traceback (most recent call last) Cell In[4], line 45 42 # FULL STEPS 43 for jL in range(1, L): 44 # MOMENTUM ---> 45 pStar = pStar - delta * dU(xStar).reshape(2, 1) 46 # POSITION/SAMPLE 47 xStar = xStar + delta * pStar
ValueError: cannot reshape array of size 4 into shape (2,1)
- Assistant
My apologies for the error in the previous code. The
reshape(2, 1)seems to be incorrect, so we should remove it. Here's the updated code:python - User
- Assistant
It seems like there is an issue with Theano library and the current version of numpy you are using. Theano is no longer actively developed, so compatibility issues with newer versions of numpy are likely to occur.
As an alternative, you can try using PyTorch, another popular deep learning library in Python, which has similar syntax and functionality to Theano. Here's the same code using PyTorch:
pythonimport torch def gamma(beta, ahat, e): if beta == 0: return torch.div(torch.mul(ahat, e), torch.add(ahat, e)) else: num = torch.mul(torch.add(beta, torch.neg(ahat)), e) denom = torch.mul(beta, torch.add(ahat, e)) return torch.div(num, denom) beta = 0 ahat = torch.tensor([1, 2, 3], dtype=torch.float32) e = torch.tensor([4, 5, 6], dtype=torch.float32) g = gamma(beta, ahat, e) print(g)This code will give you the same output as you would get with Theano. Note that you'll need to install the library if you haven't done so already. You can do this using the following command: