Maison  >  Article  >  développement back-end  >  Comment effectuer une diffusion Numpy à l'aide d'un tableau dynamique en utilisant Python ?

Comment effectuer une diffusion Numpy à l'aide d'un tableau dynamique en utilisant Python ?

PHPz
PHPzavant
2023-09-15 09:13:02776parcourir

Comment effectuer une diffusion Numpy à laide dun tableau dynamique en utilisant Python ?

« Diffusion » fait référence à la façon dont NumPy gère les tableaux de différentes dimensions lors des opérations arithmétiques. Le plus petit tableau est « diffusé » sur le plus grand tableau, sous réserve de certaines limites, pour garantir que leurs formes sont cohérentes. La diffusion vous permet de vectoriser opérations sur les tableaux, vous permettant de boucler en C plutôt qu'en Python."

Cela se fait sans avoir besoin de copies de données inutiles, ce qui permet une implémentation efficace des algorithmes. Dans certains cas, la diffusion est une idée négative car elle entraîne un gaspillage de mémoire, ce qui ralentit le calcul.

Dans cet article, nous allons vous montrer comment effectuer une diffusion avec des tableaux NumPy en utilisant python.

在给定数组上执行广播的步骤-

  • Étape 1. Créez deux tableaux de dimensions compatibles

  • Étape 2. Imprimez le tableau donné

  • Étape 3. Effectuez une opération arithmétique avec les deux tableaux

  • Étape 4. Imprimez le tableau des résultats

添加两个不同维度的数组

使用arange() indique que la fonction 0 est n-1 et que numpy correspond à arange().值。在半开区间[start,stop]内生成值),并将某个常数值加到其中。

Exemple

import numpy as np
# Getting list of numbers from 0 to 7
givenArray = np.arange(8)

# Adding a number to the numpy array 
result_array = givenArray + 9
print("The input array",givenArray)
print("Result array after adding 9 to the input array",result_array)

输出

The input array [0 1 2 3 4 5 6 7]
Result array after adding 9 to the input array [ 9 10 11 12 13 14 15 16] 

给定的数组有一个维度(轴),长度为8,而9是一个没有维度的简单整数。由于它们的维度不同,Numpy尝试沿着某个轴广播(只是拉伸)较小的数组,使其适用于数学运算。

将具有兼容维度的两个数组相加

Créer deux tableaux NumPy de 0 à n-1 à l'aide de la fonction arange() et le remodeler avec la fonction reshape() (remodèle un tableau sans affecter ses données). Les deux tableaux ont des dimensions compatibles (3,4) et (3,1) et ajoutent les éléments correspondants des deux tableaux.

Exemple

import numpy as np
# Getting the list of numbers from 0 to 11 and reshaping it to 3 rows and 4 columns
givenArray_1 = np.arange(12).reshape(3, 4)

# Printing the shape(rowsize, columnsize) of array
print("The shape of Array_1 = ", givenArray_1.shape)
 
# Getting list of numbers from 0 to 2 and reshaping it to 3 rows and 1 columns
givenArray_2 = np.arange(3).reshape(3, 1)
print("The shape of Array_2 = ", givenArray_2.shape)

# Summing both the arrays
print("Input array 1 \n",givenArray_1)
print("Input array 2 \n",givenArray_2)
print("Summing both the arrays:")
print(givenArray_1 + givenArray_2)

输出

The shape of Array_1 =  (3, 4)
The shape of Array_2 =  (3, 1)
Input array 1 
 [[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11] ]
Input array 2 
 [[0]
  [1]
  [2]]
Summing both the arrays:
[[ 0  1  2  3]
 [ 5  6  7  8]
 [10 11 12 13]]

Le gaveArray_2 est développé le long de la deuxième dimension pour correspondre à la dimension de gaveArray_1. Comme les dimensions des deux tableaux sont compatibles, cela peut être rendu possible.

将具有不兼容维度的两个数组求和

Création de deux tableaux NumPy avec des dimensions INCOMPATIBLES (6, 4) et (6, 1). Lorsque nous essayons d'ajouter les éléments correspondants des deux tableaux, cela génère une ERREUR comme indiqué ci-dessous.

