如何使用Python使用动态数组执行Numpy广播?

如何使用python使用动态数组执行numpy广播?

“Broadcasting” refers to how NumPy handles arrays of different dimensions during arithmetic operations. The smaller array is “broadcast” across the larger array, subject to certain limits, to ensure that their shapes are consistent. Broadcasting allows you to vectorize array operations, allowing you to loop in C rather than Python.”

This is accomplished without the need for unnecessary data copies, resulting in efficient algorithm implementations. In some cases, broadcasting is a negative idea since it results in wasteful memory utilization, which slows down the computation.

In this article, we will show you how to perform broadcasting with NumPy arrays using python.

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

Step 1. Create two arrays of compatible dimensions

立即学习“Python免费学习笔记(深入)”;

Step 2. Print the given array

Step 3. Perform arithmetic operation with the two arrays

Step 4. Print the result array

添加两个不同维度的数组

使用arange()函数创建一个由0到n-1的数字组成的numpy数组(arange()函数返回在给定区间内均匀间隔的值。在半开区间[start,stop]内生成值),并将某个常数值加到其中。

Example

import numpy as np# Getting list of numbers from 0 to 7givenArray = np.arange(8)# Adding a number to the numpy array result_array = givenArray + 9print("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尝试沿着某个轴广播(只是拉伸)较小的数组,使其适用于数学运算。

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

Creating two NumPy arrays from 0 to n-1 using the arange() function and reshaping it with reshape() function(reshapes an array without affecting its data). The two arrays are with compatible dimensions (3,4) and (3,1) and adding the corresponding elements of both the arrays.

Example

import numpy as np# Getting the list of numbers from 0 to 11 and reshaping it to 3 rows and 4 columnsgivenArray_1 = np.arange(12).reshape(3, 4)# Printing the shape(rowsize, columnsize) of arrayprint("The shape of Array_1 = ", givenArray_1.shape) # Getting list of numbers from 0 to 2 and reshaping it to 3 rows and 1 columnsgivenArray_2 = np.arange(3).reshape(3, 1)print("The shape of Array_2 = ", givenArray_2.shape)# Summing both the arraysprint("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]]

The givenArray_2 is expanded along the second dimension to match the dimension of givenArray_1. As the dimensions of both the arrays are compatible this can be made possible.

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

Creating two NumPy arrays with INCOMPATIBLE dimensions (6, 4) and (6, 1). When we try to add the corresponding elements of both the arrays it raises an ERROR as shown below.

Example

import numpy as np# Getting a list of numbers from 0 to 11 and reshaping it to 3 rows and 4 columnsgivenArray_1 = np.arange(20).reshape(6, 4)# Printing the shape(rowsize, columnsize) of arrayprint("The shape of Array_1 = ", givenArray_1.shape) # Getting list of numbers from 0 to 5 and reshaping it to 3 rows and 1 columnsgivenArray_2 = np.arange(6).reshape(6, 1)print("The shape of Array_2 = ", givenArray_2.shape)# Summing both the arraysprint("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。

It cannot be inserted in a matrix of size 20 (it requires a matrix of size 6*4 = 24).

Summing Numpy Multidimensional Array and Linear Array

Create an multidimensional array using the arange() function and reshape it to some random number of rows and columns using the reshape() function. Create Another linear array using the arange() function and sum both these arrays.

Example 1

import numpy as np# Getting list of numbers from 0 to 14 and reshaping it to 5 rows and 3 columnsgivenArray_1 = np.arange(15).reshape(5, 3)# Printing the shape(rowsize, columnsize) of arrayprint("The shape of Array_1 = ", givenArray_1.shape) # Getting list of numbers from 0 to 2givenArray_2 = np.arange(3)print("The shape of Array_2 = ", givenArray_2.shape)# Summing both the arraysprint("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(多维数组)的维度。由于两个数组的维度是兼容的,这是可能的。

Example 2

