Длина вектора numpy python

Работа с векторами в Python с помощью NumPy

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

Что такое вектор в Python?

Вектор известен как одномерный массив. Вектор в Python – это единственный одномерный массив списков, который ведет себя так же, как список Python. Согласно Google, вектор представляет направление, а также величину; особенно он определяет положение одной точки в пространстве относительно другой.

Векторы очень важны в машинном обучении, потому что у них есть величина, а также особенности направления. Давайте разберемся, как мы можем создать вектор на Python.

Создание вектора в Python

Модуль Python Numpy предоставляет метод numpy.array(), который создает одномерный массив, то есть вектор. Вектор может быть горизонтальным или вертикальным.

Вышеупомянутый метод принимает список в качестве аргумента и возвращает numpy.ndarray.

Давайте разберемся в следующих примерах.

Пример – 1: горизонтальный вектор

# Importing numpy import numpy as np # creating list list1 = [10, 20, 30, 40, 50] # Creating 1-D Horizontal Array vtr = np.array(list1) vtr = np.array(list1) print("We create a vector from a list:") print(vtr)
We create a vector from a list: [10 20 30 40 50]

Пример – 2: Вертикальный вектор

# Importing numpy import numpy as np # defining list list1 = [[12], [40], [6], [10]] # Creating 1-D Vertical Array vtr = np.array(list1) vtr = np.array(list1) print("We create a vector from a list:") print(vtr)
We create a vector from a list: [[12] [40] [ 6] [10]]

Базовые операции вектора Python

После создания вектора мы теперь будем выполнять арифметические операции над векторами.

Ниже приведен список основных операций, которые мы можем производить с векторами:

  • сложение;
  • вычитание;
  • умножение;
  • деление;
  • точечное произведение;
  • скалярные умножения.

Сложение двух векторов

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

Давайте разберемся в следующем примере.

import numpy as np list1 = [10,20,30,40,50] list2 = [11,12,13,14,15] vtr1 = np.array(list1) vtr2= np.array(list2) print("We create vector from a list 1:") print(vtr1) print("We create vector from a list 2:") print(vtr2) vctr_add = vctr1+vctr2 print("Addition of two vectors: ",vtr_add)
We create vector from a list 1: [10 20 30 40 50] We create vector from a list 2: [11 12 13 14 15] Addition of two vectors: [21 32 43 54 65]

Вычитание

Вычитание векторов выполняется так же, как и сложение, оно следует поэлементному подходу, и элементы вектора 2 будут вычтены из вектора 1. Давайте разберемся в следующем примере.

import numpy as np list1 = [10,20,30,40,50] list2 = [5,2,4,3,1] vtr1 = np.array(list1) vtr2= np.array(list2) print("We create vector from a list 1:") print(vtr1) print("We create a vector from a list 2:") print(vtr2) vtr_sub = vtr1-vtr2 print("Subtraction of two vectors: ",vtr_sub)
We create vector from a list 1: [10 20 30 40 50] We create vector from a list 2: [5 2 4 3 1] Subtraction of two vectors: [5 18 26 37 49]

Умножение векторов

Элементы вектора 1 умножаются на вектор 2 и возвращают векторы той же длины, что и векторы умножения.

import numpy as np list1 = [10,20,30,40,50] list2 = [5,2,4,3,1] vtr1 = np.array(list1) vtr2= np.array(list2) print("We create vector from a list 1:") print(vtr1) print("We create a vector from a list 2:") print(vtr2) vtr_mul = vtr1*vtr2 print("Multiplication of two vectors: ",vtr_mul)
We create vector from a list 1: [10 20 30 40 50] We create vector from a list 2: [5 2 4 3 1] Multiplication of two vectors: [ 50 40 120 120 50]

Умножение производится следующим образом.

vct[0] = x[0] * y[0] vct[1] = x[1] * y[1]

Первый элемент вектора 1 умножается на первый элемент соответствующего вектора 2 и так далее.

Операция деления двух векторов

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

Давайте разберемся в следующем примере.

import numpy as np list1 = [10,20,30,40,50] list2 = [5,2,4,3,1] vtr1 = np.array(list1) vtr2= np.array(list2) print("We create vector from a list 1:") print(vtr1) print("We create a vector from a list 2:") print(vtr2) vtr_div = vtr1/vtr2 print("Division of two vectors: ",vtr_div)
We create vector from a list 1: [10 20 30 40 50] We create vector from a list 2: [5 2 4 3 1] Division of two vectors: [ 2. 10. 7.5 13.33333333 50. ]

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

Векторное точечное произведение

Векторное скалярное произведение выполняется между двумя последовательными векторами одинаковой длины и возвращает единичное скалярное произведение. Мы будем использовать метод .dot() для выполнения скалярного произведения. Это произойдет, как показано ниже.

vector c = x . y =(x1 * y1 + x2 * y2)

Давайте разберемся в следующем примере.