Exemple

import numpy as np
# Getting a list of numbers from 0 to 11 and reshaping it to 3 rows and 4 columns
givenArray_1 = np.arange(20).reshape(6, 4)

# Printing the shape(rowsize, columnsize) of array
print("The shape of Array_1 = ", givenArray_1.shape)
 
# Getting list of numbers from 0 to 5 and reshaping it to 3 rows and 1 columns
givenArray_2 = np.arange(6).reshape(6, 1)
print("The shape of Array_2 = ", givenArray_2.shape)

# Summing both the arrays
print("Summing both the arrays:")
print(givenArray_1 + givenArray_2)

输出

Traceback (most recent call last):
  File "main.py", line 3, in 
    givenArray_1 = np.arange(20).reshape(6, 4)
ValueError: cannot reshape array of size 20 into shape (6,4)

行数为6,列数为4。

Il ne peut pas être inséré dans une matrice de taille 20 (il nécessite une matrice de taille 6*4 = 24).

Résumation d'un tableau multidimensionnel Numpy et d'un tableau linéaire

Créez un tableau multidimensionnel à l'aide de la fonction arange() et remodelez-le en un nombre aléatoire de lignes et de colonnes à l'aide de la fonction reshape(). Créez un autre tableau linéaire à l'aide de la fonction arange() et additionnez ces deux tableaux.

Exemple 1

import numpy as np
# Getting list of numbers from 0 to 14 and reshaping it to 5 rows and 3 columns
givenArray_1 = np.arange(15).reshape(5, 3)

# Printing the shape(rowsize, columnsize) of array
print("The shape of Array_1 = ", givenArray_1.shape)
 
# Getting list of numbers from 0 to 2
givenArray_2 = np.arange(3)
print("The shape of Array_2 = ", givenArray_2.shape)

# Summing both the arrays
print("Array 1 \n",givenArray_1)
print("Array 2 \n",givenArray_2)
print("Summing both the arrays: \n",givenArray_1 + givenArray_2)

输出

The shape of Array_1 =  (5, 3)
The shape of Array_2 =  (3,)
Array 1 
 [[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]
  [ 9 10 11]
  [12 13 14]]
Array 2 
 [0 1 2]
Summing both the arrays: 
 [[ 0  2  4]
  [ 3  5  7]
  [ 6  8 10]
  [ 9 11 13]
  [12 14 16]]
 

给定的线数组被扩展以匹配给定数组1(多维数组)的维度。由于两个数组的维度是兼容的,这是可能的。

Exemple 2

import numpy as np
givenArray_1 = np.arange(240).reshape(6, 5, 4, 2)
print("The shape of Array_1: ", givenArray_1.shape)
 
givenArray_2 = np.arange(20).reshape(5, 4, 1)
print("The shape of Array_2: ", givenArray_2.shape)
 
# Summing both the arrays and printing the shape of it
print("Summing both the arrays and printing the shape of it:")
print((givenArray_1 + givenArray_2).shape)

输出

The shape of Array_1:  (6, 5, 4, 2)
The shape of Array_2:  (5, 4, 1)
Summing both the arrays and printing the shape of it:
(6, 5, 4, 2)

Il est essentiel de comprendre que plusieurs tableaux peuvent se propager selon plusieurs dimensions. Tableau1 a des dimensions (6, 5, 4, 2), tandis que tableau2 a des dimensions (5, 4, 1). Le tableau de dimensions est formé en étirant le tableau1 le long de la troisième dimension et le tableau2 le long des première et deuxième dimensions (6, 5, 4, 2).

结论

Numpy广播比在数组上循环更快。从第一个示例开始。用户可以通过循环遍历数组,将相同的数字添加到数组中的每个元素,而不是使用广播方法。这种方式之所以慢,有两个原因:循环需要与Python循环进行交互,这会减慢C实现的速度。其次,NumPy使用步幅而不是循环。将步幅设置为0允许您无限循环遍历组件,而不会产生内存开销。

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer