Деление матриц python numpy

numpy.divide#

Divisor array. If x1.shape != x2.shape , they must be broadcastable to a common shape (which becomes the shape of the output).

out ndarray, None, or tuple of ndarray and None, optional

A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

where array_like, optional

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None , locations within it where the condition is False will remain uninitialized.

For other keyword-only arguments, see the ufunc docs .

Returns : y ndarray or scalar

The quotient x1/x2 , element-wise. This is a scalar if both x1 and x2 are scalars.

Set whether to raise or warn on overflow, underflow and division by zero.

Equivalent to x1 / x2 in terms of array-broadcasting.

The true_divide(x1, x2) function is an alias for divide(x1, x2) .

>>> np.divide(2.0, 4.0) 0.5 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.divide(x1, x2) array([[nan, 1. , 1. ], [inf, 4. , 2.5], [inf, 7. , 4. ]]) 

The / operator can be used as a shorthand for np.divide on ndarrays.

>>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = 2 * np.ones(3) >>> x1 / x2 array([[0. , 0.5, 1. ], [1.5, 2. , 2.5], [3. , 3.5, 4. ]]) 

Источник

Python Matrix — учебное пособие по матрицам

Мы можем реализовать матрицу Python в форме 2-го списка или 2-го массива. Для выполнения операций с Python Matrix нам необходимо импортировать Python NumPy Module.

Matrix важен в области статистики, обработки данных, обработки изображений и т. д.

Python Matrix объяснение

Создание матрицы Python

Матрицу Python можно создать одним из следующих способов:

1 С использованием списков

numpy.array() можно использовать для создания массива, используя списки в качестве входных данных.

import numpy input_arr = numpy.array([[ 10, 20, 30],[ 40, 50, 60]]) print(input_arr)

Как видно выше, выходные данные представляют собой двумерную матрицу с заданным набором входных данных в виде списка.

2 С помощью функции numpy.arange()

numpy.arange() вместе со списком входов.

import numpy print(numpy.array([numpy.arange(10,15), numpy.arange(15,20)]))
[[10 11 12 13 14] [15 16 17 18 19]]

3 С помощью функции numpy.matrix().

Функция numpy.matrix() , ее синтаксис:

  • input: элементы input для формирования матрицы.
  • dtype: тип данных соответствующего вывода.
import numpy as p matA = p.matrix([[10, 20], [30, 40]]) print('MatrixA:\n', matA) matB = p.matrix('[10,20;30,40]', dtype=p.int32) # Setting the data-type to int print('\nMatrixB:\n', matB)
MatrixA: [[10 20] [30 40]] MatrixB: [[10 20] [30 40]]

Сложение

Операцию сложения матриц можно выполнить следующими способами:

1 Традиционный метод

В этом традиционном методе мы в основном берем ввод от пользователя, а затем выполняем операцию сложения с использованием циклов for (для обхода элементов матрицы) и оператора ‘+’.

import numpy as p ar1 = p.matrix([[11, 22], [33, 44]]) ar2 = p.matrix([[55, 66], [77, 88]]) res = p.matrix(p.zeros((2,2))) print('Matrix ar1 :\n', ar1) print('\nMatrix ar2 :\n', ar2) # traditional code for x in range(ar1.shape[1]): for y in range(ar2.shape[0]): res[x, y] = ar1[x, y] + ar2[x, y] print('\nResult :\n', res)

Примечание. Matrix.shape возвращает размеры конкретной матрицы.

Matrix ar1 : [[11 22] [33 44]] Matrix ar2 : [[55 66] [77 88]] Result : [[ 66. 88.] [ 110. 132.]]

2 Использование оператора «+»

Этот метод обеспечивает большую эффективность кода, поскольку он уменьшает LOC (количество строк кода) и, таким образом, оптимизирует код.

import numpy as p ar1 = p.matrix([[11, 22], [33, 44]]) ar2 = p.matrix([[55, 66], [77, 88]]) res = p.matrix(p.zeros((2,2))) print('Matrix ar1 :\n', ar1) print('\nMatrix ar2 :\n', ar2) res = ar1 + ar2 # using '+' operator print('\nResult :\n', res)
Matrix ar1 : [[11 22] [33 44]] Matrix ar2 : [[55 66] [77 88]] Result : [[ 66 88] [110 132]]

