Как найти след матрицы питон

numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)[source]#

Return the sum along diagonals of the array.

If a is 2-D, the sum along its diagonal with the given offset
is returned, i.e., the sum of elements a[i,i+offset] for all i.

If a has more than two dimensions, then the axes specified by axis1 and
axis2 are used to determine the 2-D sub-arrays whose traces are returned.
The shape of the resulting array is the same as that of a with axis1
and axis2 removed.

Parameters:
aarray_like

Input array, from which the diagonals are taken.

offsetint, optional

Offset of the diagonal from the main diagonal. Can be both positive
and negative. Defaults to 0.

axis1, axis2int, optional

Axes to be used as the first and second axis of the 2-D sub-arrays
from which the diagonals should be taken. Defaults are the first two
axes of a.

dtypedtype, optional

Determines the data-type of the returned array and of the accumulator
where the elements are summed. If dtype has the value None and a is
of integer type of precision less than the default integer
precision, then the default integer precision is used. Otherwise,
the precision is the same as that of a.

outndarray, optional

Array into which the output is placed. Its type is preserved and
it must be of the right shape to hold the output.

Returns:
sum_along_diagonalsndarray

If a is 2-D, the sum along the diagonal is returned. If a has
larger dimensions, then an array of sums along diagonals is returned.

Examples

