Specific type annotation for NumPy ndarray using mypy

What you are looking for is the numpy.typing.NDArray class: https://numpy.org/doc/stable/reference/typing.html#numpy.typing.NDArray numpy.typing.NDArray[A] is an alias for numpy.ndarray[Any, numpy.dtype[A]]: import numpy as np import numpy.typing as npt a: npt.NDArray[np.complex64] = np.zeros((3, 3), dtype=np.complex64) # reveal_type(a) # -> numpy.ndarray[Any, numpy.dtype[numpy.complexfloating[numpy.typing._32Bit, numpy.typing._32Bit]]] print(a) prints [[0.+0.j 0.+0.j 0.+0.j] [0.+0.j 0.+0.j 0.+0.j] [0.+0.j 0.+0.j 0.+0.j]] Note that even though you annotate … Read more

Numpy mean of nonzero values

Get the count of non-zeros in each row and use that for averaging the summation along each row. Thus, the implementation would look something like this – np.true_divide(matrix.sum(1),(matrix!=0).sum(1)) If you are on an older version of NumPy, you can use float conversion of the count to replace np.true_divide, like so – matrix.sum(1)/(matrix!=0).sum(1).astype(float) Sample run – … Read more

Cannot convert list to array: ValueError: only one element tensors can be converted to Python scalars

It seems like you have a list of tensors. For each tensor you can see its size() (no need to convert to list/numpy). If you insist, you can convert a tensor to numpy array using numpy(): Return a list of tensor shapes: >> [t.size() for t in my_list_of_tensors] Returns a list of numpy arrays: >> … Read more

Transforming a row vector into a column vector in Numpy

you can use the transpose operation to do this: Example: In [2]: a = np.array([[1,2], [3,4], [5,6]]) In [5]: a.shape Out[5]: (3, 2) In [6]: a_trans = a.T #or: np.transpose(a), a.transpose() In [8]: a_trans.shape Out[8]: (2, 3) In [7]: a_trans Out[7]: array([[1, 3, 5], [2, 4, 6]]) Note that the original array a will still … Read more

Deprecation status of the NumPy matrix class

tl; dr: the numpy.matrix class is getting deprecated. There are some high-profile libraries that depend on the class as a dependency (the largest one being scipy.sparse) which hinders proper short-term deprecation of the class, but users are strongly encouraged to use the ndarray class (usually created using the numpy.array convenience function) instead. With the introduction … Read more

Hata!: SQLSTATE[08004] [1040] Too many connections