Умножение матриц

Умножение матриц в Python можно обеспечить следующими способами:

Скалярное произведение

В скалярном произведении постоянное значение умножается на каждый элемент матрицы.

Оператор ‘*’ используется для умножения скалярного значения на элементы входной матрицы.

import numpy as p matA = p.matrix([[11, 22], [33, 44]]) print("Matrix A:\n", matA) print("Scalar Product of Matrix A:\n", matA * 10)
Matrix A: [[11 22] [33 44]] Scalar Product of Matrix A: [[110 220] [330 440]]

Функция numpy.dot()

Как упоминалось выше, мы можем использовать оператор ‘*’ только для скалярного умножения. Чтобы продолжить умножение матриц, нам нужно использовать numpy.dot() .

Функция numpy.dot() принимает массивы NumPy в качестве значений параметров и выполняет умножение в соответствии с основными правилами умножения матриц.

import numpy as p matA = p.matrix([[11, 22], [33, 44]]) matB = p.matrix([[2,2], [2,2]]) print("Matrix A:\n", matA) print("Matrix B:\n", matB) print("Dot Product of Matrix A and Matrix B:\n", p.dot(matA, matB))
Matrix A: [[11 22] [33 44]] Matrix B: [[2 2] [2 2]] Dot Product of Matrix A and Matrix B: [[ 66 66] [154 154]]

Вычитание

Оператор ‘-‘ используется для выполнения вычитания матриц.

import numpy as p matA = p.matrix([[11, 22], [33, 44]]) matB = p.matrix([[2,2], [2,2]]) print("Matrix A:\n", matA) print("Matrix B:\n", matB) print("Subtraction of Matrix A and Matrix B:\n",(matA - matB))
Matrix A: [[11 22] [33 44]] Matrix B: [[2 2] [2 2]] Subtraction of Matrix A and Matrix B: [[ 9 20] [31 42]]

Деление

Скалярное деление может выполняться на элементах матрицы в Python с помощью оператора ‘/’.

Оператор ‘/’ делит каждый элемент матрицы на скалярное / постоянное значение.

import numpy as p matB = p.matrix([[2,2], [2,2]]) print("Matrix B:\n", matB) print("Matrix B after Scalar Division operation:\n",(matB/2))
Matrix B: [[2 2] [2 2]] Matrix B after Scalar Division operation: [[ 1. 1.] [ 1. 1.]]

Транспонирование матрицы

Транспонирование матрицы в основном включает в себя переворачивание матрицы по соответствующим диагоналям, т. е. Меняет местами строки и столбцы входной матрицы. Строки становятся столбцами и наоборот.

Например: давайте рассмотрим матрицу A с размерами 3 × 2, т.е. 3 строки и 2 столбца. После выполнения операции транспонирования размеры матрицы A будут 2 × 3, т.е. 2 строки и 3 столбца.

Matrix.T основном выполняет транспонирование входной матрицы и создает новую в результате операции транспонирования.

import numpy matA = numpy.array([numpy.arange(10,15), numpy.arange(15,20)]) print("Original Matrix A:\n") print(matA) print('\nDimensions of the original MatrixA: ',matA.shape) print("\nTranspose of Matrix A:\n ") res = matA.T print(res) print('\nDimensions of the Matrix A after performing the Transpose Operation: ',res.shape)
Original Matrix A: [[10 11 12 13 14] [15 16 17 18 19]] Dimensions of the original MatrixA: (2, 5) Transpose of Matrix A: [[10 15] [11 16] [12 17] [13 18] [14 19]] Dimensions of the Matrix A after performing the Transpose Operation: (5, 2)

В приведенном выше фрагменте кода я создал матрицу размером 2 × 5, т.е. 2 строки и 5 столбцов.

После выполнения операции транспонирования размеры результирующей матрицы составляют 5 × 2, то есть 5 строк и 2 столбца.

Экспонента

Экспонента в матрице вычисляется поэлементно, то есть показатель степени каждого элемента вычисляется путем возведения элемента в степень входного скалярного значения.

import numpy matA = numpy.array([numpy.arange(0,2), numpy.arange(2,4)]) print("Original Matrix A:\n") print(matA) print("Exponent of the input matrix:\n") print(matA ** 2) # finding the exponent of every element of the matrix
Original Matrix A: [[0 1] [2 3]] Exponent of the input matrix: [[0 1] [4 9]]

