前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Hello Edge: Keyword Spotting on Microcontrollers

Hello Edge: Keyword Spotting on Microcontrollers

作者头像
用户6026865
发布于 2023-03-02 13:23:52
发布于 2023-03-02 13:23:52
6050
举报

- Hello Edge: Keyword Spotting on Microcontrollers -

Keyword spotting (KWS) is a critical component for enabling speech based user interactions on smart devices. It requires real-time response and high accuracy forgood user experience.

Recently, neural networks have become an attractive choicefor KWS architecture because of their superior accuracy compared to traditionalspeech processing algorithms.

Due to its always-on nature, KWS application hashighly constrained power budget and typically runs on tiny microcontrollers withlimited memory and compute capability.

The design of neural network architecturefor KWS must consider these constraints. In this work, we perform neural networkarchitecture evaluation and exploration for running KWS on resource-constrainedmicrocontrollers.

We train various neural network architectures for keywordspotting published in literature to compare their accuracy and memory/compute requirements.

We show that it is possible to optimize these neural network architectures to fit within the memory and compute constraints of microcontrollers withoutsacrificing accuracy. We further explore the depthwise separable convolutional neural network (DS-CNN) and compare it against other neural network architectures.DS-CNN achieves an accuracy of 95.4%, which is ~10% higher than the DNNmodel with similar number of parameters.

Introduction

Deep learning algorithms have evolved to a stage where they have surpassed human accuracies in avariety of cognitive tasks including image classification and conversational speech recognition.

Motivated by the recent breakthroughs in deep learning based speech recognition technologies,speech is increasingly becoming a more natural way to interact with consumer electronic devices, forexample, Amazon Echo, Google Home and smart phones.

However, always-on speech recognitionis not energy-efficient and may also cause network congestion to transmit continuous audio streamfrom billions of these devices to the cloud. Furthermore, such a cloud based solution adds latencyto the application, which hurts user experience.

There are also privacy concerns when audio iscontinuously transmitted to the cloud. To mitigate these concerns, the devices first detect predefinedkeyword(s) such as "Alexa", "Ok Google", "Hey Siri", etc., which is commonly known as keywordspotting (KWS). Detection of keyword wakes up the device and then activates the full scale speechrecognition either on device or in the cloud.

In some applications, the sequence of keywordscan be used as voice commands to a smart device such as a voice-enabled light bulb. Since KWSsystem is always-on, it should have very low power consumption to maximize battery life.

On theother hand, the KWS system should detect the keywords with high accuracy and low latency, forbest user experience.

These conflicting system requirements make KWS an active area of researchever since its inception over 50 years ago. Recently, with the renaissance of artificial neuralnetworks in the form of deep learning algorithms, neural network (NN) based KWS has become verypopular.

Low power consumption requirement for keyword spotting systems make microcontrollers an obviouschoice for deploying KWS in an always-on system.

Microcontrollers are low-cost energy-efficientprocessors that are ubiquitous in our everyday life with their presence in a variety of devices rangingfrom home appliances, automobiles and consumer electronics to wearables.

However, deployment ofneural network based KWS on microcontrollers comes with following challenges:

  • Limited memory footprint: Typical microcontroller systems have only tens to few hundred KB ofmemory available. The entire neural network model, including input/output, weights and activations,has to fit within this small memory budget.
  • Limited compute resources: Since KWS is always-on, the real-time requirement limits the totalnumber of operations per neural network inference.

These microcontroller resource constraints in conjunction with the high accuracy and low latencyrequirements of KWS call for a resource-constrained neural network architecture exploration to findlean neural network structures suitable for KWS, which is the primary focus of our work. The maincontributions of this work are as follows:

  • We first train the popular KWS neural net models from the literature on Googlespeech commands dataset and compare them in terms of accuracy, memory footprintand number of operations per inference.
  • In addition, we implement a new KWS model using depth-wise separable convolutions andpoint-wise convolutions, inspired by the success of resource-efficient MobileNet [10] incomputer vision. This model outperforms the other prior models in all aspects of accuracy,model size and number of operations.
  • Finally, we perform resource-constrained neural network architecture exploration and presentcomprehensive comparison of different network architectures within a set of compute andmemory constraints of typical microcontrollers. The code, model definitions and pretrainedmodels are available at https://github.com/ARM-software/ML-KWS-for-MCU.

Background

Keyword Spotting (KWS) System

A typical KWS system consists of a feature extractor and a neural network based classifier as shownin Fig. 1. First, the input speech signal of length L is framed into overlapping frames of length lwith a stride s, giving a total of T =L−ls + 1 frames. From each frame, F speech features areextracted, generating a total of T × F features for the entire input speech signal of length L.

Log-melfilter bank energies (LFBE) and Mel-frequency cepstral coefficients (MFCC) are the commonlyused human-engineered speech features in deep learning based speech-recognition, that are adaptedfrom traditional speech processing techniques.

Feature extraction using LFBE or MFCC involvestranslating the time-domain speech signal into a set of frequency-domain spectral coefficients, whichenables dimensionality compression of the input signal.

The extracted speech feature matrix is fedinto a classifier module, which generates the probabilities for the output classes. In a real-worldscenario where keywords need to be identified from a continuous audio stream, a posterior handlingmodule averages the output probabilities of each output class over a period of time, improving theoverall confidence of the prediction.

Traditional speech recognition technologies for KWS use Hidden Markov Models (HMMs) andViterbi decoding. While these approaches achieve reasonable accuracies, they are hardto train and are computationally expensive during inference.

Other techniques explored for KWSinclude discriminative models adopting a large-margin problem formulation or recurrent neuralnetworks (RNN). Although these methods significantly outperform HMM based KWS in termsof accuracy, they suffer from large detection latency.

Traditional speech recognition technologies for KWS use Hidden Markov Models (HMMs) andViterbi decoding. While these approaches achieve reasonable accuracies, they are hardto train and are computationally expensive during inference.

Other techniques explored for KWSinclude discriminative models adopting a large-margin problem formulation or recurrent neuralnetworks (RNN). Although these methods significantly outperform HMM based KWS in termsof accuracy, they suffer from large detection latency.

KWS models using deep neural networks (DNN)based on fully-connected layers with rectified linear unit (ReLU) activation functions are introduced, which outperforms the HMM models with a very small detection latency.

Furthermore,low-rank approximation techniques are used to compress the DNN model weights achieving similaraccuracy with less hardware resources. The main drawback of DNNs is that they ignorethe local temporal and spectral correlation in the input speech features.

In order to exploit thesecorrelations, different variants of convolutional neural network (CNN) based KWS are explored, which demonstrate higher accuracy than DNNs.

The drawback of CNNs in modeling timevarying signals (e.g. speech) is that they ignore long term temporal dependencies. Combining thestrengths of CNNs and RNNs, convolutional recurrent neural network based KWS is investigated and demonstrate the robustness of the model to noise.

While all the prior KWS neural networksare trained with cross entropy loss function, a max-pooling based loss function for training KWSmodel with long short-term memory (LSTM) is proposed, which achieves better accuracy thanthe DNNs and LSTMs trained with cross entropy loss.

Although many neural network models for KWS are presented in literature, it is difficult to make afair comparison between them as they are all trained and evaluated on different proprietary datasets(e.g. "TalkType" dataset, "Alexa" dataset, etc.) with different input speech featuresand audio duration.

Also, the primary focus of prior research has been to maximize the accuracywith a small memory footprint model, without explicit constraints of underlying hardware, such aslimits on number of operations per inference.

In contrast, this work is more hardware-centric andtargeted towards neural network architectures that maximize accuracy on microcontroller devices.The constraints on memory and compute significantly limit the neural network parameters and thenumber of operations.

Microcontroller Systems

A typical microcontroller system consists of a processor core, an on-chip SRAM block and anon-chip embedded flash.

Table 1 shows some commercially available microcontroller developmentboards with Arm Cortex-M processor cores with different compute capabilities running at differentfrequencies (16 MHz to 216 MHz), consisting of a wide range of on-chip memory (SRAM: 8 KB to320 KB; Flash: 128 KB to 1 MB).

The program binary, usually preloaded into the non-volatile flash,is loaded into the SRAM at startup and the processor runs the program with the SRAM as the maindata memory. Therefore, the size of the SRAM limits the size of memory that the software can use.

Other than the memory footprint, performance (i.e., operations per second) is also a constraining factorfor running neural networks on microcontrollers.

Most microcontrollers are designed for embeddedapplications with low cost and high energy-efficiency as the primary targets, and do not have highthroughput for compute-intensive workloads such as neural networks.

Some microcontrollers haveintegrated DSP instructions that can be useful for running neural network workloads. For example,Cortex-M4 and Cortex-M7 have integrated SIMD and MAC instructions that can be used to acceleratelow-precision computation in neural networks.

Neural Network Architectures for KWS

This section gives an overview of all the different neural network architectures explored in thiswork including the deep neural network (DNN), convolutional neural network (CNN), recurrentneural network (RNN), convolutional recurrent neural network (CRNN) and depthwise separableconvolutional neural network (DS-CNN).

Deep Neural Network (DNN)

The DNN is a standard feed-forward neural network made of a stack of fully-connected layers andnon-linear activation layers. The input to the DNN is the flattened feature matrix, which feeds into astack of d hidden fully-connected layers each with n neurons. Typically, each fully-connected layeris followed by a rectified linear unit (ReLU) based activation function. At the output is a linear layerfollowed by a softmax layer generating the output probabilities of the k keywords, which are used forfurther posterior handling.

Convolutional Neural Network (CNN)

One main drawback of DNN based KWS is that they fail to efficiently model the local temporaland spectral correlation in the speech features.

CNNs exploit this correlation by treating the inputtime-domain and spectral-domain features as an image and performing 2-D convolution operationsover it.

The convolution layers are typically followed by batch normalization, ReLU basedactivation functions and optional max/average pooling layers, which reduce the dimensionality ofthe features. During inference, the parameters of batch normalization can be folded into the weightsof the convolution layers. In some cases, a linear low-rank layer, which is simply a fully-connectedlayer without non-linear activation, is added in between the convolution layers and dense layers forthe purpose of reducing parameters and accelerating training .

Recurrent Neural Network (RNN)

RNNs have shown superior performance in many sequence modeling tasks, especially speech recognition [20], language modeling [21], translation [22], etc. RNNs not only exploit the temporal relationbetween the input signal, but also capture the long-term dependencies using "gating" mechanism

Convolutional Recurrent Neural Network (CRNN)

Convolution recurrent neural network is a hybrid of CNN and RNN, which takes advantages ofboth. It exploits the local temporal/spatial correlation using convolution layers and global temporaldependencies in the speech features using recurrent layers. As shown in Fig. 3, a CRNN model

Depthwise Separable Convolutional Neural Network (DS-CNN)

Recently, depthwise separable convolution has been proposed as an efficient alternative to the standard3-D convolution operation [29] and has been used to achieve compact network architectures in thearea of computer vision

Experiments and ResultsConclusions

Hardware optimized neural network architecture is key to get efficient results on memory and computeconstrained microcontrollers.

We trained various neural network architectures for keyword spottingpublished in literature on Google speech commands dataset to compare their accuracy and memoryrequirements vs. operations per inference, from the perspective of deployment on microcontrollersystems.

We quantized representative trained 32-bit floating-point KWS models into 8-bit fixed-pointversions demonstrating that these models can easily be quantized for deployment without any lossin accuracy, even without retraining. Furthermore, we trained a new KWS model using depthwiseseparable convolution layers, inspired from MobileNet.

Based on typical microcontroller systems,we derived three sets of memory/compute constraints for the neural networks and performed resourceconstrained neural network architecture exploration to find the best networks achieving maximumaccuracy within these constraints.

In all three sets of memory/compute constraints, depthwiseseparable CNN model (DS-CNN) achieves the best accuracies of 94.4%, 94.9% and 95.4% comparedto the other model architectures within those constraints, which shows good scalability of the DS-CNNmodel.

