具体实现
对于 Ising 模型,Metropolis-Hasting 算法遵循以下步骤:
(1)选择一个起始自旋状态x。
(2)选择一个新的自旋状态x'。
(3)根据新状态与旧状态的相对概率p(x')/p(x),随机地决定采用新状态还是保留旧状态。
(4)重复步骤 2 和 3,直到收敛。实际上这里往往是设定一个N步。
其中,关于x的概率质量函数是,

这意味着对于第 3 步,似然比是

这是一个比值,因此避免了对所有状态求和

得到似然比为,

算法按照上述比率来选择新旧状态x'和x,从而以适当的加权概率游走马尔可夫链。Hastings 在文献中描述了几种方案,但表示 Metropolis 他们的选择是最有效的。算法中是以如下概率从x转移到x',

5.简单实现
针对 Ising 模型的简单模拟网上 Python 代码很多,比如 https://rajeshrinet.github.io/blog/2014/ising-model/
。
import numpy as np
from numpy.random import rand
import matplotlib.pyplot as plt
%matplotlib inline
# Simulating the Ising model
class Ising():
''' Simulating the Ising model '''
## monte carlo moves
def mcmove(self, config, N, beta):
''' This is to execute the monte carlo moves using
Metropolis algorithm such that detailed
balance condition is satisified'''
for i in range(N):
for j in range(N):
a = np.random.randint(0, N)
b = np.random.randint(0, N)
s = config[a, b]
nb = config[(a+1)%N,b] + config[a,(b+1)%N] + config[(a-1)%N,b] + config[a,(b-1)%N]
cost = 2 <em> s </em> nb
if cost < 0:
s *= -1
elif rand() < np.exp(-cost*beta):
s *= -1
config[a, b] = s
return config
def simulate(self):
''' This module simulates the Ising model'''
N, temp = 64, .4 # Initialse the lattice
config = 2*np.random.randint(2, size=(N,N))-1
f = plt.figure(figsize=(15, 15), dpi=80);
self.configPlot(f, config, 0, N, 1);
msrmnt = 1001
for i in range(msrmnt):
self.mcmove(config, N, 1.0/temp)
if i == 1: self.configPlot(f, config, i, N, 2);
if i == 4: self.configPlot(f, config, i, N, 3);
if i == 32: self.configPlot(f, config, i, N, 4);
if i == 128: self.configPlot(f, config, i, N, 5);
if i == 256: self.configPlot(f, config, i, N, 6);
def configPlot(self, f, config, i, N, n_):
''' This modules plts the configuration once passed to it along with time etc '''
X, Y = np.meshgrid(range(N), range(N))
sp = f.add_subplot(3, 3, n_ )
plt.setp(sp.get_yticklabels(), visible=False)
plt.setp(sp.get_xticklabels(), visible=False)
plt.pcolormesh(X, Y, config, cmap=plt.cm.RdBu);
plt.title('Time=%d'%i); plt.axis('tight')
plt.show()
rm = Ising()
rm.simulate()
运行结果如下,

本文转载自微信公众号:机器学习与数学