MxNet, check if all elements of array have same value - python

I need to check if two MxNet arrays are the same, so I'm using:
def check_equity(x1, x2):
comp = mx.nd.equal(x1, x2)
which produces an array of 0/1 based on whether the corresponding values of x1 and x2 are equal. But how can I check if all the values of the produced comp array are 1s?
The lame way is to just iterate through them (they are images, so (3x224x224 arrays):
check = True
for ch in comp:
for row in ch:
for col in row:
if col == 0:
check = False
return check
I imagine there has to be some sort of .all() method, just can't find any documentation about it.

Related

How to directly compare two lists of integers with that are in different functions in Python

I am currently working on a class project, and it deals with user-defined functions.
I had to get the grid size of an array and put them in a list, as [row, columns], and then there is another function where they check by putting random integers in another list to see if that certain position is inside the array or not. For example, if I have an array with 3 rows and 4 columns, it would be [3,4] and during the test, I inserted [4,4] it would return as false. I am not allowed to hardcore the "position" variable, and that is the one where a list of two integers will be given to compare to the actual size of the array.
What should I do?
Here is my current code
def get_grid_size(grid: list[list[str]]) -> list[int, int]:
grid_size = load_map(MAP_FILE)
col = len(grid_size[0])
row = len(grid_size)
grid_size = [row,col]
return grid_size
def is_inside_grid(grid: list[list[str]], position: list[int, int]) -> bool:
given_row = int(position[1])
given_col = int(position[0])
grid_rows, grid_cols = get_grid_size(grid)
print(grid_rows, grid_cols)
while True:
if grid_rows >= given_row and grid_cols >= given_col:
return True
else:
return False
I tried getting the 0th and 1sth index and respectively make them as row and column variable, then checked weather or now those position row and position column integers were smaller or equal to the actual array row and array column, if it was smaller or equal to, then yes its inside the grid, if its bigger, its not. Negative integers will not be tested for.

Delete 2D unique elements in a 2D NumPy array

I generate a set of unique coordinate combinations by using:
axis_1 = np.arange(image.shape[0])
axis_1 = np.reshape(axis_1,(axis_1.shape[0],1))
axis_2 = np.arange(image.shape[1])
axis_2 = np.reshape(axis_2,(axis_2.shape[0],1))
coordinates = np.array(np.meshgrid(axis_1, axis_2)).T.reshape(-1,2)
I then check for some condition and if it is satisfied i want to delete the coordinates from the array.
Something like this:
if image[coordinates[i,0], coordinates[i,1]] != 0:
remove coordinates i from coordinates
I tried the remove and delete commands but one doesn't work for arrays and the other simply just removes every instance where coordinates[i,0] and coordinates[i,1] appear, rather than the unique combination of both.
You can use np.where to generate the coordinate pairs that should be removed, and np.unique combined with masking to remove them:
y, x = np.where(image > 0.7)
yx = np.column_stack((y, x))
combo = np.vstack((coordinates, yx))
unique, counts = np.unique(combo, axis=0, return_counts=True)
clean_coords = unique[counts == 1]
The idea here is to stack the original coordinates and the coordinates-to-be-removed in the same array, then drop the ones that occur in both.
You can use the numpy.delete function, but this function returns a new modified array, and does not modify the array in-place (which would be quite problematic, specially in a for loop).
So your code would look like that:
nb_rows_deleted = 0
for i in range(0, coordinates.shape[0]):
corrected_i = i - nb_rows_deleted
if image[coordinates[corrected_i, 0], coordinates[corrected_i, 1]] != 0:
coordinates = np.delete(coordinates, corrected_i, 0)
nb_rows_deleted += 1
The corrected_i takes into consideration that some rows have been deleted during your loop.

Selecting list values based on matrix binary values?

I am trying to map elements of a binary matrix to a list of integers. It needs to loop over each row of the matrix, if the value is 1 an item from the corresponding list is chosen and if the value is 0 no item is chosen. The end goal is to have a vector containing the sum of each row of corresponding values.
For example:
listOfNums: [1,2,3,4,5]
m1= [[1,0,1,1,1]
[0,0,0,0,1]
[1,0,0,0,1]]
>>>[13,5,6]
Here is what I have tried so far however I keep getting index errors
def corrspondingVal(self, x):
nums = [1,2,3,4,5,6,7,8,9,10]
return [self.nums[i] for i in range(x) if x[i]]
def sumPerRow(self):
v = np.apply_along_axis(self.correspondingVals(self.matrix1), axis=1, arr=self.matrix1)
return v
(self.matrix1 is a (10,5) matrix of binary values)
Here is one short way, although the multiplication may be expensive.
np.sum(m1 * list, axis=1)
Even better is
np.dot(m1, list)
Without numpy:
listOfSums = [ sum(num for idx,num in enumerate(listOfNums) if row[idx]) for row in m1 ]

Python concatenate 2D array to new list if condition is met

Let's say I have an array:
print(arr1.shape)
(188621, 10)
And in the nth column (let's say 4 for this example), I want to check when a value is above a threshold, t. I want to create a new list (of x instances) of the entire row of arr1 when the ith iteration of the 4th column is above threshold t. In other words, it is extracting the ith row from arr1 when the condition in the 4th column is met. So far I have:
arr2 = []
for i in range(0,len(arr1)):
if arr1[i,4] > t:
arr2.append(arr1[i,:])
I have also tried something along the lines of:
for i in range(0,len(arr1)):
if arr1[i,4] > t:
if len(arr2) == 0:
arr2 = arr1[i,:]
else:
arr2 = np.concatenate((arr2,arr1[i,:]))
However, both instances seem to be growing in 1D terms of x*10 instead of a 2D list of (x, 10) when the conditions are met. What am I missing here?
Well, it wasn't that difficult.
arr2 = arr1[np.logical_not(arr1[:,4] < t)]

Python-1D indice link with 2D array location

Introduction
Sometimes, I want to get the value of an 2-d array at a random location.
For example, there is an array data in the shape of (20,20). There is a random number-pair (5,5). Then, I get the data[5,5] as my target value.
On the purpose of using genetic algorithm. I want to get the samples from an 2-d array as several individuals. So, I want to generate an linked table which connect an 1d value to 2d position.
My attempt
## data was the 2-d array in the shape of 20x20
data = np.random.randint(0,1000,400)
data = data.reshape(20,20)
## direction was my linked table
direction = {"Indice":[],"X":[],"Y":[]}
k = 0
for i in range(0,data.shape[0],1):
for j in range(0,data.shape[1],1):
k+=1
direction["Indice"].append(k)
direction["X"].append(j)
direction["Y"].append(i)
direction = pd.DataFrame(direction)
## generate an random int and connect with the 2-d value.
loc = np.random.randint(0,400)
XX = np.array(direction[direction.Indice == loc ].X)
YY = np.array(direction[direction.Indice == loc ].Y)
target_value = data[YY,XX]
My question
Are there any neat way to achieve my attempt?
Any advice would be appreciate!
You could use np.ravel to make data 1-dimensional, then index it using the flat index loc:
target_value = data.ravel()[loc-1]
Or, if you want XX and YY, perhaps you are looking for np.unravel_index. It maps a flat index or an array of flat indices to a tuple of coordinates.
For example, instead of building the direction DataFrame, you could use
np.unravel_index(loc-1, data.shape)
instead of
XX = np.array(direction[direction.Indice == loc ].X)
YY = np.array(direction[direction.Indice == loc ].Y)
Then you could define target_value as :
target_value = data[np.unravel_index(loc-1, data.shape)]
Alternatively, to simply get a random value from the 2D array data, you could use
target_value = np.random.choice(data.flat)
Or to get N random values, use
target_values = np.random.choice(data.flat, size=(N,))
Why the minus one in loc-1:
In your original code, the direction['Indice'] column uses k values which
start at 1, not 0. So when loc equals 1, the 0th-indexed row of direction is
selected. I used loc-1 to make
target_value = data[np.unravel_index(loc-1, data.shape)]
return the same result that
XX = np.array(direction[direction.Indice == loc ].X)
YY = np.array(direction[direction.Indice == loc ].Y)
target_value = data[YY,XX]
returns. Note however, that if loc equals 0, then np.unravel_index(-1, data.shape) raises a ValueError, while your original code would return an empty array for target_value.

Categories