how to make rank array in numpy - python

Given a numpy ndarray A, return its rank array.
Input : [[ 9 4 15 0 18]
[16 19 8 10 1]]
Return value: [[4 2 6 0 8]
[7 9 3 5 1]]
**but I didnt solve actually I solve but my solution is wrong
how can I solve ? please help meemphasized text**
import numpy as np
array=np.array([[9,4,15,0,18],[16,19,8,10,1]])
array_1=np.array([9,4,15,0,18])
array_2=np.array([16,19,8,10,1])
temp1 = array_1.argsort()
temp2 = array_2.argsort()
ranks1 = np.arange(len(array_1))[temp1.argsort()]
rankss=ranks1.argsort()
ranks2 = np.arange(len(array_2))[temp2.argsort()]
print(ranks1*array.ndim)
print(rankss)

If you pass axis=None to argsort then the source array
is flattened at the first step (and only then arg-sorted).
So probably the shortest code is:
result = arr.argsort(axis=None).reshape(arr.shape)
No need to explicitely flatten the source array and only
a single call to argsort.

Related

How do I add a vector into a specific row of a matrix?

I have a matrix and I want to add a vector into the fourth row of the matrix. I am using vstack but I am having trouble figuring out how to input it as the fourth row. If I input the new vector as either the first or second argument, it will add the vector as the first or last row of them matrix. Here is my example:
A = np.reshape(range(1,21),(4,5)
print (A)
B = np.vstack([(10,3,5,2,6),A])
print(B)
With this code, B will have the new vector as the first row of the matrix. I need it to be the fourth row so that when I print B, the last row of the matrix is [16,17,18,19,20] and B becomes a 5x5 matrix.
[1 2 3 4 5]
[6 7 8 9 10]
[11 12 13 14 15]
[10 3 5 2 6]
[16 17 18 19 20]
The matrix above is my desired output. What do I need to include?
I think this should do it. Likely read the docs to get clarification, but this seemed to work.
B = np.vstack([A, (10,3,5,3,6)])
for some reason the order mattered, of course I did not read enough to give more.

Applying a function along a numpy array using indexes as parameters

I am trying to find a way to run a function through a whole ndarray using the indexes of every value as parameters. A regular loop is quite slow and I can't find a way to make it work using numpy built-in functions. The next example code summarizes what i'm trying to do. Thanks in advance.
import numpy as np
arr = np.arange(10).reshape(2, 5)
print(arr)
def example_func(row, col, value):
return(row + col + value)
for row in range(arr.shape[0]):
for col in range(arr.shape[1]):
arr[row, col] = example_func(row, col, arr[row, col])
print(arr)
[[0 1 2 3 4]
[5 6 7 8 9]]
[[ 0 2 4 6 8]
[ 6 8 10 12 14]]
What you try to do can be done with meshgrid.
Return coordinate matrices from coordinate vectors.
n_rows, n_cols = arr.shape
col_matrix, row_matrix = np.meshgrid(np.arange(n_cols), np.arange(n_rows))
result = arr + col_matrix + row_matrix
print(result)
This returns
[[ 0 2 4 6 8]
[ 6 8 10 12 14]]

How can I permute the rows/columns of a Tensorflow 3-tensor?

I have a (N, 9, 9) shape tensorflow tensor T, and permutations Px, Py which might look like this: [3 4 5 6 7 8 2 1 0], [6 8 2 0 3 7 4 1 5].
I want to apply the permutation Px to the 1st axis of T, and Py to the 2nd axis. That is, I want to compute a tensor S defined by
S_i,j,k = T_i,Px(j),Py(k)
To use tf.gather_nd to construct S I need to construct an indices tensor such that
indices[i,j,k,0] = i
indices[i,j,k,1] = Px(j)
indices[i,j,k,2] = Py(k)
What's the cleanest way to construct indices (in Python)?
If I undestand your problem statement correctly, I believe this is what you need.
indices[:,:,:,0] = np.arange(indices.shape[0])
indices[:,:,:,1] = indices[:,Px(np.arange(indices.shape[1]),:,1]
indices[:,:,:,2] = indices[:,:,Py(np.arange(indices.shape[2]),2]
Hard to tell without a minimal reproducible.

Python - Theano scan() function

I cannot fully understand the behaviour of theano.scan().
Here's an example:
import numpy as np
import theano
import theano.tensor as T
def addf(a1,a2):
return a1+a2
i = T.iscalar('i')
x0 = T.ivector('x0')
step= T.iscalar('step')
results, updates = theano.scan(fn=addf,
outputs_info=[{'initial':x0, 'taps':[-2]}],
non_sequences=step,
n_steps=i)
f=theano.function([x0,i,step],results)
print f([1,1],10,2)
The above snippet prints the following sequence, which is perfectly reasonable:
[ 3 3 5 5 7 7 9 9 11 11]
However if I switch the tap index from -2 to -1, i.e.
outputs_info=[{'initial':x0, 'taps':[-1]}]
The result becomes:
[[ 3 3]
[ 5 5]
[ 7 7]
[ 9 9]
[11 11]
[13 13]
[15 15]
[17 17]
[19 19]
[21 21]]
instead of what would seem reasonable to me (just take the last value of the vector and add 2):
[ 3 5 7 9 11 13 15 17 19 21]
Any help would be much appreciated.
Thanks!
When you use taps=[-1], scan suppose that the information in the output info is used as is. That mean the addf function will be called with a vector and the non_sequence as inputs. If you convert x0 to a scalar, it will work as you expect:
import numpy as np
import theano
import theano.tensor as T
def addf(a1,a2):
print a1.type
print a2.type
return a1+a2
i = T.iscalar('i')
x0 = T.iscalar('x0')
step= T.iscalar('step')
results, updates = theano.scan(fn=addf,
outputs_info=[{'initial':x0, 'taps':[-1]}],
non_sequences=step,
n_steps=i)
f=theano.function([x0,i,step],results)
print f(1,10,2)
This give this output:
TensorType(int32, scalar)
TensorType(int32, scalar)
[ 3 5 7 9 11 13 15 17 19 21]
In your case as it do addf(vector,scalar), it broadcast the elemwise value.
Explained in another way, if taps is [-1], x0 will be passed "as is" to the inner function. If taps contain anything else, what is passed to the inner function will have 1 dimension less then x0, as x0 must provide many initial steps value (-2 and -1).

Loop across K-uplets from a N-K matrix in python

I have to use dynamic programming in a python script.
I defined a numpy array u with shape=(N,K).
I want to pick one element for each column, therefore generating a K-uplets.
How would you proceed to loop efficiently across all K-uplets generated this way ? A solution would be to use
import itertools
itertools.combination_with_replacement(list,K)
where list = [0..N-1], but I will need to build iteratively each of my K-uplets using the output (index) of the itertools method.
Is there a more direct way to proceed ?
Thanks
Vincent
You can build the K-uplet with arr[ind, np.arange(K)]. Of course, that's actually a NumPy ndarray, but they are easy to convert to tuplets if you really want tuplets: tuple(arr[ind, np.arange(K)]).
import numpy as np
import itertools as IT
N, K = 5,3
arr = np.arange(N*K).reshape(N,K)
print(arr)
# [[ 0 1 2]
# [ 3 4 5]
# [ 6 7 8]
# [ 9 10 11]
# [12 13 14]]
for ind in IT.combinations_with_replacement(range(N), K):
print(arr[ind, np.arange(K)])
# [0 1 2]
# [0 1 5]
# [0 1 8]
# [ 0 1 11]
# ...

Categories

Resources