2013-02-21 69 views
3
import numpy as np 
from numpy.linalg import solve,norm,cond,inv,pinv 
import math 
import matplotlib.pyplot as plt 
from scipy.linalg import toeplitz 
from numpy.random import rand 

c = np.zeros(512) 
c[0] = 2 
c[1] = -1 
a = c 
A = toeplitz(c,a) 

cond_A = cond(A,2) 

# creating 10 random vectors 512 x 1 
b = rand(10,512) 

# making b into unit vector 
for i in range (10): 
    b[i]= b[i]/norm(b[i],2) 

# creating 10 random del_b vectors 
del_b = [rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512), rand(10,512)] 

# del_b = 10 sets of 10 vectors (512x1) whose norm is 0.01,0.02 ~0.1 
for i in range(10): 
    for j in range(10): 
     del_b[i][j] = del_b[i][j]/(norm(del_b[i][j],2)/((float(j+1)/100))) 

x_in = [np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512), np.zeros(512)] 

x2 = np.zeros((10,10,512)) 
for i in range(10): 
    x_in[i] = A.transpose()*b[i] 

for i in range(10): 
    for j in range(10): 
     x2[i][j] = ((A.transpose()*(b[i]+del_b[i][j])) 

最後一行給我錯誤。 (輸出操作數需要減少,但是減少未啓用) 我該如何解決它? 我是新來的蟒蛇並請讓我知道,如果沒有做到這一點輸出操作數需要減少,但是減少未啓用Python

由於更簡單的方法

+1

將有助於大大如果你可以添加import語句(如numpy的NP,SciPy的#小號託普利茨,等等),這樣的代碼複製,粘貼和運行原樣。 – YXD 2013-02-21 10:26:35

+0

我剛剛包括在內。謝謝 – kiki 2013-02-21 17:11:48

+2

在提高錯誤的行中,左手邊的形狀是'(512,)',右手邊的形狀是(512,512)'。您試圖將一個512x512二維數組塞入一個512長的一維數組中。 – DSM 2013-02-21 17:22:17

回答

1

你看到的錯誤是因爲在您創建什麼尺寸不匹配的,但你的代碼在循環播放時效率也很低,並且不能最大限度地利用Numpy的自動廣播。我已經重寫了代碼做什麼,似乎你想要的:

import numpy as np 
from numpy.linalg import solve,norm,cond,inv,pinv 
import math 
import matplotlib.pyplot as plt 
from scipy.linalg import toeplitz 
from numpy.random import rand 

# These should probably get more sensible names 
Nvec = 10 # number of vectors in b 
Nlevels = 11 # number of perturbation norm levels 
Nd = 512 # dimension of the vector space 

c = np.zeros(Nd) 
c[0] = 2 
c[1] = -1 
a = c 

# NOTE: I'm assuming you want A to be a matrix 
A = np.asmatrix(toeplitz(c, a)) 

cond_A = cond(A,2) 

# create Nvec random vectors Nd x 1 
# Note: packing the vectors in the columns makes the next step easier 
b = rand(Nd, Nvec) 

# normalise each column of b to be a unit vector 
b /= norm(b, axis=0) 

# create Nlevels of Nd x Nvec random del_b vectors 
del_b = rand(Nd, Nvec, Nlevels) 

# del_b = 10 sets of 10 vectors (512x1) whose norm is 0.01,0.02 ~0.1 
targetnorms = np.linspace(0.01, 0.1, Nlevels) 
# cause the norms in the Nlevels dimension to be equal to the target norms 
del_b /= norm(del_b, axis=0)[None, :, :]/targetnorms[None, None, :] 

# Straight linear transformation - make sure you actually want the transpose 
x_in = A.T*b 

# same linear transformation on perturbed versions of b 
x2 = np.zeros((Nd, Nvec, Nlevels)) 
for i in range(Nlevels): 
    x2[:, :, i] = A.T*(b + del_b[:, :, i])