Python произведение двух массивов

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

Чтобы вычислить скалярное произведение массивов numpy nd, вы можете использовать функцию numpy.dot() в Python. Она принимает в качестве аргументов два массива numpy, вычисляет их скалярное произведение и возвращает результат.

Синтаксис

Синтаксис метода numpy.dot():

Параметр Описание
a [обязательный] Первый аргумент для операции скалярного произведения.
b [обязательный] Второй аргумент для операции скалярного произведения.
out [необязательно] Этот аргумент используется для оценки производительности. Это должен быть C-смежный массив, а dtype должен быть тем dtype, который будет возвращен для точки (a, b).

На основе размеров входного массива

В следующей таблице указывается тип выполняемой операции на основе размеров входных массивов: a и b.

Размерности «a» и «b» Выход
Нулевое измерение (скалярное) Умножение двух скаляров a и b.
Одномерные массивы (вектор) Внутреннее произведение векторов.
Двумерные массивы (матрица) Умножение матриц.
a: N-мерный массив, b: 1-мерный массив Суммируйте произведение по последней оси a и b.
a: N-мерный массив, b: M-мерный массив (M> = 2) Суммируйте произведение по последней оси a и предпоследней оси b.

Пример 1: произведение скаляров с несколькими точками

В этом примере мы берем два скаляра и вычисляем их скалярное произведение с помощью функции numpy.dot(). Точечное произведение с двумя скалярами в качестве аргументов возвращает умножение двух скаляров.

import numpy as np a = 3 b = 4 output = np.dot(a,b) print(output)

Пример 2: произведение числовых точек одномерных массивов

В этом примере мы берем два numpy одномерных массива и вычисляем их скалярное произведение с помощью функции numpy.dot(). Мы уже знаем, что если входные аргументы метода dot() одномерные, то выход будет внутренним произведением этих двух векторов (поскольку это одномерные массивы).

import numpy as np #initialize arrays A = np.array([2, 1, 5, 4]) B = np.array([3, 4, 7, 8]) #dot product output = np.dot(A, B) print(output)
output = [2, 1, 5, 4].[3, 4, 7, 8] = 2*3 + 1*4 + 5*7 + 4*8 = 77

Пример 3: произведение числовых точек двумерных массивов

В этом примере мы берем два двумерных массива numpy и вычисляем их скалярное произведение. Точечное произведение двух двумерных массивов возвращает матричное умножение двух входных массивов.

import numpy as np #initialize arrays A = np.array([[2, 1], [5, 4]]) B = np.array([[3, 4], [7, 8]]) #dot product output = np.dot(A, B) print(output)
output = [[2, 1], [5, 4]].[[3, 4], [7, 8]] = [[2*3+1*7, 2*4+1*8], [5*3+4*7, 5*4+4*8]] = [[13, 16], [43, 52]]

В этом руководстве на примерах Python мы узнали, как вычислить скалярное произведение массивов numpy с помощью примеров программ.

Источник

Python: Multiply Lists (6 Different Ways)

Python Multiply Lists Cover Image

In this tutorial, you’ll learn how to use Python to multiply lists, including how to multiply list elements by a number and multiply lists with one another. By the end of this tutorial, you’ll have learned how to multiply each element by a number, including how to do this with for loops, list comprehensions and numpy array multiplication. Then, you’ll learn how to multiply lists element-wise, using for loops, list comprehensions, the Python zip() function, and the numpy np.multiply() function.

Читайте также:  Dividing lines in html

Python lists are a powerful data structure that are used in many different applications. Knowing how to multiply them will be an invaluable tool as you progress on your data science journey. For example, you may have a list that contains the different values for a radius of a circle and want to calculate the area of the circles. You may also have a list of incomes and want to calculate how much of a bonus to give.

The Quick Answer: Use Numpy

Quick Answer - Python Multiply Lists By Number or Element-Wise

Multiply Two Python Lists by a Number Using Numpy

Let’s start off by learning how to multiply two Python lists by a numer using numpy. The benefit of this approach is that it makes it specifically clear to a reader what you’re hoping to accomplish. Numpy uses arrays, which are list-like structures that allow us to manipulate the data in them in. Numpy comes with many different methods and functions, but in this case, we can simply multiply the array by a scalar.

In the code below, you’ll learn how to multiply a Python list by a number using numpy:

# Multiply a Python List by a Number Using Numpy import numpy as np numbers = [1, 2, 3, 4, 5] array = np.array(numbers) * 2 multiplied = list(array) print(multiplied) # Returns: [2, 4, 6, 8, 10]

Let’s break down what we did here:

  1. We converted the list into a numpy array.
  2. We then multiplied the array by a number, 2
  3. Finally, we converted the array back into a list

The benefit of this approach, while it involves importing numpy, is that it’s immediately clear what you’re hoping to accomplish with your code. This allows us simplify the process of later understanding our code.

In the next section, you’ll learn how to use a Python for loop to multiply a list by a number.

Multiply Two Python Lists by a Number Using a For Loop

In this section, you’ll learn how to use a Python for loop to multiply a list by a number. Python for loops allow us to iterate over over iterable objects, such as lists. We can use for loops to loop over each item in a list and then multiply by it by a given number.

Let’s see how we can multiply a list by a number using a Python for loop:

# Multiply a Python List by a Number Using a for loop numbers = [1, 2, 3, 4, 5] multiplied = [] for number in numbers: multiplied.append(number * 2) print(multiplied) # Returns: [2, 4, 6, 8, 10]

Let’s break down what we have done here: We instantiated two lists, one that contains our numbers and an empty list to hold our multiplied values. We then loop over each item in the list that contains our number. We append the multiplied number to our list that holds our multiplied values.

