I know there is image_gradients in tensorflow to get dx, dy of the image like this
dx, dy = tf.image.image_gradients(image)
print(image[0, :,:,0])
tf.Tensor(
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]
[10. 11. 12. 13. 14.]
[15. 16. 17. 18. 19.]
[20. 21. 22. 23. 24.]], shape=(5, 5), dtype=float32)
print(dx[0, :,:,0])
tf.Tensor(
[[5. 5. 5. 5. 5.]
[5. 5. 5. 5. 5.]
[5. 5. 5. 5. 5.]
[5. 5. 5. 5. 5.]
[0. 0. 0. 0. 0.]], shape=(5, 5), dtype=float32)
print(dy[0, :,:,0])
tf.Tensor(
[[1. 1. 1. 1. 0.]
[1. 1. 1. 1. 0.]
[1. 1. 1. 1. 0.]
[1. 1. 1. 1. 0.]
[1. 1. 1. 1. 0.]], shape=(5, 5), dtype=float32)
It looks like the gradient values are organized so that [I(x+1, y) - I(x, y)] is in location (x, y).
If I would like to do it manually, I'm not sure what I should do.
I tried to input the formula [I(x+1, y) - I(x, y)], but I have no idea how to implement it in the loop
x = image[0,:,:,0]
x_unpacked = tf.unstack(x)
processed = []
for t in x_unpacked:
???
processed.append(result_tensor)
output = tf.concat(processed, 0)
Or if I can shift the whole tensor to the x,y direction, I could do the tensor subtraction, but still not sure about how to handle the edge information. (Above example, they are all zero for the last row/column)
Any help would be appreciated.
for the above example,dx
dx = tf.pad(img[1:,] - img[:-1,], [[0,1],[0,0]])
for dy
dy = tf.pad(img[:,1:] - img[:,:-1], [[0,0],[0,1]])
Related
I have many 2D arrays inside of a 3D array.
Let’s assume that shape of the 3D array is (3, 5, 5). Therefore, I have 3 2D Arrays of shape (5, 5).
Column #4 (idx of 3) in each 2D array has a certain value as per below. I want to replace those values with corresponding ranks in descending order. The highest value will correspond to the maximum number of records (I.e. shape[1]) in 2D array, and the lowest value will have a rank of 1 (not 0).
I know that this could be achieved using NumPy’s argsort() function. But what I want to avoid is looping through the 3D array.
Could you please suggest the most efficient, native NumPy and loop-free alternatives?
Thank you!
[[[1. 0. 0.10. 0.]
[2. 0. 0. 9. 0.]
[3. 0. 0. 8. 0.]
[4. 0. 0. 7. 0.]
[5. 0. 0. 6. 0.]]
[[1. 0. 0. 199. 0.]
[2. 0. 0. 198. 0.]
[3. 0. 0. 196. 0.]
[4. 0. 0. 190. 0.]
[5. 0. 0. 160. 0.]]
[[1. 0. 0. 999. 0.]
[2. 0. 0. 870. 0.]
[3. 0. 0. 270. 0.]
[4. 0. 0. 100. 0.]
[5. 0. 0. 80. 0.]]]
I suggest:
arr[:, :, 3] = arr[:, :, 3].argsort(axis=1).argsort(axis=1) + 1
Note that using argsort twice is necessary to obtain "ranks".
I made the NxN matrix with Zeros and Ones and symmetrical and diagonal = 0. Now I want to make another matrix. Instead of the one in the matrix, I put a random number from 0-100 opposite numbers in the upper triangle and the one tringle have the same value as in the picture
and I want to do this to all ones in the new matrix
Thank You
enter image description here
All you should need to do is generate an NxN array of random numbers and multiply:
import numpy as np
N = 7
base = np.zeros((N,N))
for _ in range(15):
a = np.random.randint(N)
b = np.random.randint(N)
if a != b:
base[a,b] = 1
base[b,a] = 1
print(base)
# Fetch the location of the 1s.
ones = np.argwhere(base==1)
ones = ones[ones[:,0] < ones[:,1],:]
# Assign random values.
for a,b in ones:
base[a,b] = base[b,a] = np.random.randint(100)
print(base)
Note that my array creation is just for this example. You said you already have the 1/0 matrix so I'm not worried about that part.
Output:
[[0. 1. 0. 1. 1. 1. 1.]
[1. 0. 1. 0. 1. 1. 0.]
[0. 1. 0. 1. 1. 0. 0.]
[1. 0. 1. 0. 1. 0. 1.]
[1. 1. 1. 1. 0. 0. 1.]
[1. 1. 0. 0. 0. 0. 0.]
[1. 0. 0. 1. 1. 0. 0.]]
[[ 0. 37. 0. 7. 43. 40. 54.]
[37. 0. 45. 0. 87. 40. 0.]
[ 0. 45. 0. 74. 8. 0. 0.]
[ 7. 0. 74. 0. 47. 0. 75.]
[43. 87. 8. 47. 0. 0. 41.]
[40. 40. 0. 0. 0. 0. 0.]
[54. 0. 0. 75. 41. 0. 0.]]
How to find the inverse of a matrix in Python by hand?
Reasons you might want to do this:
I need to learn how to inverse a matrix for a school project.
I'm interested in calculating the inverse of a matrix using a programming language.
I recently wrote a code to find the inverse of a matrix in Python.
It gives a step by step explanation as you run the code. It also determines whether the inverse exists. I hope you enjoy it!
This code is for educational purposes. This might not be the most efficient way.
# Import packages
from numpy import *
from random import *
# Defining functions (skip this cell for readability)
def Gauss_explain():
global A, A_inv
for j in range(i+1,len(A)):
if (A[j][i]):
factor=A[j][i]/A[i][i]
for k in range(len(A)):
A[j][k]-=factor*A[i][k]
A_inv[j][k]-=factor*A_inv[i][k]
print()
if (factor>0): print('--- Gauss elimination: row',j+1,'-',factor,'* row',i+1,'---\n')
else: print('--- Gauss elimination: row',j+1,'+',-factor,'* row',i+1,'---\n')
print(A)
print()
print(A_inv)
def Switch_explain():
global A, A_inv
det=0
for j in range(i+1,len(A)):
if (A[j][i]):
temp=A[i].copy()
A[i]=A[j]
A[j]=temp
temp=A_inv[i].copy()
A_inv[i]=A_inv[j]
A_inv[j]=temp
det=1
print()
print('--- Switch rows',i+1,'and',j+1,'---\n')
print(A)
print()
print(A_inv)
break
return det
def Gauss_up_explain():
global A, A_inv
if (A[j][i]):
factor=A[j][i]/A[i][i]
A[j][i]-=factor*A[i][i]
for k in range(len(A)):
A_inv[j][k]-=factor*A_inv[i][k]
print()
if (factor>0): print('--- Gauss elimination (up): row',j+1,'-',factor,'* row',i+1,'---\n')
else: print('--- Gauss elimination (up): row',j+1,'+',-factor,'* row',i+1,'---\n')
print(A)
print()
print(A_inv)
def Divide_explain():
global A, A_inv
if (A[i][i]!=1):
factor=A[i][i]
A[i][i]=1
A_inv[i]/=factor
print()
print('--- Divide row',i+1,'by',factor,'---\n')
print(A)
print()
print(A_inv)
# Choose a random seed to generate a matrix
seed(28)
# Interesting examples:
# Seed 4 is not invertable (det=0)
# Seed 28 uses the switch rows operator (zero value on diagonal)
# Generate a matrix A with random input
A_len=3
A=zeros((A_len,A_len))
for i in range(A_len):
for j in range(A_len):
A[i][j]=int(random()*11)
A_0=A.copy()
print('Matrix A:')
print(A)
# Generate the identity tensor (starting point for the inverse)
A_inv=eye(len(A))
print()
print('Inverse A (starting point):')
print(A_inv)
# Start solving for the inverse
# All operations are performed on the matrix A, as well as the identity tensor to find its inverse.
# While det=1 the inverse exists, if det=0 the operation is aborted. (note: this function does not find the determinant)
det=1
for i in range(len(A)):
# If the number on the diagonal is nonzero, apply Gauss elimination to triangualize the matrix.
if (A[i][i]):
Gauss_explain()
# If the number on the diagonal is zero, check for nonzero terms below in the same column.
# In that case switch the rows and perform the Gauss elimination nonetheless.
elif (Switch_explain()):
Gauss_explain()
# If all numbers below the diagonal are also zero, the determinant = 0, and the inverse doesn't exist.
# The operation is aborted.
else:
det=0
print()
print('--- Det = 0, not invertable. ---')
break
if (det):
# Now we know the inverse exists
# We apply again Gauss elimination, this time to diagonalize the matrix.
for i in range(len(A)-1,0,-1):
for j in range(i-1,-1,-1):
Gauss_up_explain()
# Divide the rows of the matrix, so that we find the Identity tensor.
# This results also in the inverse for the second matrix.
for i in range(len(A)):
Divide_explain()
# Check if the matrix times its inverse gives the identity tensor
A_0#A_inv
The result might be:
Matrix A:
[[1. 1. 6.]
[1. 1. 5.]
[4. 2. 4.]]
Inverse A (starting point):
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
--- Gauss elimination: row 2 - 1.0 * row 1 ---
[[ 1. 1. 6.]
[ 0. 0. -1.]
[ 4. 2. 4.]]
[[ 1. 0. 0.]
[-1. 1. 0.]
[ 0. 0. 1.]]
--- Gauss elimination: row 3 - 4.0 * row 1 ---
[[ 1. 1. 6.]
[ 0. 0. -1.]
[ 0. -2. -20.]]
[[ 1. 0. 0.]
[-1. 1. 0.]
[-4. 0. 1.]]
--- Switch rows 2 and 3 ---
[[ 1. 1. 6.]
[ 0. -2. -20.]
[ 0. 0. -1.]]
[[ 1. 0. 0.]
[-4. 0. 1.]
[-1. 1. 0.]]
--- Gauss elimination (up): row 2 - 20.0 * row 3 ---
[[ 1. 1. 6.]
[ 0. -2. 0.]
[ 0. 0. -1.]]
[[ 1. 0. 0.]
[ 16. -20. 1.]
[ -1. 1. 0.]]
--- Gauss elimination (up): row 1 + 6.0 * row 3 ---
[[ 1. 1. 0.]
[ 0. -2. 0.]
[ 0. 0. -1.]]
[[ -5. 6. 0.]
[ 16. -20. 1.]
[ -1. 1. 0.]]
--- Gauss elimination (up): row 1 + 0.5 * row 2 ---
[[ 1. 0. 0.]
[ 0. -2. 0.]
[ 0. 0. -1.]]
[[ 3. -4. 0.5]
[ 16. -20. 1. ]
[ -1. 1. 0. ]]
--- Divide row 2 by -2.0 ---
[[ 1. 0. 0.]
[ 0. 1. 0.]
[ 0. 0. -1.]]
[[ 3. -4. 0.5]
[-8. 10. -0.5]
[-1. 1. 0. ]]
--- Divide row 3 by -1.0 ---
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[ 3. -4. 0.5]
[-8. 10. -0.5]
[ 1. -1. -0. ]]
In python, how to create a matrix or 2D array of N x N such that :
[A] Each Row has non-duplicate integers from 0 : N-1
And [B] Each Column has non-duplicate integers from 0:N-1
Example :
[[1 0 2]
[2 1 0]
[0 2 1]]
So I had a bit of a tinker with this question, this code seems to work
import numpy as np
N = 10
row = np.arange(N)
result = np.zeros((N, N))
for i in row:
result[i] = np.roll(row, i)
print(result)
output:
[[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[9. 0. 1. 2. 3. 4. 5. 6. 7. 8.]
[8. 9. 0. 1. 2. 3. 4. 5. 6. 7.]
[7. 8. 9. 0. 1. 2. 3. 4. 5. 6.]
[6. 7. 8. 9. 0. 1. 2. 3. 4. 5.]
[5. 6. 7. 8. 9. 0. 1. 2. 3. 4.]
[4. 5. 6. 7. 8. 9. 0. 1. 2. 3.]
[3. 4. 5. 6. 7. 8. 9. 0. 1. 2.]
[2. 3. 4. 5. 6. 7. 8. 9. 0. 1.]
[1. 2. 3. 4. 5. 6. 7. 8. 9. 0.]]
Ask away if you have any questions.
I have a NumPy array with missing values. I want to impute the mean of the nearest values vertically.
import numpy as np
arr = np.random.randint(0, 10, (10, 4)).astype(float)
arr[2, 0] = np.nan
arr[4, 3] = np.nan
arr[0, 2] = np.nan
print(arr)
[[ 5. 7. nan 4.] # should be 4
[ 2. 6. 4. 9.]
[nan 2. 5. 5.] # should be 4.5
[ 7. 0. 3. 8.]
[ 6. 4. 3. nan] # should be 4
[ 8. 1. 2. 0.]
[ 0. 0. 1. 1.]
[ 1. 2. 6. 6.]
[ 8. 1. 9. 7.]
[ 3. 5. 8. 8.]]
If you are open to using Pandas, pd.DataFrame.interpolate is easy to use. Set limit_direction if "interpolating" values at ends of array:
df = pd.DataFrame(arr).interpolate(limit_direction='both')
df.to_numpy() # back to a numpy array if needed (if using v0.24.0 or above)
Output:
array([[5. , 7. , 4. , 4. ],
[2. , 6. , 4. , 9. ],
[4.5, 2. , 5. , 5. ],
[7. , 0. , 3. , 8. ],
[6. , 4. , 3. , 4. ],
[8. , 1. , 2. , 0. ],
[0. , 0. , 1. , 1. ],
[1. , 2. , 6. , 6. ],
[8. , 1. , 9. , 7. ],
[3. , 5. , 8. , 8. ]])
import numpy as np
arr = np.random.randint(0, 10, (10, 4)).astype(float)
arr[2, 0] = np.nan
arr[4, 3] = np.nan
arr[0, 2] = np.nan
print(arr)
[[ 5. 7. nan 4.]
[ 2. 6. 4. 9.]
[nan 2. 5. 5.]
[ 7. 0. 3. 8.]
[ 6. 4. 3. nan]
[ 8. 1. 2. 0.]
[ 0. 0. 1. 1.]
[ 1. 2. 6. 6.]
[ 8. 1. 9. 7.]
[ 3. 5. 8. 8.]]
for x, y in np.argwhere(np.isnan(arr)):
sample = arr[np.maximum(x - 1, 0):np.minimum(x + 2, 20), y]
arr[x, y] = np.mean(sample[np.logical_not(np.isnan(sample))])
print(arr)
[[5. 7. 4. 4. ] # 3rd value here is mean(4)
[2. 6. 4. 9. ]
[4.5 2. 5. 5. ] # first value here is mean(2, 7)
[7. 0. 3. 8. ]
[6. 4. 3. 4. ] # 4th value here is mean(8, 0)
[8. 1. 2. 0. ]
[0. 0. 1. 1. ]
[1. 2. 6. 6. ]
[8. 1. 9. 7. ]
[3. 5. 8. 8. ]]