# indices to calculate pair-wise products (H, V, D1, D2)
shifts = [[0,1], [1,0], [1,1], [-1,1]]
# calculate pairwise components in each orientation
for itr_shift in range(1, len(shifts) + 1):
OrigArr = structdis
reqshift = shifts[itr_shift-1] # shifting index
for i in range(structdis.shape[0]):
for j in range(structdis.shape[1]):
if(i + reqshift[0] >= 0 and i + reqshift[0] < structdis.shape[0] \
and j + reqshift[1] >= 0 and j + reqshift[1] < structdis.shape[1]):
ShiftArr[i, j] = OrigArr[i + reqshift[0], j + reqshift[1]]
else:
ShiftArr[i, j] = 0
If I try to run the code, I get the following error:
NameError: Name 'ShiftArr' is not defined
How can I solve this error?
By the looks of things you have not defined ShiftArr before you have used it. This is what the error is saying.
It looks like you first use ShiftArr in your nested loop, but nowhere before have you said something like ShiftArr = ...
If you add ShiftArr = [] before your first for loop, this should solve your issue I think. It's a little difficult to understand what you're trying to do as your variable names aren't super informative - this might help you when drying to fix errors in your code.
Related
I have an image tensor of size [1,3,224,224]. I want to apply the delta algorithm onto it (a type of parsing as such in NLP). I have referred to the paper to replicate the algorithm (Section5) - https://arxiv.org/abs/2204.03479
The code I have used so far is as follows, but it uses too many iterations.
img=torch.squeeze(img)
i=0
j=1
d=torch.zeros(img.shape)
for i in range(img.shape[0]):
d[i,0,:]=img[i,0,:]
for j in range(img.shape[1]-1):
d[i,j,:]=img[i,j,:]-img[i,j-1,:]
for k in range(img.shape[2]-1):
if (torch.abs(d[i,j,k])<torch.tensor(0.05)).any():
d[i,j,k]=torch.tensor(0)
img[i,j-1,:]=img[i,j-2,:]
k=k+1
img[i,j-1,:]=img[i,j,:]
j=j+1
i=i+1
This snippet reverts back the delta matrix onto my image reference matrix.
j=1
for j in range(img.shape[1]-1):
img[:,j,:]=img[:,j-1,:]+d[:,j,:]
j=j+1
I want to vectorize the code as much as possible however, could use some pointers on how to proceed.
inputs=input.cuda()
i=0
j=1
delta_inputs = torch.zeros(inputs.shape).cuda()
d = torch.zeros(inputs.shape[0],inputs.shape[1],inputs.shape[2]).cuda()
merge = torch.zeros(inputs.shape[0],inputs.shape[1],inputs.shape[2]).cuda()
for i in range(inputs.shape[2]):
if(i == 0):
d = inputs[:,:,i,:]
else:
d = inputs[:,:,i,:] - inputs[:,:,i-1,:]
merge = d.abs()
merge = torch.gt(merge, 0)
d = d*merge.int()
merge = d.bool()
merge = merge.int()
inputs[:,:,i,:] = inputs[:,:,i,:]*merge + inputs[:,:,i-1,:]*(torch.ones(inputs.shape[0],inputs.shape[1],inputs.shape[2]).cuda()-merge)
delta_inputs[:,:,i,:] = d[:,:,:]
output = torch.zeros(delta_inputs.shape).cuda()
for i in range(inputs.shape[2]):
if(i == 0):
output[:,:,i,:] = delta_inputs[:,:,i,:]
else:
output[:,:,i,:] = output[:,:,i-1,:] + delta_inputs[:,:,i,:]
input=output.cuda()
Hello so I am trying to run this code where i want X_Matrices dictionary to contain all the X_matrix_i matricies. However, all i am getting that X_Matrices end up being the final X_matrix_i of the final loop. I am not quite sure where i am stuck. Any information would be appreciated! thanks.
n = 5
T = 3
p = 5
X_matrix_i = np.zeros((T,p))
X_Matrices = {}
for i in range(n):
X_Matrices["X" + str(i)] = np.zeros((T,p))
for i in range(n):
for t in range(T):
#initial randomness for loop t
ϵ = np.random.normal(0,1,1)
η = np.random.normal(0,1,1)
Covu = np.zeros((p,p))
#Generating X and e of X
for j in range(len(Covu[0])): #covariance matrix for vector x
for l in range(len(Covu)):
Covu[l,j] = 0.7**(np.abs(l-j))
Zerop = np.zeros(p) # mean vector for vector x
x = np.random.multivariate_normal(Zerop,Covu)
X_matrix_i[t] = x
X_Matrices["X" + str(i)] = X_matrix_i
There are two problems here. First one is the conflicting "i" variables in for loops.
One of them should be changed! I replaced the first for loop i variable with k.
for k in range(n):
for t in range(T):
#initial randomness for loop t
The second problem is that by doing
X_Matrices["X" + str(i)] = X_matrix_i
(last line) you are referencing X_Matrices["X" + str(i)] to X_matrix_i! The issue with mutable objects in Python happens! Instead of doing so, you should use shallow copy to assign values to X_Matrices["X" + str(i)]. So a copy of X_matrix_i will be assigned, not X_matrix_i itself.
I replaced the last line with
X_Matrices["X" + str(k)][:] = X_matrix_i
and the problem solved.
[:] acts as shallow copy here.
I think your problem is caused by the redeclaration of i in the second for loop
for j in range(len(Covu[0])): #covariance matrix for vector x
for i in range(len(Covu)):
Covu[i,j] = 0.7**(np.abs(i-j))
Try to rename the i to something else and it should solve your problem.
I'm trying to implemnt Minesweeper game , but i'm stuck , i'm getting the list out of range error and i don't where i did wrong
def Int_jeu(largeur,longueur,diff):
global n, m,T
dif = diff
n=largeur
m=longueur
T = [[0 for i in range(n)] for j in range(m)]
d=((n*m)*dif)//100
print(len(T[0]))
for i in range(d):
a=random.randint(0,len(T)-1)
b=random.randint(0,len(T[0])-1)
while (T[a][b] == "2"):
a=random.randint(0,n-1)
b=random.randint(0,m-1)
T[a][b] = "2"
return(T)
this is the line where i got the error
while (T[a][b] == "2"):
i have declared the matrix T out of the int_jeu function
T = []
can anyone explain me why i get the error please.
m is your first dimension, n is your second, but a is used to index the first dimension (m) while being derived from n (same for b, in reverse).
Change:
a=random.randint(0,n-1)
b=random.randint(0,m-1)
to:
a=random.randint(0,m-1) # Or to simplify, random.randrange(m)
b=random.randint(0,n-1) # Or to simplify, random.randrange(n)
to fix.
This portion I was able to vectorize and get rid of a nested loop.
def EMalgofast(obsdata, beta, pjt):
n = np.shape(obsdata)[0]
g = np.shape(pjt)[0]
zijtpo = np.zeros(shape=(n,g))
for j in range(g):
zijtpo[:,j] = pjt[j]*stats.expon.pdf(obsdata,scale=beta[j])
zijdenom = np.sum(zijtpo, axis=1)
zijtpo = zijtpo/np.reshape(zijdenom, (n,1))
pjtpo = np.mean(zijtpo, axis=0)
I wasn't able to vectorize the portion below. I need to figure that out
betajtpo_1 = []
for j in range(g):
num = 0
denom = 0
for i in range(n):
num = num + zijtpo[i][j]*obsdata[i]
denom = denom + zijtpo[i][j]
betajtpo_1.append(num/denom)
betajtpo = np.asarray(betajtpo_1)
return(pjtpo,betajtpo)
I'm guessing Python is not your first programming language based on what I see. The reason I'm saying this is that in python, normally we don't have to deal with manipulating indexes. You act directly on the value or the key returned. Make sure not to take this as an offense, I do the same coming from C++ myself. It's a hard to remove habits ;).
If you're interested in performance, there is a good presentation by Raymond Hettinger on what to do in Python to be optimised and beautiful :
https://www.youtube.com/watch?v=OSGv2VnC0go
As for the code you need help with, is this helping for you? It's unfortunatly untested as I need to leave...
ref:
Iterating over a numpy array
http://docs.scipy.org/doc/numpy/reference/generated/numpy.true_divide.html
def EMalgofast(obsdata, beta, pjt):
n = np.shape(obsdata)[0]
g = np.shape(pjt)[0]
zijtpo = np.zeros(shape=(n,g))
for j in range(g):
zijtpo[:,j] = pjt[j]*stats.expon.pdf(obsdata,scale=beta[j])
zijdenom = np.sum(zijtpo, axis=1)
zijtpo = zijtpo/np.reshape(zijdenom, (n,1))
pjtpo = np.mean(zijtpo, axis=0)
betajtpo_1 = []
#manipulating an array of numerator and denominator instead of creating objects each iteration
num=np.zeros(shape=(g,1))
denom=np.zeros(shape=(g,1))
#generating the num and denom real value for the end result
for (x,y), value in numpy.ndenumerate(zijtpo):
num[x],denom[x] = num[x] + value *obsdata[y],denom[x] + value
#dividing all at once after instead of inside the loop
betajtpo_1= np.true_divide(num/denom)
betajtpo = np.asarray(betajtpo_1)
return(pjtpo,betajtpo)
Please leave me some feedback !
Regards,
Eric Lafontaine
For some reason, when I try and implement the following code (I'm using Sublime Text 2) it gives me the error "Invalid Syntax" on line 18. I'm not sure why this is, I found the code here and it apparently should work, so I have no idea why it doesn't. Any tips?
Here is the code:
def damerau_levenshtein_distance(word1, word2):
distances = {}
len_word1 = len(word1)
len_word2 = len(word2)
for i in xrange(-1, (len_word1 + 1)):
distances[(i,-1)] = i + 1
for j in xrange(-1, (len_word2 + 1)):
distances[(-1,j)] = j + 1
for i in xrange(len_word1):
if word1[i] == word2[j]:
distance_total = 0
else:
distance_total = 1
distances[(i, j)] = min(
distances[(i-1,j)] + 1, # deletion
distances[(i,j-1)] + 1 # insertion
distances[(i-1,j-1)] + distance_total #substitution
)
if i and j and word1[i] == word2[j-1] and word1[i-1] == word2[j]:
distances[(i,j)] = min(distances[(i,j)], distances[i-2,j-2] + distance_total) # transposition
return distances[len_word1-1,len_word2-1]
there is an error should be:
,#insertion
Looks like you've fixed this issue, but if you don't want to implement all of these yourself, you can use the jellyfish package found in pypi: https://pypi.python.org/pypi/jellyfish. I've used it to great success in the past.
It contains several distance functions, including Damerau-Levenshtein distances.