import numpy as npgivenArray_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 itprint("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)

It is critical to understand that multiple arrays can be propagated along several dimensions. Array1 has dimensions (6, 5, 4, 2), whereas array2 has dimensions (5, 4, 1). The dimension array is formed by stretching array1 along the third dimension and array2 along the first and second dimensions(6, 5, 4, 2).

结论

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

以上就是如何使用Python使用动态数组执行Numpy广播?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1342848.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 05:56:43
下一篇 2025年12月13日 05:56:55

相关推荐

  • 生成任何图像的点状文本的Python脚本

    在数字时代,操纵图像和创造艺术效果已成为一种常见的做法。一种有趣的效果是从图像生成点状文本。此过程涉及将图像的像素转换为点图案,从而创建有趣的文本视觉表示。 在这篇博文中,我们将探索如何创建一个可以从任何给定图像生成点线文本的 Python 脚本。通过利用 Python 的强大功能和一些重要的库,我…

    2025年12月13日
    000
  • 使用Python和Rasa的聊天机器人

    聊天机器人已被公认为企业与客户互动的首选沟通工具,提供了更高效、便捷的交互方式。 Python这种因其开发资源而变得简单的编程语言已成为构建各种聊天机器人的首选。另一方面,Rasa 是一个专门的工具,专注于构建具有自然语言理解的聊天机器人。 在本文中,我们将深入研究使用 Python 和 Rasa …

    2025年12月13日
    000
  • Python程序用于从两个数组中找到不同的元素

    在编程中,数组是一种数据结构,用于存储同质数据元素的集合。数组中的每个元素都由一个键或索引值来标识。 Python 中的数组 Python 没有特定的数据类型来表示数组。相反,我们可以将 List 用作数组。 [1, 4, 6, 5, 3] 从两个数组中查找不同元素意味着识别两个给定数组之间的唯一元…

    2025年12月13日
    000
  • 在Python中的HDF5文件

    文件类型HDF5(分层数据格式5)经常用于存储和处理庞大而复杂的数据集。它是科学和工业用途的完美选择,因为它具有多功能、可扩展且有效的特点。 Python 是可用于生成、读取和修改 HDF5 文件的众多编程语言之一。在本教程中,我们将介绍如何在 Python 中使用 HDF5 文件。 安装和设置 我…

    2025年12月13日
    000
  • 在Python中的高阶函数

    简介 Python 的高阶函数世界 如果您想提高 Python 编程能力并生成更具表现力和更有效的代码,那么您来对地方了。 Python 中的函数不仅仅是专门的代码块。它们也是可以移动、转移、甚至动态生成的强大东西。通过处理其他函数,高阶函数增强了这种多功能性。 本文将广泛讨论高阶函数的原理。我们将…

    2025年12月13日
    000
  • 如何在Python中终止正在运行的Windows进程?

    深入研究 Windows 操作系统上的 Python 开发领域时,毫无疑问会出现需要的情况终止正在运行的进程。此类终止背后的动机可能涉及多种情况,包括无响应、资源消耗过多或仅仅需要停止脚本执行。在这篇综合文章中,我们将探索使用 Python 完成终止 Windows 上正在运行的进程的任务的各种方法…

    2025年12月13日
    000
  • 如何在Python中创建和自定义Venn图?

    维恩图是用来表示集合之间关系的图。要创建维恩图,我们将使用 matplotlib。 Matplotlib是一个在Python中常用的数据可视化库,用于创建交互式的图表和图形。它也用于制作交互式的图像和图表。Matplotlib提供了许多函数来自定义图表和图形。在本教程中,我们将举例说明三个示例来自定…

    2025年12月13日
    000
  • 如何在kivymd-Python中创建横幅?

    在kivymd-python中,横幅是一个向用户显示短消息或通知的图形元素。它可用于通知用户应用程序的状态,例如任务成功完成或发生错误。 横幅可以自定义颜色、文本和屏幕上的位置。它们对于空间有限且向用户快速反馈非常重要的移动应用程序特别有用。横幅可以通过提供及时的相关信息来改善整体用户体验。 横幅类…

    2025年12月13日
    000
  • Python程序打印一个数组

    单个变量和连续内存位置中的同质元素的集合称为数组。数组中的元素可以是任何数据类型,但数组中存在的所有元素应该是同类的,即应该属于相同的数据类型。 数组是一种特殊的变量,它实际上以单个变量的名称存储多个值或元素,具有连续的内存位置,准确地称为“索引”。 指数 索引一词代表索引的复数形式。索引一词表示元…

    2025年12月13日
    000
  • 深入了解Python在智能化教育中的重要作用

    随着人工智能的快速发展,智能化教育也逐渐成为了教育界的热门话题。在众多的人工智能技术中,Python语言因其简洁、易学、功能强大而备受青睐。Python在智能化教育中起着举足轻重的作用,它不仅可以用于开发智能教育应用,还可以支持教师和学生进行自主学习、编程技能的提升以及教学内容的个性化定制。 Pyt…

    2025年12月13日
    000
  • 如何在Python中比较JSON对象而不考虑顺序?

    JSON,全称为JavaScript对象表示法,是一种在网络上交换数据的广泛使用的数据格式。在Python中,常常比较两个JSON对象以确定它们是否相同。然而,当这些对象具有相同的元素但顺序不同时,比较JSON对象可能是一项具有挑战性的任务。 在本文中,我们将探索三种不同的方法来比较 Python …

    2025年12月13日
    000
  • 在Python中,我什么时候可以依赖于使用is运算符进行身份测试?

    示例 is运算符是Python中的一个身份运算符。它用于测试对象的身份。让我们来看一个例子 − x = [“Paul”,”Mark”]y = [“Paul”,”Mark”]z = x# Python IS operatorprint(x is z) 输出 True 假设我们考虑另一个例子,其中测试 …

    2025年12月13日
    000
  • 如何在Python中删除一个文件?

    要删除文件,请使用python 中的remove() 方法。将要删除的文件的名称作为参数传递。 让我们首先创建一个文件并读取内容:我们将显示文本文件的内容。为此,我们首先创建一个包含以下内容的文本文件 amit.txt – 文件amit.txt在项目目录中可见 – 立即学习“…

    2025年12月13日
    000
  • 如何在Python中实现持久化对象?

    要在Python中实现持久化对象,请使用以下库。 上架泡菜 搁置模块 “架子”是一个持久的、类似字典的对象。与“dbm”数据库的区别在于,架子中的值(不是键!)本质上可以是任意 Python 对象 – pickle 模块可以处理的任何对象。这包括大多数类实例、递归数据类型以及包含大量共享…

    2025年12月13日
    000
  • 如何在Python的Matplotlib中给条形图添加注释?

    简介 条形图是数据可视化中常用的一种图表。它们是许多数据科学家的首选,因为它们易于生成和理解。然而,当我们需要可视化其他信息时,条形图可能会不够用。 注释在这种情况下很有用。在条形图中,可以使用注释以便更好地理解数据。 语法和用法 使用 Matplotlib 的 annotate() 函数。该方法接…

    2025年12月13日
    000
  • Python与PHP高效传递JSON数组:从多字符串到结构化解析实践

    本教程旨在解决python脚本向php返回多个json对象时,php端解析困难的问题。核心方案在于python脚本将所有独立的json数据聚合为一个列表,并统一序列化为单个json字符串输出。php接收该字符串后,通过两次`json_decode`操作,首先解析外部的json数组结构,然后遍历数组对…

    2025年12月13日
    000
  • 使用Docker容器化Laravel与PostgreSQL的完整教程

    本教程详细指导如何利用docker和docker compose容器化laravel应用程序与postgresql数据库。文章涵盖了优化的dockerfile配置,用于构建laravel应用镜像;以及一份完整的docker-compose.yml文件,用于编排laravel应用、postgresql…

    2025年12月13日
    000
  • 从Python程序中自动化关闭Web浏览器进程的方法

    本教程详细介绍了如何从python应用程序中,通过操作系统级别的进程管理命令来强制关闭web浏览器进程。文章涵盖了windows、macos和linux三大主流操作系统的具体实现方法,并强调了使用`os.system`模块执行系统命令的原理,以及在自动化任务中强制终止进程的注意事项和潜在风险。 从P…

    2025年12月13日
    000
  • 使用Docker容器化Laravel与PostgreSQL:完整实践指南

    本教程旨在提供一个使用docker容器化%ignore_a_1%应用与postgresql数据库的完整指南。我们将详细介绍如何配置dockerfile以构建php-fpm服务,集成composer和node.js,并创建docker-compose.yml文件来编排laravel应用容器和postg…

    2025年12月13日
    000
  • PHP进程与任务管理技巧_PHP处理后台任务的方式

    PHP可通过pcntl(CLI模式)、Supervisor托管和消息队列实现稳定后台任务管理;需避免僵尸进程、资源复用、内存泄漏等陷阱,确保进程可控、资源独立、职责解耦。 PHP进程与任务管理技巧 PHP本身是无状态、短生命周期的脚本语言,但通过合理设计,完全可以胜任后台任务调度与长期运行进程的管理…

    2025年12月13日
    000

发表回复

登录后才能评论
关注微信