Python for loops are intuitive ways of looping over lists, but they require us to instantiate a list first and use more lines of code than necessary. To trim down our code and make it more readable in the process, you’ll learn about Python list comprehensions in the next section.

Читайте также:  Java task class example

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Multiply Two Python Lists by a Number Using a List Comprehension

In this section, you’ll learn how to a Python list comprehension to multiply the elements of a Python list by a number. Python list comprehensions are easy way to represent for loops in a simpler and easier to read format.

Let’s see how we can use a Python list comprehension to accomplish this:

# Multiply a Python List by a Number Using a list comprehension numbers = [1, 2, 3, 4, 5] multiplied = [number * 2 for number in numbers] print(multiplied) # Returns: [2, 4, 6, 8, 10]

This example is a bit more readable than using a for loop. We can make it clear that we’re multiplying each number in our list by a value. This saves us the step of first instantiating an empty list while making the process more readable.

In the next sections, you’ll learn how to multiply Python lists element-wise.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Multiply Two Python Lists Element-wise Using Numpy

In the following sections, you’ll learn how to multiply lists element-wise. This means that the first element of one list is multiplied by the first element of the second list, and so on.

One of the easiest and most intuitive ways to accomplish this is, again, to use numpy. Numpy comes with a function, multiply() , that allows us to multiply two arrays. In order to accomplish this, it would seem that we first need to convert the list to a numpy array. However, numpy handles this implicitly. The method returns a numpy array. Because of this, we need to convert the array back into a list.

Let’s see how we can use NumPy to multiply two Python lists:

# Multiply 2 Python Lists using numpy import numpy as np numbers1 = [1, 2, 3, 4, 5] numbers2 = [5, 4, 3, 2, 1] multiplied = list(np.multiply(numbers1, numbers2)) print(multiplied) # Returns: [5, 8, 9, 8, 5]

Let’s break down what we’ve done here:

  • We instantiated two lists and passed them into the np.multiply() function
  • We then turned the returned array back into a list

If you’d rather not use numpy, the next two sections will explore how to multiply two Python lists without the need to import an additional library.

Multiply Two Python Lists Element-wise Using a For Loop and Zip

In this section, you’ll learn how to use a Python for loop and the zip function to multiply two lists element-wise.

Python actually comes with a built in function that allows us to iterate over multiple lists directly, the zip() function. I cover this function off extensively here – I suggest checking out the tutorial to get a full understanding of how this function works.

Читайте также:  Javascript поменять строки таблицы местами

Let’s see how we can use the zip function to multiply two lists element-wise in Python:

# Multiply 2 Python Lists using a for loop and zip() numbers1 = [1, 2, 3, 4, 5] numbers2 = [5, 4, 3, 2, 1] multiplied = [] for value1, value2 in zip(numbers1, numbers2): multiplied.append(value1 * value2) print(multiplied) # Returns: [5, 8, 9, 8, 5]

In the example above, we unpack the tuples that the zip object returns and multiply them together. The product of these values is append to our list.

In the next section, you’ll learn how to use a list comprehension to multiply a list element wise in Python.

Multiply Two Python Lists Element-wise Using a List Comprehension and Zip

In this final section, you’ll learn how to use a Python list comprehension to multiply a list element-wise with another list. A Python list comprehension is a condensed, easy-to-read way of replacing for loops that generate lists. While this is extremely oversimplified, it does give us a sense of how we’ll use the list comprehension to multiply lists.

Let’s see how we can accomplish this:

# Multiply 2 Python Lists using a list comprehension and zip() numbers1 = [1, 2, 3, 4, 5] numbers2 = [5, 4, 3, 2, 1] multiplied = [item1 * item2 for item1, item2 in zip(numbers1, numbers2)] print(multiplied) # Returns: [5, 8, 9, 8, 5]

We can see here very clearly that we’re multiplying items at the same index of two lists and assigning it to a new list.

Conclusion

In this tutorial, you learned two different methods to multiply Python lists: multiplying lists by a number and multiplying lists element-wise. You learned how to simplify this process using numpy and how to use list comprehensions and Python for loops to multiply lists.

To learn more about the Python np.multiply() method, check out the official documentation here.

Источник

Умножение матриц NumPy: начните за 5 минут

bestprogrammer.ru

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

Без рубрики

NumPy — популярная библиотека Python, которая предлагает ряд мощных математических функций. Библиотека широко используется в количественных областях, таких как наука о данных, машинное обучение и глубокое обучение. Мы можем использовать NumPy для выполнения сложных математических вычислений, таких как умножение матриц.

Умножение матриц может помочь нам быстро приблизиться к очень сложным вычислениям. Он может помочь нам в теории сетей, линейных системах уравнений, моделировании населения и многом другом. В этом руководстве мы рассмотрим некоторые основные вычисления с умножением матриц NumPy.

Что такое NumPy?

NumPy — это библиотека Python с открытым исходным кодом, которую мы можем использовать для выполнения высокоуровневых математических операций с массивами, матрицами, линейной алгеброй, анализом Фурье и т. Д. Библиотека NumPy очень популярна в научных вычислениях, науках о данных и машинном обучении. NumPy совместим с популярными библиотеками данных, такими как pandas, matplotlib и Scikit-learn. Это намного быстрее, чем списки Python, потому что он объединяет более быстрые коды, такие как C и C ++, в Python. Он также разбивает наши задачи на несколько частей и обрабатывает каждую часть одновременно.

Установка и импорт NumPy

Прежде чем мы начнем, убедитесь, что у нас установлен NumPy. Если у вас уже есть Python, вы можете установить NumPy с помощью одной из следующих команд:

Источник

Оцените статью