В приведенном выше фрагменте кода мы выяснили показатель степени каждого элемента входной матрицы, возведя его в степень 2.

Операция умножения с использованием методов NumPy

Для выполнения умножения матрицы NumPy можно использовать следующие методы:

  • Использование метода multiply();
  • метода matmul();
  • Использование метода dot() — уже описано в этой статье.

Метод 1: использование метода multiply()

Метод numpy.multiply() выполняет поэлементное умножение входной матрицы.

import numpy as p matA = p.matrix([[10, 20], [30, 40]]) print('MatrixA:\n', matA) matB = p.matrix('[10,20;30,40]', dtype=p.int32) # Setting the data-type to int print('\nMatrixB:\n', matB) print("Matrix multplication using numpy.matrix() method") res = p.multiply(matA,matB) print(res)
MatrixA: [[10 20] [30 40]] MatrixB: [[10 20] [30 40]] Matrix multplication using numpy.matrix() method [[ 100 400] [ 900 1600]]

Метод 2: использование метода matmul()

Метод numpy.matmul() выполняет матричное произведение.

import numpy as p matA = p.matrix([[10, 20], [30, 40]]) print('MatrixA:\n', matA) matB = p.matrix('[10,20;30,40]', dtype=p.int32) # Setting the data-type to int print('\nMatrixB:\n', matB) print("Matrix multplication using numpy.matmul() method") res = p.matmul(matA,matB) print(res)
MatrixA: [[10 20] [30 40]] MatrixB: [[10 20] [30 40]] Matrix multplication using numpy.matmul() method [[ 700 1000] [1500 2200]]

Транспонирование матрицы NumPy

Функция numpy.transpose() выполняет транспонирование.

import numpy matA = numpy.array([numpy.arange(10,15), numpy.arange(15,20)]) print("Original Matrix A:\n") print(matA) print('\nDimensions of the original MatrixA: ',matA.shape) print("\nTranspose of Matrix A:\n ") res = matA.transpose() print(res) print('\nDimensions of the Matrix A after performing the Transpose Operation: ',res.shape)
Original Matrix A: [[10 11 12 13 14] [15 16 17 18 19]] Dimensions of the original MatrixA: (2, 5) Transpose of Matrix A: [[10 15] [11 16] [12 17] [13 18] [14 19]] Dimensions of the Matrix A after performing the Transpose Operation: (5, 2)

Источник

Element-Wise Division в Python NumPy

Element-Wise Division в Python NumPy

  1. NumPy Element-Wise Division с функцией numpy.divide()
  2. NumPy Element-Wise Division с оператором /

В этом руководстве будут представлены методы для выполнения поэлементного деления массивов NumPy в Python.

NumPy Element-Wise Division с функцией numpy.divide()

Если у нас есть два массива и мы хотим разделить каждый элемент первого массива на каждый элемент второго массива, мы можем использовать функцию numpy.divide() . Функция numpy.divide() выполняет поэлементное деление на массивы NumPy. Функция numpy.divide() принимает в качестве аргументов массив делимых, массив делителей и выходной массив и сохраняет результаты деления внутри выходного массива. См. Следующий пример кода.

import numpy as np  array1 = np.array([10,20,30]) array2 = np.array([2,4,6])  np.divide(array1, array2, array3) print(array3) 

В приведенном выше коде мы сначала создали два массива NumPy, массив делимых array1 и массив делителей array2 с помощью функции np.array() . Затем мы разделили массив array1 на array2 и сохранили результаты внутри массива NumPy array3 с помощью функции np.divide() .

NumPy Element-Wise Division с оператором /

Мы также можем использовать оператор / для поэлементного деления массивов NumPy в Python. Оператор / является сокращением функции np.true_divide() в Python. Мы можем использовать оператор / , чтобы разделить один массив на другой и сохранить результаты внутри третьего массива. См. Следующий пример кода.

import numpy as np  array1 = np.array([10,20,30]) array2 = np.array([2,4,6])  array3 = array1/array2 print(array3) 

Мы разделили массив array1 на array2 и сохранили результаты внутри массива NumPy array3 с помощью оператора / .

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Источник

Читайте также:  Test php smtp mail
Оцените статью