>>> np.trace(np.eye(3))
3.0
>>> a = np.arange(8).reshape((2,2,2))
>>> np.trace(a)
array([6, 8])
>>> a = np.arange(24).reshape((2,2,2,3))
>>> np.trace(a).shape
(2, 3)

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    With the help of Numpy matrix.trace() method, we can find the sum of all the elements of diagonal of a matrix by using the matrix.trace() method.

    Syntax : matrix.trace()
    Return : Return sum of a diagonal elements of a matrix

    Example #1 :
    In this example we can see that by using matrix.trace() method can help us to find the sum of all the elements of a diagonal of given matrix.

    import numpy as np

    gfg = np.matrix('[4, 1; 12, 3]')

    geek = gfg.trace()

    print(geek)

    Example #2 :

    import numpy as np

    gfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]')

    geek = gfg.trace()

    print(geek)

    Last Updated :
    29 May, 2019

    Like Article

    Save Article

    Matrix is fun! Not the movie, but the one from mathematics. After having a decent understanding of the properties of matrices, one can very well tap into their potential & deploy them over a wide range of applications. Data encryption and password generation to name a few!

    Also read: Python Matrix Tutorial

    This article will help you to understand one of the many properties of matrices – the matrix trace. The trace aids in calculating the sum of the diagonal elements in any given matrix. Let’s get started by importing the numpy library using the below code.

    We shall further explore the trace( ) function through each of the following sections.

    • Syntax of trace( ) function
    • Calculating Trace for Two-Dimensional Arrays
    • Calculating Trace for Three-Dimensional Arrays
    • Using Offset for Calculating Trace

    Syntax of trace( ) function

    The trace( ) function sums up all the elements in the diagonal of any given N-dimensional array, but things just don’t end there. It also happens to be packed with a handful of features such as those given within the syntax below,

    numpy.trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None)
    

    where,

    • a – N-dimensional array for which the trace is to be calculated
    • offset – an optional construct used to offset the trace calculation from the main diagonal. Set to zero (0) by default, one can also use ‘+1’ or ‘-1’ to offset the main diagonal positively or negatively respectively
    • axis1 – an optional construct used to specify the first axis of the two-dimensional sub-arrays from which the diagonal is to be taken. Set to zero (0) by default.
    • axis2 – an optional construct used to specify the second axis of the two-dimensional sub-arrays from which the diagonal is to be taken. Set to one (1) by default.
    • dtype – an optional construct set to none by default, but could be used to specify the data type which is being used
    • out – an optional construct set to none by default, but could be used to store the result

    Calculating Trace for Two-Dimensional Arrays

    After importing the numpy library let us find the trace of a two-dimensional array using the code given below.

    ar1 = np.array([[12, 5],
                    [5, 9]], dtype = int)
    np.trace(ar1)
    

    Once the above code is run, the following computation happens in the back end for calculating the trace of the matrix given in the form of an array.

    • The first element of the first row from which the diagonal starts is added with the second element of the second row where the diagonal ends.
    • The sum of the two elements (i.e) 12+9 = 21 is then returned as the trace of the given input array.

    The final answer deduced in the last step as stated above can also be seen as the result in the below image when the code is run.

    Trace Calculated For A Two Dimensional Array

    Trace Calculated For A Two-Dimensional Array

    Calculating Trace for Three-Dimensional Arrays

    The same technique can also be deployed while calculating the trace of a three-dimensional array such as the one given below.

    ar2 = np.array([[2.1, 5.5, 8.8], [10.2, 7.3, 3.5], [4.7, 9.8, 6.3]], dtype=float)
    np.trace(ar2, dtype=float)
    

    Trace Calculated For A Three Dimensional Array

    Trace Calculated For A Three-Dimensional Array

    Since the data type has been specified the diagonal elements are added (2.1+7.3+6.3 = 15.7) & the result with the decimal value has been returned as the trace for the given input array.


    Using Offset for Calculating Trace

    Trace shall be calculated for the same array used in the above section, but with the diagonal being offset by ‘+1’.

    ar2 = np.array([[2.1, 5.5, 8.8], [10.2, 7.3, 3.5], [4.7, 9.8, 6.3]], dtype=float) 
    np.trace(ar2, offset=+1, dtype=float)
    

    Trace Calculated With Offset

    Trace Calculated With Offset

    The diagonal elements are 5.5 & 3.5 now, whose sum 9.0 is returned as the result!


    Conclusion

    Now that we have reached the end of this article, hope it has elaborated on how to use the trace( ) function from the numpy library to calculate the sum of diagonal elements of any given matrix. Here’s another article that explains the vdot( ) function from numpy in Python. There are numerous other enjoyable and equally informative articles in AskPython that might be of great help to those who are looking to level up in Python. Whilst you enjoy those, hasta luego!

    Возвращает сумму по диагоналям массива.

    Если a 2-D, возвращается сумма по его диагонали с заданным смещением, то есть сумма элементов a[i,i+offset] для всех i.

    Если a имеет более двух измерений, то оси, указанные в параметрах axis1 и axis2, используются для определения двумерных подмассивов, трассы которых возвращаются. Форма результирующего массива одно и то же, что и с axis1 и axis2 удалены. a

    Parameters
    aarray_like

    Входной массив,из которого берутся диагонали.

    offsetint, optional

    Смещение диагонали от главной диагонали.Может быть как положительным,так и отрицательным.По умолчанию 0.

    axis1, axis2 int, необязательно

    Оси, которые будут использоваться в качестве первой и второй оси двумерных подмассивов, из которых должны быть взяты диагонали. Значения по умолчанию являются первыми двумя осями . a

    dtypedtype, optional

    Определяет тип данных возвращаемого массива и аккумулятора, в котором суммируются элементы. Если dtype имеет значение None и a имеет целочисленный тип точности меньше, чем целочисленная точность по умолчанию, то используется целочисленная точность по умолчанию. В остальном точность такая же, как у a .

    outndarray, optional

    Массив,в который помещается выход.Его тип сохраняется,и он должен иметь правильную форму,чтобы удерживать выход.

    Returns
    sum_along_diagonalsndarray

    Если a 2-D, возвращается сумма по диагонали. Если имеет большие размеры, то массив сумм вдоль диагоналей возвращается. a

    Examples

    >>> np.trace(np.eye(3))
    3.0
    >>> a = np.arange(8).reshape((2,2,2))
    >>> np.trace(a)
    array([6, 8])
    
    >>> a = np.arange(24).reshape((2,2,2,3))
    >>> np.trace(a).shape
    (2, 3)
    

    Python has a powerful module named Numpy. At the same time, its specialization is in Data science, used in many ways. The in-built functions are versatile. So we provide tutorials for its various parts for you to practice. In this, we will see about numpy trace. The base of it’s working on matrix work, so a new field holds with python.

    What numpy trace is ?

    Numpy matrix.trace() method, we can find the sum of all the diagonal elements of a matrix by using the matrix.trace() method. This method returns the sum along diagonals of the array. The sum along with diagonal returns for a 2D array with a given offset using this method.

    For a 2-D array =

    00 01
    10 11
    A

    And if we had to find the sum of all diagonal elements i.e.(A[00] + A[11]) then we had to use numpy.trace().

    As per NumPy.org, when an array has more than two dimensions, we use axes specified by axis1 and axis2. These axes determine the 2-D sub-arrays, then the method finds their traces. The shape of the resulting array is the same as that of a with axis1 and axis2 removed.

    Syntax of Numpy Trace

    The syntax with all parameters is:

    numpy.trace(arr, offset=0, axis1=0, axis2=1, dtype=None, out
    

    But we usually use only:

    numpy.trace(arr)
    #or
    numpy.matrix.trace()
    #if array predeclared using numpy
    array.trace()
    

    Parameters Used in Numpy Trace

    Parameter Mandatory or notmatrix
    a mandatory
    offset optional
    axis1 optional
    axis2 optional
    dtype optional
    out optional

    a : Array_like / matrix

    ‘a’ is the prime parameter. This input is all that is enough for evaluation—input array or object. The method tests elements of the array. This array is considered matrix and written in that form.

    offset

    Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults to 0.

    axis1/axis2

     The first and second axis of the 2D sub-arrays is the axes providing the diagonals required. The default values are the first two axes of a. The data type is int

    dtype

    This parameter determines the data type of the returned array, and the accumulator sums the items. If the dtype has the value None and a is of integer precision less than the default integer precision, then use the default integer precision. Otherwise, the accuracy is the same as that of a.

    out

    The data type is array_like and optional to use. This parameter makes the output array with the same dimensions as the Input array, placed with the result. It has the same shape as the planned performance and maintains its form. Array sets the output. Parameter preserves its type, and it must be of the right shape to hold the result.

    Return Value of numpy trace

    Return the sum along diagonals of the array. In the form of ndarray as 

    sum_along_diagonals. If a is 2-D, then we get the sum along the diagonal. If a has larger dimensions, then an array of sums along diagonals is returned.

    Examples for Understanding

    firstly we import numpy as:

    then either we create an array or directly use it with the trace method:

    arr = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
    arr
    array([[1., 2., 3.],
           [4., 5., 6.],
           [7., 8., 9.]])
    arr.trace()
    15.0
    np.trace(arr)
    15.0
    

    You may get another type of output if done in the following way:

    arr = = np.matrix('[1,2,3; 4,5,6;7,8,9]') 
    arr
    matrix([[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]])
    arr.trace()
    [[15]]
    

    another example:

    a = np.arange(24).reshape((2,2,2,3))
    a
    array([[[[ 0,  1,  2],
             [ 3,  4,  5]],
    
            [[ 6,  7,  8],
             [ 9, 10, 11]]],
    
    
           [[[12, 13, 14],
             [15, 16, 17]],
    
            [[18, 19, 20],
             [21, 22, 23]]]])
    np.trace(a)
    array([[18, 20, 22],
           [24, 26, 28]])
    np.trace(a).shape
    (2, 3)
    

    Now you would understand the trace method easily.

    What’s Next?

    NumPy is very powerful and incredibly essential for information science in Python. That being true, if you are interested in data science in Python, you really ought to find out more about Python.

    You might like our following tutorials on numpy.

    • Mean: Implementation and Importance
    • Using Random Function to Create Random Data
    • Reshape: Reshaping Arrays With Ease
    • In-depth Explanation of np.power() With Examples
    • Clip Function

    Conclusion

    Numpy has an extensive range of applications. This method is fun to use and varies places to use. Matrix is not so attractive topic in math but of very use in ML. Trace optimizes the use.

    Still have any doubts or questions do let me know in the comment section below. I will try to help you as soon as possible.

    Happy Pythoning!

    Понравилась статья? Поделить с друзьями:
  • Как найти две четвертые части квадрата
  • Как найти кодовое слово в сбербанке договоре
  • Газовый счетчик свистит как исправить
  • Провисла деревянная дверь как исправить
  • Годовой отчет компании как составить