How to set the number of decimals of results in Python - python-3.x

I'm doing matrix factorization whose output matrix has non-integer entries. To make the display more compact, I would like to ask how to limit the number of decimals of results. Thank you so much!
import numpy as np
import scipy.linalg as la
A = np.array([[1, 0, 8, 7, 8, 1],
[0, 1, 2, 8, 9, 2],
[5, 1, 0, 6, 10, 3],
[5, 4, 4, 8, 10, 4]])
(P, L, U) = la.lu(A)
F = np.array(sorted(U, key=lambda x: tuple(x!=0), reverse=False))
print(F)
[[ 0. 0. 0. 6.85483871 8.51612903 1.62903226]
[ 0. 0. 8.26666667 5.93333333 6. 0.46666667]
[ 0. 3. 4. 2. 0. 1. ]
[ 5. 1. 0. 6. 10. 3. ]]
PS: I would like to ask for a global setting instead of repeating apply the function round to each output.

You can use numpy.around:
import numpy as np
import scipy.linalg as la
A = np.array([[1, 0, 8, 7, 8, 1],
[0, 1, 2, 8, 9, 2],
[5, 1, 0, 6, 10, 3],
[5, 4, 4, 8, 10, 4]])
(P, L, U) = la.lu(A)
F = np.array(sorted(U, key=lambda x: tuple(x!=0), reverse=False))
F = list(map(lambda x: np.around(x,2),F)) # 2 here is the number of decimals
print(F)

Related

how to pad a text after build the vocab in pytorch

I used torchtext vocab to convert the text to index, but which function should I use to make all the index list be the same length before I send them to the net?
For example I have 2 texts:
I am a good man
I would like a coffee please
After vocab:
[1, 3, 2, 5, 7]
[1, 9, 6, 2, 4, 8]
And what I want is:
[1, 3, 2, 5, 7, 0]
[1, 9, 6, 2, 4, 8]
It is easy to understand by looking at the following example.
Code:
import torch
v = [
[0,2],
[0,1,2],
[3,3,3,3]
]
torch.nn.utils.rnn.pad_sequence([torch.tensor(p) for p in v], batch_first=True)
Result:
tensor([[0, 2, 0, 0],
[0, 1, 2, 0],
[3, 3, 3, 3]])

3D matrix addition python

I am trying to add 3D matrix but third loop is not starting from 0.
Here shape of matrix is (2,3,3).
Code:
for i in range(0,r):
for j in range(0,c):
for l in range(0,k):
sum[i][j][k]=A1[i][j][k]+A2[i][j][k]
Output:
IndexError: index 3 is out of bounds for axis 0 with size 3
For element-wise addition of two matrices, you can simply use the + operator between two numpy arrays:
#create two matrices of random integers
matrix1 = np.random.randint(10, size=(2,3,3))
matrix2 = np.random.randint(10, size=(2,3,3))
#add the two matrices element-wise
sum_matrix = matrix1 + matrix2
print(matrix1, matrix2, sum_matrix, sep='\n__________\n')
I don't get IndexError. Maybe you post your whole code?
This is my code:
arr1 = [[[2, 4, 8], [7, 7, 1], [4, 9, 0]], [[5, 0, 0], [3, 8, 6], [0, 5, 8]]]
arr2 = [[[3, 8, 0], [1, 5, 2], [0, 3, 9]], [[9, 7, 7], [1, 2, 5], [1, 1, 3]]]
sumArr = [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0],[0, 0, 0]]]
for i in range(2): #can also use range(0,2)
for j in range(3):
for k in range(3):
sumArr[i][j][k]=arr1[i][j][k]+arr2[i][j][k]
print(sumArr)
By the way, is it necessary to use for loop?
If not, you can use numpy library.
import numpy as np
Convert your manual array to numpy matrix array, then do addition.
arr1 = [[[2, 4, 8], [7, 7, 1], [4, 9, 0]], [[5, 0, 0], [3, 8, 6], [0, 5, 8]]]
arr2 = [[[3, 8, 0], [1, 5, 2], [0, 3, 9]], [[9, 7, 7], [1, 2, 5], [1, 1, 3]]]
m1 = np.array(arr1)
m2 = np.array(arr2)
print("M1: \n", m1)
print("M2: \n", m2)
print("Sum: \n", m1 + m2)
You iterate with 'l' in the third loop but to access in list, you used k. As a result, your code is trying to access k-th index which doesn't exists, and you're getting an error.
Use this:
for i in range(0, r):
for j in range(0, c):
for l in range(0, k):
sum[i][j][l] = A1[i][j][l] + A2[i][j][l]

How to get the number of rows if you have both 1D and 2D arrays?

I have two arrays as follows and would like to get the number of rows by function .shape.
X = np.array([0, 4, 3, 5, 1, 2])
Y = np.array([[-1, 0, 4, 4],
[ 1, 0, 5, 0],
[ 2, 7, 4, 0],
[ 3, 0, 4, 9],
[ 4, 6, 4, 0]])
X.shape[0]
Y.shape[0]
The result is
6
5
Because X is a matrix with 1 row, I expect X.shape[0] returns 1. However, it returns 6 which is the number of columns. Could you please suggest a function to achieve my goal?
From #Divakar's comment, the command to achieve this goal is np.atleast_2d.

Array conforming shape of a given variable

I need to do some calculations with a NetCDF file.
So I have two variables with following dimensions and sizes:
A [time | 1] x [lev | 12] x [lat | 84] x [lon | 228]
B [lev | 12]
What I need is to produce a new array, C, that is shaped as (1,12,84,228) where B contents are propagated to all dimensions of A.
Usually, this is easily done in NCL with the conform function. I am not sure what is the equivalent of this in Python.
Thank you.
The numpy.broadcast_to function can do something like this, although in this case it does require B to have a couple of extra trailing size 1 dimension added to it to satisfy the numpy broadcasting rules
>>> import numpy
>>> B = numpy.arange(12).reshape(12, 1, 1)
>>> B
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> B = B.reshape(12, 1, 1)
>>> B.shape
(12, 1, 1)
>>> C = numpy.broadcast_to(b, (1, 12, 84, 228))
>>> C.shape
(1, 12, 84, 228)
>>> C[0, :, 0, 0]
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
>>> C[-1, :, -1, -1]
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

How to find a column in a ndarray

Say i have a array
x = array([[ 0, 1, 2, 5],
[ 3, 4, 5, 5],
[ 6, 7, 8, 5],
[ 9, 10, 11, 5]])
I need to find the position/index of [3, 4, 5, 5]. In this case, it should return 1.
Create an array y that has all rows equal to the one you are looking for. Then, do an elementwise comparison x == y and find the rows where you get all True.
import numpy as np
x1 = np.array([[0, 1, 2, 5], [3, 4, 5, 5],
[6, 7, 8, 5], [9, 10, 11, 5]])
y1 = np.array([[3, 4, 5, 5]] * 4)
print(np.where(np.all(x1 == y1, axis=1))[0]) # => [1]
This approach returns an array of the indices where the desired row appears.
y2 = np.array([[1, 1, 1, 1]] * 4)
print(np.where(np.all(x1 == y2, axis=1))[0]) # => []
x2 = np.array([[3, 4, 5, 5], [3, 4, 5, 5],
[6, 7, 8, 5], [9, 10, 11, 5]])
print(np.where(np.all(x2 == y1, axis=1))[0]) # => [0 1]

Resources