gpt4 book ai didi

Python Newaxis 与 for 循环

转载 作者:行者123 更新时间:2023-11-28 22:55:56 27 4
gpt4 key购买 nike

我正在努力使我的程序更快。我有一个矩阵和一个向量:

GDES = N.array([[1,2,3,4,5],
[6,7,8,9,10],
[11,12,13,14,15],
[16,17,18,19,20],
[21,22,23,24,25]])
Ene=N.array([1,2,3,4,5])
NN=len(GDES);

我定义了一个矩阵乘法函数:

def Gl(n,np,k,q):
matrix = GDES[k,np]*GDES[k,n]*GDES[q,np]*GDES[q,n]
return matrix

我在计算中做了一个for循环:

SIl = N.zeros((NN,NN),N.float)
for n in xrange(NN):
for np in xrange(NN):
SumJ = N.sum(N.sum(Gl(n,np,k,q) for q in xrange(NN)) for k in xrange(NN))
SIl[n,np]=SumJ

print 'SIl:',SIl

输出:

SIl: [[ 731025. 828100. 931225. 1040400. 1155625.]
[ 828100. 940900. 1060900. 1188100. 1322500.]
[ 931225. 1060900. 1199025. 1345600. 1500625.]
[ 1040400. 1188100. 1345600. 1512900. 1690000.]
[ 1155625. 1322500. 1500625. 1690000. 1890625.]]

我想使用 newaxis 让它更快:

def G():
Mknp = GDES[:, :, N.newaxis, N.newaxis]
Mkn = GDES[:, N.newaxis, :, N.newaxis]
Mqnp = GDES[:, N.newaxis, N.newaxis, :]
Mqn = GDES[N.newaxis, :, :, N.newaxis]
matrix=Mknp*Mkn*Mqnp*Mqn
return matrix

tmp = G()
MGI = N.sum(N.sum(tmp,axis=3), axis=2)
MGI = N.reshape(MGI,(NN,NN))
print 'MGI:', MGI

输出:

MGI: [[ 825 3900 9225 16800 26625]
[ 31200 92400 169600 262800 372000]
[ 146575 413400 722475 1073800 1467375]
[ 403200 1116900 1911600 2787300 3744000]
[ 857325 2352900 3980725 5740800 7633125]]

知道怎样才能得到正确答案吗?

最佳答案

您的问题非常适合 np.einsum :

>>> GDES = np.arange(1, 26).reshape(5, 5)
>>> np.einsum('kj,ki,lj,li->ij', GDES, GDES, GDES, GDES)
array([[ 731025, 828100, 931225, 1040400, 1155625],
[ 828100, 940900, 1060900, 1188100, 1322500],
[ 931225, 1060900, 1199025, 1345600, 1500625],
[1040400, 1188100, 1345600, 1512900, 1690000],
[1155625, 1322500, 1500625, 1690000, 1890625]])

对于您的特定情况,其他语法可能更容易理解:

>>> np.einsum(GDES, [2,1], GDES, [2,0], GDES, [3,1], GDES, [3,0], [0,1])
array([[ 731025, 828100, 931225, 1040400, 1155625],
[ 828100, 940900, 1060900, 1188100, 1322500],
[ 931225, 1060900, 1199025, 1345600, 1500625],
[1040400, 1188100, 1345600, 1512900, 1690000],
[1155625, 1322500, 1500625, 1690000, 1890625]])

关于Python Newaxis 与 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201303/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com