Numpy+Python比MATLAB慢15倍?

2024-05-12 14:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一些我用Python/Numpy编写的代码,这些代码几乎都是直接从MATLAB代码中翻译出来的。当我在我的机器上运行MATLAB代码时,大约需要17秒。当我在我的机器上运行Python/Numpy代码时,大约需要233秒。我不是在有效地使用Numpy吗?请检查一下我的Python代码,看看我是否以一种无效的方式使用Numpy。在

import numpy as np
from numpy import * 
import pylab as py
from pylab import *
import math
import time

def heat(D,u0,q,tdim):
    xdim = np.size(u0)
    Z = np.zeros([xdim,tdim])
    Z[:,0]=u0;
    for i in range(1,tdim):
        for j in range (1,xdim-1):
            Z[j,i]=Z[j,i-1]+ D*q*(Z[j-1,i-1]-2*Z[j,i-1]+Z[j+1,i-1])
    return Z

start_time = time.clock()
L = 10
D = 0.5

s = 0.03  # magnitude of noise

Tmax = 0.2
xdim = 25
tdim = 75 

x = np.linspace(0,L,xdim)
t = np.linspace(0,Tmax,tdim)

dt = t[1]-t[0]
dx = x[1]-x[0]

q = dt/(dx**2)
r1 = 0.75*L
r2 = 0.8*L


################################################
## check the stability criterion dt/(dx^2)<.5 ##
################################################

# Define the actual initial temperature distribution
u0 = np.zeros(xdim)
for i in range(0,xdim):
    if(x[i]>=r1 and x[i]<=r2):
        u0[i] = 1
xDat = range(1,xdim-1)
tDat = np.array([tdim])
nxDat = len(xDat)
ntDat = 1
tfinal = tdim-1

# synthesize data
Z = heat(D,u0,q,tdim)
u = Z[xDat,tfinal] # matrix
uDat = u + s*randn(nxDat)

# MATLAB PLOTTING
#figure(1);surf(x,t,Z); hold on;
#if ntDat>1, mesh(x(xDat),t(tDat),uDat);
#else set(plot3(x(xDat),t(tDat)*ones(1,nxDat),uDat,'r-o'),'LineWidth',3);
#end; hold off; drawnow


#MCMC run
N = 10000
m = 100
XD = 1.0
X = np.zeros(N)
X[0] = XD
Z = heat(XD,u0,q,tdim)
u = Z[xDat,tfinal]
oLLkd = sum(sum(-(u-uDat)**2))/(2*s**2)
LL = np.zeros(N)
LL[0] = oLLkd

# random walk step size
w = 0.1
for n in range (1,N):
    XDp = XD+w*(2*rand(1)-1)
    if XDp > 0:
        Z = heat(XDp,u0,q,tdim)
        u = Z[xDat,tfinal]
        nLLkd = sum(sum( -(u-uDat)**2))/(2*s**2)
        alpha = exp((nLLkd-oLLkd))
        if random() < alpha:     
            XD = XDp
            oLLkd = nLLkd
            CZ = Z
    X[n] = XD;
    LL[n] = oLLkd;

print time.clock() - start_time, "seconds"

Tags: 代码importnumpytimenpzerosrangeheat
1条回答
网友
1楼 · 发布于 2024-05-12 14:34:07

Numpy和Matlab在基本数组/矩阵操作方面的性能差异很可能是由于Numpy是针对较慢的Lapack实现而安装的。为了获得最佳性能,您可以考虑针对LAPACK(instructions here)构建numpy。在

在您的代码中,主要的性能损失是您基本上是在python for循环中执行一个conversion。因此,你并没有真正利用Numpy的能力。您应该用一个专用的卷积函数来替换double for loop,例如scipy.ndimage.卷积. 在

相关问题 更多 >