import numpy as np list1 = [10,20,30,40,50] list2 = [5,2,4,3,1] vtr1 = np.array(list1) vtr2= np.array(list2) print("We create vector from a list 1:") print(vtr1) print("We create a vector from a list 2:") print(vtr2) vtr_product = vtr1.dot(vtr2) print("Dot product of two vectors: ",vtr_product)
We create vector from a list 1: [10 20 30 40 50] We create vector from a list 2: [5 2 4 3 1] Dot product of two vectors: 380

Векторно-скалярное умножение

В операции скалярного умножения; мы умножаем скаляр на каждую компоненту вектора. Давайте разберемся в следующем примере.

import numpy as np list1 = [10,20,30,40,50] vtr1 = np.array(list1) scalar_value = 5 print("We create vector from a list 1:") print(vtr1) # printing scalar value print("Scalar Value : " + str(scalar_value)) vtr_scalar = vtr1 * scalar_value print("Multiplication of two vectors: ",vtr_scalar)
We create vector from a list 1: [10 20 30 40 50] Scalar Value : 5 Multiplication of two vectors: [ 50 100 150 200 250]

В приведенном выше коде скалярное значение умножается на каждый элемент вектора в порядке s * v =(s * v1, s * v2, s * v3).

Источник

NUMPY ДЛИНА ВЕКТОРА

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

Длина вектора — это расстояние от начала координат в n-мерном пространстве до точки, заданной координатами.

Для вычисления длины вектора в NumPy можно использовать функцию `linalg.norm(v)`, где `v` — вектор, длину которого нужно найти. Например, чтобы найти длину вектора (2, 3, 4), можно написать следующий код:

import numpy as np
v = np.array([2, 3, 4])
length = np.linalg.norm(v)
print(length)

Результат выполнения кода будет следующим:

Таким образом, длина вектора (2, 3, 4) равна примерно 5.39.

NumPy Tutorial (2022): For Physicists, Engineers, and Mathematicians

Learn NUMPY in 5 minutes — BEST Python Library!

A Note on Python/Numpy Vectors (C1W2L16)

1.6 Vectors with Numpy in Python — Array — Data science and analysis course — Tutorial

Python Tutorials — Attributes of NumPy Array

Vectorization and Broadcasting — Python Numpy Tutorial

Maximizing Python Speed with Numpy Vectorization (Part 1)

  • Что нужно чтобы программировать на python
  • Numpy where несколько условий
  • Передача файлов python
  • Подпись графика plot python
  • Python актуальность языка
  • Квантильная регрессия python
  • Matlab или python
  • Параллельный запуск тестов pytest
  • Python expected an indented block ошибка
  • Python константная модель
  • Python градиент функции
  • Как заработать на python
  • Python на андроид
  • Наследование python классов

Источник

How to Get NumPy Array Length

In Python Numpy you can get array length/size using numpy.ndarray.size and numpy.ndarray.shape properties. The size property gets the total number of elements in a NumPy array. The shape property returns a tuple in (x, y).

You can get the length of the multi-dimensional array with the shape property in Python. In this article, we’ll explain several ways of how to get Numpy array length with examples by using properties like numpy.ndarray.size and numpy.ndarray.shape with examples.

1. Quick Examples to Get NumPy Array Length

If you are in a hurry, below are some quick examples of getting Python NumPy array size.

 # Below are the quick examples # Example 1: Use numpy.size Property arr = np.array([1,3,6,9,12,15,20,22,25]) print(arr.size) # Example 2: Using on 2-d array arr = np.array([[1,3,6],[9,12,15],[20,22,25]]) print(arr.size) # Example 3: Use numpy.shape property arr = np.array([[1,3,6],[9,12,15],[20,22,25]]) print(arr.shape) 

2. Use NumPy.size to Get Length

You can use ndarray.size property to get the total number of elements (length) in a NumPy array. Let’s create a NumPy array and use this to get the number of elements from one-dimensional arrays.

 import numpy as np # Use numpy.size Property arr = np.array([1,3,6,9,12,15,20,22,25]) print(arr.size) # OutPut: # 9 

In the below code, you get the number of elements in the multi-dimensional array with the ndarray.size property in Python. It also gives us the value 9 because the total number of elements is the same as in the previous example. This is the reason why this method is not suitable for multi-dimensional arrays.

 # Use numpy.size property to get length of a NumPy array array = np.array([[1,3,6],[9,12,15],[20,22,25]]) print(array.size) # OutPut: # 9 

3. Use NumPy.shape to get Length

So for multi-dimensional NumPy arrays use ndarray.shape function which returns a tuple in (x, y), where x is the number of rows and y is the number of columns in the array. You can now find the total number of elements by multiplying the values in the tuple with each other. This method is preferred over the previous method because it gives us the number of rows and columns.

 # Use numpy.shape property arr = np.array([[1,3,6],[9,12,15],[20,22,25]]) print(arr.shape) # Output: # (3, 3) 

4. Conclusion

In this article, I have explained how to get Python Numpy array length/size or shape using ndarray.shape , ndarray.size properties with examples. By using the size property you can get the size of the array however it is not suitable to get the length of the multi-dimensional array. In order to get the multi-dimensional array size use the shape property which returns the tuple(x,y)

References

You may also like reading:

Источник

Читайте также:  Html font types css
Оцените статью