I am trying to use a single line of code to make a matrix with zeros except a custom value for the diagonals. I am able to do it like the code I put below, but am wondering if I can do it by only using np.eye?
import numpy as np
a = np.eye(4,4 k=0)
np.fill_diagonal (a,4)
print(a)
try the identity matrix in numpy module:
a=np.identity(10)*4
import numpy as np
a = np.eye(4)*4
print(a)
I would avoid np.eye() altogether and just use np.fill_diagonal() on a zeroed matrix, if you are not using any of its features:
import numpy as np
def value_eye_fill(value, n):
result = np.zeros((n, n))
np.fill_diagonal(result, value)
return result
That should be the fastest approach for larger inputs, within NumPy.
Of course you can also use np.eye() and avoid np.fill_diagonal() by just multiplying the value by the result of np.eye():
import numpy as np
def value_eye_fill(value, n):
return value * np.eye(n)
Related
How to convert the Matlab code
v = [1: n]
to pytorch?
Writing a whole loop for that seems inefficient.
You can directly use the arange method from Pytorch.
torch_v = torch.arange(1,n)
Reference: https://pytorch.org/docs/master/torch.html?highlight=arange#torch.arange
You form a sequence of consecutive numbers in python
import numpy as np
v= np.arange(1,n)
if you want a torch tensor you can transform the numpy array like this:
torch_v = torch.from_numpy(v)
I have a numpy array of dimension (i, j) in which I would like to add up the first dimension to receive a array of shape (j,). Normally, I'd use NumPy's own sum
import numpy
a = numpy.random.rand(100, 77)
numpy.sum(a, axis=0)
but in my case it doesn't cut it: Some of the sums are very ill-conditioned, so the computed results only have a few correct digits.
math.fsum is fantastic at keeping the errors at bay, but it only applies to iterables of one dimension. numpy.vectorize doesn't do the job either.
How to efficiently apply math.fsum to an array of multiply dimensions?
This one works fast enough for me.
import numpy
import math
a = numpy.random.rand(100, 77)
a = numpy.swapaxes(a, 0, 1)
a = numpy.array([math.fsum(row) for row in a])
Hopefully it's the axis you are looking for (returns 77 sums).
Check out the signature keyword to vectorize.
_math_fsum_vec = numpy.vectorize(math.fsum, signature='(m)->()')
Unfortunately, it's slower than the for solution:
Code to reproduce the plot:
import math
import numpy
import perfplot
_math_fsum_vec = numpy.vectorize(math.fsum, signature='(m)->()')
def fsum_vectorize(a):
return _math_fsum_vec(a.T).T
def fsum_for(a):
return numpy.array([math.fsum(row) for row in a.T])
perfplot.save(
'fsum.png',
setup=lambda n: numpy.random.rand(n, 100),
kernels=[fsum_vectorize, fsum_for],
n_range=[2**k for k in range(12)],
logx=True,
logy=True,
)
let us say I have a numpy matrix A that is of size Nx2. What I am doing, is computing the 4-quadrant inverse tangent of the first column, and the second column, as so:
import math
for i in xrange(A.shape[0]):
phase[i] = math.atan2(A[i,0], A[i,1])
I would however like to do this in a vectorized manner. How can I do that? The math.atan2() function does not seem to support vectorization.
Thanks!
It looks to me like it should just be:
import numpy as np
phase = np.arctan2(A[:, 0], A[:, 1])
Or possibly (if phase is a different length than A for some odd reason):
phase[:len(A)] = np.arctan2(A[:, 0], A[:, 1])
In other words, don't use math.atan2, use numpy.arctan2 since numpy functions are generally vectorized versions of their math counterparts.
I have encountered the following function in MATLAB that sequentially flips all of the dimensions in a matrix:
function X=flipall(X)
for i=1:ndims(X)
X = flipdim(X,i);
end
end
Where X has dimensions (M,N,P) = (24,24,100). How can I do this in Python, given that X is a NumPy array?
The equivalent to flipdim in MATLAB is flip in numpy. Be advised that this is only available in version 1.12.0.
Therefore, it's simply:
import numpy as np
def flipall(X):
Xcopy = X.copy()
for i in range(X.ndim):
Xcopy = np.flip(Xcopy, i)
return Xcopy
As such, you'd simply call it like so:
Xflip = flipall(X)
However, if you know a priori that you have only three dimensions, you can hard code the operation by simply doing:
def flipall(X):
return X[::-1,::-1,::-1]
This flips each dimension one right after the other.
If you don't have version 1.12.0 (thanks to user hpaulj), you can use slice to do the same operation:
import numpy as np
def flipall(X):
return X[[slice(None,None,-1) for _ in X.shape]]
Is it possible to apply for example numpy.exp or similar pointwise operators to all elements in a scipy.sparse.lil_matrix or another sparse matrix format?
import numpy
from scipy.sparse import lil_matrix
x = numpy.ones((10,10))
y = numpy.exp(x)
x = lil_matrix(numpy.ones((10,10)))
# y = ????
numpy.exp(x) or scipy.exp(x) yields an AttributeError, and numpy.exp(x.data) yields the same.
thanks!
I do not know the full details, but converting to another type works, at least when using the array of non zero elements:
xcsc = x.tocsc()
numpy.exp(xcsc.data) # works