The code, model definitions and pretrained models are available at https://github.com/ARMsoftware/ML-KWS-for-MCU.

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-12-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 SmellLikeAISpirit 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
python: import详解
在python用import或者from...import或者from...import...as...来导入相应的模块,作用和使用方法与C语言的include头文件类似。其实就是引入某些成熟的函数库和成熟的方法,避免重复造轮子,提高开发速度。 python的import方法可以引入系统的模块,也可以引入我们自己写好的共用模块,这点和php非常相似,但是它们的具体细节还不是很一样。因为php是在引入的时候指明引入文件的具体路径,而python中不能够写文件路径进行引入。 下面总结一下import的几种情况:
昱良
2018/04/04
9840
python 学习笔记(8)——python绝对路径相对路径
今天在调试代码的时候,程序一直提示没有该模块,一直很纳闷,因为我导入文件一直是用绝对路径进行导入的。按道理来讲是不会出现模块找不到的情况的。    最后仔细分析了整个代码的目录结构,才发现了问题。
my_sunshine
2020/09/18
5.6K0
Python在不同目录下导入模块的方法
python在不同层级目录import模块的方法 使用python进行程序编写时,经常会调用不同目录下的模块及函数。本篇博客针对常见的模块调用讲解导入模块的方法。
李智
2018/08/03
3.2K0
python 跨文件夹引用
python目前也像php一样越来越多的朋友使用它了,今天 小编在学习python时碰到不同层级引用的问题,希望可以帮助到大家。
py3study
2020/01/08
3.5K0
python导入父级别目录
使用python进行程序编写时,经常会使用第三方模块包。这种包我们可以通过python setup install 进行安装后,通过import XXX或from XXX import yyy 进行导入。不过如果是自己遍写的依赖包,又不想安装到python的相应目录,可以放到本目录里进行import进行调用;为了更清晰的理清程序之间的关系,例如我们会把这种包放到lib目录再调用。本篇就针对常见的模块调用方法汇总下。
py3study
2020/01/08
3.9K0
Python采用并发查询mysql以及调用API灌数据 (三)- Python跨文件目录引入类方法
本次因为服务架构重构,表优化、重构,带来的任务就是需要从原来的mysql数据库中,读取原表数据(部分存在多张关联查询)然后通过调用API的服务方式灌入新的数据库表中(包含mysql、mongodb)。
Devops海洋的渔夫
2019/05/31
8450
python中如何import不同层级的模块 python中如何import不同层级的模块
main.py为主文件,model.py是我们要引入的文件,则直接import model或from model import *即可。
尾尾部落
2018/09/04
4.9K0
python module manage
python模块     就是python的程序模块     顶层文件     模块文件1     模块文件2         可以将代码量较大的程序分割成多个有组织的、彼此独立但又能互相交互的代码片段,这些自我包含的有组织的代码段就是模块。模块在物理形式上表现为以.py结尾的代码文件。一个文件被看作一个独立的模块,一个模块也可以被看作是一个文件。模块的文件名就是模块的名字加上扩展名.py。每个模块都有自己的名称空间。     python允许“导入”其它模块以实现代码重用,从而也实现了将独立的代码文件组织成更大的程序系统。python中,模块也是对象;在一个模块顶层定义的所有变量都在被导入时成为了被导入模块的属性。 python的程序架构     一个python程序通常包括一个顶层程序文件和其它的模块文件(0个、1个或多个)     顶层文件:包含了程序的主要控制流程     模块文件:为顶层文件或其它模块提供各种功能性组件。模块首次导入(或重载)时,python会立即执行模块文件的顶层程序代码(不在函数内的代码),而位于函数主体内的代码直到函数被调用后才会执行。python也自带了很多模块,可以使用help(module)查看,这些被称为python标准库文件。 模块的执行环境     模块是被导入的(import),但模块也可以导入和使用其它模块,这些模块可以用python或其它编程语言写成。     模块可内含变量、函数以及类来进行其工作,而函数和类可以包含变量和其它元素。     建议:在顶层文件可以出现大量的控制流语句,而其它的被调用文件仅包含变量、函数及类,这样程序在执行时效率才会高。 python导入模块     在导入模块时只能使用模块名,而不能使用带.py后缀的模块文件名     import语句:导入指定的整个模块,包括生成一个以模块名命名的名称空间     import module1[, module2[, ... moduleN ]]       建议一个import语句只导入一个模块     import module as module_alias     from-import语句: 常用于只导入指定模拟的部分属性至当前名称空间。     from module import name1[, name2[, ... nameN ]]             例:from random import choice,randint,random     建议:在顶层文件可以出现大量的控制流语句,而其它的被调用文件仅包含变量、函数及类,这样程序在执行时效率才会高。     import 和 from - import是赋值语句     import和from 是可执行语句,类似于def,因此,它们可以嵌套在if测试中,出现于def中等等     python执行到这些语句时才会对其进行解析,这意味着,所有来自模块的属性仅在import语句执行后才能使用。     import 和from 都是隐性赋值语句     import 将整个模块对象赋值给一个变量名;from将一个或多个变量名赋值给导入此模块的模块中的同名对象     模块就是名称空间:模块的名称空间可以通过属性__dict__或dir(M)获取;模块属性可通过点号(.)运算符获取,格式为M.attr;模块是一个独立的作用域(本地变量就是全局变量)     import的工作机制     import语句导入指定的模块时会执行三个步骤:        (1) 找到模块文件:在指定的路径下搜索模块文件        (2) 编译成字节码:文件导入时就会编译,因此顶层文件的.pyc字节码文件在内部使用后会被丢弃,只有被导入的文件才会留下.pyc文件。        (3) 执行模块的代码来创建其所有定义的对象:模块文件中的所有语句会依次执行,从头至尾,而此步骤中任何对变量名的赋值运算,都会产生所得到的模块文件的属性。     注意:模块只在第一次导入时才会执行如上步骤。后续的导入操作只不过是提取内存中已加载的模块对象。reload可用于重新加载模块。     模块搜索:     python解释器在import模块时必须先找到对应的模块文件     程序的主目录;PYTHONPATH目录(如果设置了些变量);标准链接库目录;任何.pth文件的内容(如果存在.pth文件)     这四个组件组合起来即为sys.path所包含的路径,而python会选择"在搜索路径中的第一个符合导入文件名"的文件。        import sys        sys.path    返回一个路径列表,该路径列表是python解释器需要搜索的路径顺序列表
py3study
2020/01/06
6790
python之模块和包
一 Python模块简介 1 模块化 一般来说,编程语言中,库,包,模块是同一种概念,是代码组织方式 python中只有一种模块对象类型,但是为了模块化组织的便利,提供了一个概念: 包 模块(module):指的是python的源代码文件 包(package):指的是模块组织在一起放入和包名同名的目录及相关文件 ---- 可以将代码量较大的程序分割成多个有组织,彼此间独立但又能互相交互的代码片段,这些自我包含的有组织的代码段就是模块 ---- 模块在物理形式上表现为以.py 结尾的代码文
py3study
2020/01/09
1.5K0
python之模块和包
解决python3中关于import的疑难杂症
在Python工程项目中,如果一个文件夹下有__init__.py文件就会认为该文件夹是一个包package,这样可以方便组织工程文件,避免模块名冲突。
TOMOCAT
2021/04/09
1.9K0
python 模块定义、导入、优化
2. import module_name,module2_name (导入多个模块)
py3study
2018/08/02
1.6K0
python中import星_Python imports 指北
声明:如果你每天写Python,你会发现这篇文章中没有新东西。 这是专为那些像运维人员等偶尔使用Python的人以及那些忘记/误用python import的人写的。 尽管如此,代码是用Python 3.6类型注释编写的,以满足有经验的Python读者。 像往常一样,如果你发现任何错误,请告诉我!
用户7886150
2020/12/31
1.1K0
[Python]自定义包及3种包导入方式
原文链接:https://blog.csdn.net/humanking7/article/details/88368950
祥知道
2020/03/10
3.1K0
Python 3.x | 史上最详解的 导入(import)「建议收藏」
1、模块、包 **模块 module:**一般情况下,是一个以.py为后缀的文件。其他可作为module的文件类型还有”.pyo”、”.pyc”、”.pyd”、”.so”、”.dll”,但Python初学者几乎用不到。 module 可看作一个工具类,可共用或者隐藏代码细节,将相关代码放置在一个module以便让代码更好用、易懂,让coder重点放在高层逻辑上。 module能定义函数、类、变量,也能包含可执行的代码。module来源有3种: ①Python内置的模块(标准库); ②第三方模块; ③自定义模块。
全栈程序员站长
2022/09/13
11K0
Python 3.x | 史上最详解的 导入(import)「建议收藏」
python--如何优雅的import
import应该是python代码中比较常见的模块了。import就是导入其他文件中的类,方法,变量,我认为除了主流程逻辑,其他代码文件模块就是为了给别人import的~
languageX
2023/08/08
1.1K0
Python-import导入上级目录文件
dir0文件夹下有file1.py、file2.py两个文件和dir3、dir4两个子文件夹,dir3中有file3.py文件,dir4中有file4.py文件。
bye
2021/03/20
11.5K0
Python中的import问题的本质理解
在Python中,import是必不可少的,但是在自己写模块的时候,经常出现各种烦人import问题。
明月AI
2021/10/28
8670
Python中的import问题的本质理解
python中import原理
在 python 中引入 Module 是再常见不过了,那么当我们 import 时它做了什么事情呢?它是如何加载 Module 使用的呢?
编程黑洞
2023/03/04
4850
Python 的 import 是怎么工作的?
Python 的 import 是非常直观的,但即使这样,有时候你会发现,明明包就在那里,我们仍会遇到 ModuleNotFoundError,明明相对路径非常正确,就是报错
somenzz
2022/04/07
8010
Python 的 import 是怎么工作的?
Python学习笔记整理(十三)Pyth
一、模块 模块是Pyhon最高级别的程序组织单元,它将程序代码和数据封装起来以便重用。实际的角度,模块往往对应Python程序文件。 每个文件都是一个模块,并且模块导入其他模块之后就可以使用导入模块定义的变量名。模块可以由两个语句和一个重要的内置函数进行处理。 import: 使客户端(导入者)以一个整体获取一个模块。 from:容许客户端从一个模块文件中获取特定的变量名。 reload:在不中止Python程序的情况下,提供了一个重新载入模块文件代码的方法。 在一个模块文件的顶层定义的所有变量名都成为了被导入的模块对象的属性。 模块至少有三个角色: 代码重用:模块还是定义变量名的空间,被认作是属性。可以被多个外部的客户端应用。 系统命名空间的划分: 现实共享服务和数据: 1、python程序构架 一个ptyhon程序包括了多个含有Python语句的文件。程序是作为一个主体的,顶层的文件来构造的,配合有零个或多个支持文件,在Python中这些文件称作模块。 标准模块:python自带了200多个使用的模块、成为标准连接库 import如何工作 执行三个步骤 1)、找到模块文件 2)、编译成位码(需要时) 3)、执行模块的代码来创建其所定义的对象。 在之后导入相同的模块时候,会跳过这三个步骤,而只提取内存中已加载模块对象。 搜索模块 导入模块时,不带模块的后缀名,比如.py Python搜索模块的路径: 1)、程序的主目录 2)、PTYHONPATH目录(如果已经进行了设置) 3)、标准连接库目录(一般在/usr/local/lib/python2.X/) 4)、任何的.pth文件的内容(如果存在的话).新功能,允许用户把有效果的目录添加到模块搜索路径中去 .pth后缀的文本文件中一行一行的地列出目录。 这四个组建组合起来就变成了sys.path了, >>> import sys >>> sys.path 导入时,Python会自动由左到右搜索这个列表中每个目录。 第1,第3元素是自动定义的,第2,第4可以用于扩展路径,从而包括自己的源码目录。 import b的形式可能加载 源码文件b.py 字节码文件.pyc 目录b 编译扩展模块,比如linux的b.so 用C编写的编译好的内置模块,并通过静态连接至Python ZIP文件组件,导入时自动解压压缩。 java类型,在Jython版本的python中。 .NET组件,在IronPython版本中的Python中 脚本中随处可见 object.attribute这里表达式法:多数对象都有一些可用的属性。可以通过"."运算符取出。 有些是可调用的对象。例如,函数。 第三方工具:distutils 第三方扩展,通常使用标准连接库中的distutils工具来自动安装。使用distutils的系统一般附带setup.py脚本 命令空间是一种独立完备的变量包,而变量就是命名空间对象的属性。模块的命令空间包含了代码在模块文件顶层赋值的所有变量名(也就是没有嵌套与def和class语句中) 二、模块代码编写基础 1、模块的创建和使用。 创建模块 后缀.py文本文件,模块顶层指定的所有变量名都会变成其属性。 定义一个module.py模块 name='diege' age=18 def printer(x):         print x 使用模块 import全部导入 >>> import module 属性 >>> module.name 'diege' 函数 >>> module.printer('hi') hi >>> module.printer('9')  9 from语句 from将获取(复制)模块特定变量名 from 模块名 import 需要复制的属性 from 模块名 import 需要复制的属性 as 新的属性名 from会把变量名赋值到另一个作用域,所以它就可以让我们直接在脚本中使用复制后的变量名,而不是通过模块 >>> from module import name >>> name 'diege >>> from module import name as myname >>> myname 'diege' >>> from module import printer as PR >>> PR('hi python') hi python >>> PR('99')         99 from * 语句 from 模块名 import * 取得模块顶层所有赋了值的变量名的拷贝。 模块只导入一次,因为该操作开销大 import和from是赋值语句,是可执行
py3study
2020/01/07
1.7K0
相关推荐
python: import详解
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档