版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Python()的基础面向对象程序设计()输入和输出()例外()numpy,scipy,matplotlib,scikit-learn面向对象程序设计类()和对象()是面向对象编程的两个主要方面。类创建一个新类型,其中对象是类的实例。一个类比是,您可以有int类型的变量,也就是说存储整数的变量是int类的实例(对象)机器学习基础2020/12/3自我类方法与普通函数()只有一个具体的区别--它们必须有一个额外的名字,这个名字必须添加到参数列表的开头,但是当您调用该方法时,您没有给出这个参数的值,Python将提供它。这个特定的变量指的是对象本身,按照惯例,它被命名为self机器学习基础2020/12/3上课机器学习基础>>>类圈:通过>>>c=Circle()>>>打印(c)<__main__.circle实例位于0x0134F3C8>>>>2020/12/3方法机器学习基础>>>>>>类圈:defsay_hi(self):打印(“嗨,我是一个圆圈”)>>>c=Circle()>>>C.say_hi()嗨,我是一个圆圈>>>2020/12/3init方法有许多方法名在Python类(Python)中具有特殊意义。现在我们将看到init方法的重要性一旦实例化类的对象,就会立即运行init方法。该方法对于执行您想要对对象执行的任何初始化都很有用。请注意名称开头和结尾的双下划线。(2)机器学习基础2020/12/3机器学习基础>>>类圈:def__init__(自,半径):self.radius=半径defsay_hi(self):打印('Hi,Iamacircle.Myradiusis‘,self.radius,'.')>>>c=圆(5.0)>>>C.say_hi()嗨,我是一个圆圈。我的半径是5.0.>>>2020/12/32020/12/3机器学习基础>>>类圈:def__init__(自,半径):self.radius=半径defget_area(self):返回3.14*self.radius*self.radius>>>c=圆(10)>>>c.get_area()314.0>>>类和对象变量()有两种类型的字段--类变量()和对象变量(),它们根据类或对象分别拥有变量进行分类类变量是shared()--该类的所有实例都可以访问它们。类变量只有一个副本,当任何一个对象对类变量进行更改时,所有其他实例都将看到该更改Objectvariablesareownedbyeachindividualobject/instanceoftheclass(对象变量是对象私有的).Inthiscase,eachobjecthasitsowncopyofthefieldi.e.theyarenotsharedandarenotrelatedinanywaytothefieldbythesamenameinadifferentinstance.2023/11/4FoundationsofMachineLearning2023/11/4FoundationsofMachineLearningclassRobot:"""Representsarobot,withaname."""#Aclassvariable,countingthenumberofrobotspopulation=0def__init__(self,name):"""Initializesthedata."""=nameprint("(Initializing{})".format())#Whenthispersoniscreated,therobot#addstothepopulationRobot.population+=1defdie(self):"""Iamdying."""print("{}isbeingdestroyed!".format())Robot.population-=12023/11/4FoundationsofMachineLearningifRobot.population==0:print("{}wasthelastone.".format()else:print("Therearestill{:d}robots\working.".format(Robot.population))
defsay_hi(self):"""Greetingbytherobot.Yeah,theycandothat."""print("Greetings,mymasterscallme\{}.".format())
@classmethoddefhow_many(cls):"""Printsthecurrentpopulation."""print("Wehave{:d}robots.".format(cls.population))Inheritance(继承)Oneofthemajorbenefitsofobjectorientedprogrammingisreuseofcode(代码复用)andoneofthewaysthisisachievedisthroughtheinheritancemechanism.Inheritancecanbebestimaginedasimplementingatypeandsubtyperelationshipbetweenclasses.Supposeyouwanttowriteaprogramwhichhastokeeptrackoftheteachers(教师)andstudents(学生)inacollege.Theyhavesomecommoncharacteristicssuchasname,ageandaddress(SchoolMember).Theyalsohavespecificcharacteristicssuchassalary,coursesandleavesforteachersand,marksandfeesforstudents.继承的类图表示2023/11/4FoundationsofMachineLearningSchoolMember2023/11/4FoundationsofMachineLearningclassSchoolMember:'''Representsanyschoolmember.'''def__init__(self,name,age):=nameself.age=ageprint('(InitializedSchoolMember:\{})'.format())deftell(self):'''Tellmydetails.'''print('Name:"{}"Age:"{}"'.format(,\self.age))Teacher2023/11/4FoundationsofMachineLearningclassTeacher(SchoolMember):'''Representsateacher.'''def__init__(self,name,age,salary):SchoolMember.__init__(self,name,age)self.salary=salaryprint('(InitializedTeacher:\{})'.format())deftell(self):SchoolMember.tell(self)print('Salary:"{:d}"'.format(self.salary))Student2023/11/4FoundationsofMachineLearningclassStudent(SchoolMember):'''Representsastudent.'''def__init__(self,name,age,marks):SchoolMember.__init__(self,name,age)self.marks=marksprint('(InitializedStudent:\{})'.format())deftell(self):SchoolMember.tell(self)print('Marks:"{:d}"'.format(self.marks))Python之特殊方法特殊方法的定义:定义在某些class当中不需要直接调用Python的某些函数或者是操作符会调用相应的特殊方法特殊方法很多,我们只需要编写用到的特殊方法,以及有关联性的特殊方法。2023/11/4FoundationsofMachineLearning__str__和__repr__方法:
如果要把一个类的实例变成
str,就需要实现特殊方法__str__():2023/11/4FoundationsofMachineLearning但是当我们输入p的时候我们并不能显示出字符串>>>p<__main__.Personobjectat0x035FC950>好像是__str__并没有调用因为Python定义了__str__()和__repr__()两种方法,__str__()用于显示给用户,而__repr__()用于显示给开发人员。有一个偷懒的定义__repr__的方法:2023/11/4FoundationsofMachineLearning__lt____gt____eq__
对
int、str
等内置数据类型排序时,Python的
sorted()
按照默认的比较函数排序,但是,如果对一组
Student
类的实例排序时,就必须提供我们自己的特殊方法比较函数:2023/11/4FoundationsofMachineLearning__len__函数:要让
len()
函数工作正常,类必须提供一个特殊方法__len__(),它返回元素的个数。2023/11/4FoundationsofMachineLearning数学运算:Python提供的基本数据类型
int、float
可以做整数和浮点的四则运算以及乘方等运算。但是,四则运算不局限于int和float,还可以是有理数、矩阵等。要表示有理数,可以用一个Rational类来表示:2023/11/4FoundationsofMachineLearning类型转换:为了能够将那个Rational函数变为int,我们可以使用int()在类里面我们可以使用特殊的函数转化。比如命名‘__int__()’2023/11/4FoundationsofMachineLearning@property当我们考虑隐秘性的时候,我们会使用__属性来保证该属性,不会被外在所访问。2023/11/4FoundationsofMachineLearning但是我们可以使用其他的方法来装饰函数,这样可以节约代码。2023/11/4FoundationsofMachineLearning__slots__如果要限制添加的属性,例如,Student类只允许添加
name、gender和score
这3个属性,就可以利用Python的一个特殊的__slots__来实现。2023/11/4FoundationsofMachineLearning__iter__
和
__next__如果一个类想被用于for...in循环,类似list和tuple那样,就要用__iter__()方法,它返回一个迭代对象然后,python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环2023/11/4FoundationsofMachineLearning__getitem__要表现的像list那样按照下标取元素,需要__getitem__()方法:2023/11/4FoundationsofMachineLearningWhyUseClassesInheritance(继承)Pizza-makingrobotsarekindsofrobots,sotheypossesstheusualrobot-yproperties.InOOPterms,wesaythey“inherit”propertiesfromthegeneralcategoryofallrobots.Thesecommonpropertiesneedtobeimplementedonlyonceforthegeneralcaseandcanbereusedbyalltypesofrobotswemaybuildinthefuture.Composition(组合)Pizza-makingrobotsarereallycollectionsofcomponentsthatworktogetherasateam.Forinstance,forourrobottobesuccessful,itmightneedarmstorolldough,motorstomaneuvertotheoven,andsoon.InOOPparlance,ourrobotisanexampleofcomposition;itcontainsotherobjectsthatitactivatestodoitsbidding.Eachcomponentmightbecodedasaclass,whichdefinesitsownbehaviorandrelationships.2023/11/4FoundationsofMachineLearningExampleClassestorepresentsfigure(图)andshapes(形状).一张图包括很多形状形状可能有三角形、矩形2023/11/4FoundationsofMachineLearningFigureShapeCircleRectangleClassShape2023/11/4FoundationsofMachineLearningclassShape:def__init__(self,color):self.color=colordef__str__(self):return"Color:"+self.colorClassCircle2023/11/4FoundationsofMachineLearningclassCircle(Shape):def__init__(self,color,radius):Shape.__init__(self,color)self.radius=radiusdef__str__(self):return"Circle--Radius:"+str(self.radius)\+","+Shape.__str__(self)defget_area(self):return3.14*self.radius*self.radius2023/11/4FoundationsofMachineLearningclassRectangle(Shape):def__init__(self,color,width,height):Shape.__init__(self,color)self.width=widthself.height=heightdef__str__(self):return"Rectangle--Width:"+str(self.width)\+",Height:"+str(self.height)\+","+Shape.__str__(self)defget_area(self):returnself.width*self.height2023/11/4FoundationsofMachineLearningclassFigure:def__init__(self):self.shapes=[]defadd(self,shape):self.shapes.append(shape)def__str__(self):s="Thisfigurehasfollowingshapes:"forshapeinself.shapes:s=s+"\n"+str(shape)returns2023/11/4FoundationsofMachineLearningif__name__=="__main__":c=Circle("red",5.0)print(c,c.get_area())f=Figure()f.add(c)print(f)f.add(Circle("blue",3.0))print(f)r=Rectangle("gray",4.0,5.0)print(r,r.get_area())f.add(r)InputandOutputInputfromuserFilesPickle2023/11/4FoundationsofMachineLearningInputfromuserTheinput()functiontakesastringasargumentanddisplaysittotheuser.Thenitwaitsfortheusertotypesomethingandpressthereturnkey.Oncetheuserhasenteredandpressedthereturnkey,theinput()functionwillthenreturnthattexttheuserhasentered.2023/11/4FoundationsofMachineLearningFilesYoucanopenandusefilesforreadingorwritingbycreatinganobjectofthefileclassandusingitsread,readlineorwritemethodsappropriatelytoreadfromorwritetothefile.Theabilitytoreadorwritetothefiledependsonthemodeyouhavespecifiedforthefileopening.Thenfinally,whenyouarefinishedwiththefile,youcalltheclosemethodtotellPythonthatwearedoneusingthefile.2023/11/4FoundationsofMachineLearningopen()returnsafileobject,andismostcommonlyusedwithtwoarguments:open(filename,mode).Thefirstargumentisastringcontainingthefilename.Thesecondargumentisanotherstringcontainingafewcharactersdescribingthewayinwhichthefilewillbeused.modecanbe'r'whenthefilewillonlyberead,'w'foronlywriting(anexistingfilewiththesamenamewillbeerased),and'a'opensthefileforappending;anydatawrittentothefileisautomaticallyaddedtotheend.'r+'opensthefileforbothreadingandwriting.Themodeargumentisoptional;'r'willbeassumedifit’somitted.2023/11/4FoundationsofMachineLearning>>>f=open('workfile','w')>>>print(f)<openfile'workfile',mode'w'at80a0960>MethodsofFileObjectsToreadafile’scontents,call
f.read(size),whichreadssomequantityofdataandreturnsitasastring.
size
isanoptionalnumericargument.When
size
isomittedornegative,theentirecontentsofthefilewillbereadandreturnedf.readline()
readsasinglelinefromthefile;anewlinecharacter(\n)isleftattheendofthestring,andisonlyomittedonthelastlineofthefileifthefiledoesn’tendinanewline.2023/11/4FoundationsofMachineLearningForreadinglinesfromafile,youcanloopoverthefileobject.Thisismemoryefficient,fast,andleadstosimplecode:2023/11/4FoundationsofMachineLearning>>>forlineinf:print(line)Thisisthefirstlineofthefile.SecondlineofthefilePicklePythonprovidesastandardmodulecalledpickleusingwhichyoucanstoreanyplainPythonobjectinafileandthengetitbacklater.Thisiscalledstoringtheobjectpersistently.2023/11/4FoundationsofMachineLearningimportnumpyasnpimportpickleimportioif__name__=='__main__':path='test'f=open(path,'wb')data={'a':123,'b':'ads','c':[[1,2],[3,4]]}pickle.dump(data,f)f.close()f1=open(path,'rb')data1=pickle.load(f1)print(data1)Exceptions(异常)Exceptionsoccurwhenexceptionalsituationsoccurinyourprogram.Forexample,whatifyouaregoingtoreadafileandthefiledoesnotexist?Orwhatifyouaccidentallydeleteditwhentheprogramwasrunning?Suchsituationsarehandledusingexceptions.Similarly,whatifyourprogramhadsomeinvalidstatements?ThisishandledbyPythonwhichraisesitshandsandtellsyouthereisanerror.2023/11/4FoundationsofMachineLearningErrors2023/11/4FoundationsofMachineLearning>>>Print("HelloWorld")File"<stdin>",line1Print("HelloWorld")^SyntaxError:invalidsyntax>>>print("HelloWorld")HelloWorldExceptionsWewilltrytoreadinputfromtheuser.Pressctrl-dandseewhathappens.2023/11/4FoundationsofMachineLearning>>>s=input('entersomthing-->')entersomthing-->Traceback(mostrecentcalllast):File"<pyshell#4>",line1,in<module>s=input('entersomthing-->')EOFError:EOFwhenreadingaline>>>HandlingExceptions(异常处理)Wecanhandleexceptionsusingthetry…exceptstatement.Webasicallyputourusualstatementswithinthetry-blockandputallourerrorhandlersintheexcept-block.2023/11/4FoundationsofMachineLearningtry:text=input('Entersomething-->')exceptEOFError:print('WhydidyoudoanEOFonme?')exceptKeyboardInterrupt:print('Youcancelledtheoperation.')else:print('Youentered{}'.format(text))RaisingExceptions(抛出异常)Youcanraiseexceptionsusingtheraisestatementbyprovidingthenameoftheerror/exceptionandtheexceptionobjectthatistobethrown.TheerrororexceptionthatyoucanraiseshouldbeaclasswhichdirectlyorindirectlymustbeaderivedclassoftheExceptionclass.2023/11/4FoundationsofMachineLearningclassShortInputException(Exception):'''Auser-definedexceptionclass.'''def__init__(self,length,atleast):Exception.__init__(self)self.length=lengthself.atleast=atleast2023/11/4FoundationsofMachineLearningtry:text=input('Entersomething-->')iflen(text)<3:raiseShortInputException(len(text),3)#OtherworkcancontinueasusualhereexceptEOFError:print('WhydidyoudoanEOFonme?')exceptShortInputExceptionasex:print('ShortInputException:Theinputwas'+\'{0}long,expectedatleast{1}')\.format(ex.length,ex.atleast))else:print('Noexceptionwasraised.')Try…Finally(try…finally语句)Supposeyouarereadingafileinyourprogram.Howdoyouensurethatthefileobjectisclosedproperlywhetherornotanexceptionwasraised?Thiscanbedoneusingthefinallyblock.2023/11/4FoundationsofMachineLearning2023/11/4FoundationsofMachineLearningimportsysimporttimef=Nonetry:f=open("poem.txt")#Ourusualfile-readingidiomwhileTrue:line=f.readline()iflen(line)==0:breakprint(line)sys.stdout.flush()print("Pressctrl+cnow“)#Tomakesureitrunsforawhiletime.sleep(2)2023/11/4FoundationsofMachineLearningtry:…exceptIOError:print("Couldnotfindfilepoem.txt")exceptKeyboardInterrupt:print("!!Youcancelledthereadingfromthefile.")finally:iff:f.close()print("(Cleaningup:Closedthefile)")Thewithstatement(with语句)Acquiringaresourceinthetryblockandsubsequentlyreleasingtheresourceinthefinallyblockisacommonpattern.Hence,thereisalsoawithstatementthatenablesthistobedoneinacleanmanner:2023/11/4FoundationsofMachineLearningwithopen("poem.txt")asf:forlineinf:print(line)Italwayscallsthethefile.enterfunctionbeforestartingtheblockofcodeunderitandalwayscallsthefile.exitafterfinishingtheblockofcode.numpy,scipy,matplotlib,Scikit-learnNumPy‘sarraytypeaugmentsthePythonlanguagewithanefficientdatastructureusefulfornumericalwork,e.g.,manipulatingmatrices.NumPyalsoprovidesbasicnumericalroutines,suchastoolsforfindingeigenvectors.SciPycontainsadditionalroutinesneededinscientificwork:forexample,routinesforcomputingintegralsnumerically,solvingdifferentialequations,optimization,andsparsematrices.Thematplotlibmoduleproduceshighqualityplots.Withityoucanturnyourdataoryourmodelsintofiguresforpresentationsorarticles.Noneedtodothenumericalworkinoneprogram,savethedata,andplotitwithanotherprogram.scikit-learnMachineLearninginPythonSimpleandefficienttoolsfordatamininganddataanalysisAccessibletoeverybody,andreusableinvariouscontextsBuiltonNumPy,SciPy,andmatplotlibOpensource,commerciallyusable-BSDlicense2023/11/4FoundationsofMachineLearningNumpy数组(1、数组初探)NumPy数组属性NumPy数组的维数称为秩(rank),一维数组的秩为1,二维数组的秩为2,以此类推。在NumPy中,每一个线性的数组称为是一个轴(axes),秩其实是描述轴的数量。比如说,二维数组相当于是两个一维数组,其中第一个一维数组中每个元素又是一个一维数组。所以一维数组就是NumPy中的轴(axes),第一个轴相当于是底层数组,第二个轴是底层数组里的数组。而轴的数量——秩,就是数组的维数。2023/11/4FoundationsofMachineLearningNumPy的数组中比较重要ndarray对象属性有:ndarray.ndim:数组的维数(即数组轴的个数),等于秩。最常见的为二维数组(矩阵)。ndarray.shape:数组的维度。为一个表示数组在每个维度上大小的整数元组。例如二维数组中,表示数组的“行数”和“列数”。ndarray.shape返回一个元组,这个元组的长度就是维度的数目,即ndim属性。ndarray.size:数组元素的总个数,等于shape属性中元组元素的乘积。ndarray.dtype:表示数组中元素类型的对象,可使用标准的Python类型创建或指定dtype。另外也可使用前一篇文章中介绍的NumPy提供的数据类型。ndarray.itemsize:数组中每个元素的字节大小。例如,一个元素类型为float64的数组itemsiz属性值为8(float64占用64个bits,每个字节长度为8,所以64/8,占用8个字节。ndarray.data:包含实际数组元素的缓冲区,由于一般通过数组的索引获取元素,所以通常不需要使用这个属性。2023/11/4FoundationsofMachineLearning2023/11/4FoundationsofMachineLearning>>>fromnumpyimport*>>>a=arange(15).reshape(3,5)>>>aarray([[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]])>>>a.shape(3,5)>>>a.ndim2>>>'int32'>>>a.itemsize4>>>a.size15>>>type(a)numpy.ndarray>>>b=array([6,7,8])>>>barray([6,7,8])>>>type(b)numpy.ndarray创建数组使用array函数从常规的Python列表和元组创造数组2023/11/4FoundationsofMachineLearning>>>fromnumpyimport*>>>a=array([2,3,4])>>>aarray([2,3,4])>>>a.dtypedtype('int32')>>>b=array([1.2,3.5,5.1])>>>b.dtypedtype('float64')使用array函数创建时,参数必须是由方括号括起来的列表,而不能使用多个数值作为参数调用array。2023/11/4FoundationsofMachineLearning>>>a=array(1,2,3,4)#WRONG>>>a=array([1,2,3,4])#RIGHT可使用双重序列来表示二维的数组,三重序列表示三维数组,以此类推。2023/11/4FoundationsofMachineLearning>>>b=array([(1.5,2,3),(4,5,6)])>>>barray([[1.5,2.,3.],[4.,5.,6.]])用函数zeros可创建一个全是0的数组,用函数ones可创建一个全为1的数组,函数empty创建一个内容随机并且依赖与内存状态的数组。2023/11/4FoundationsofMachineLearning>>>zeros((3,4))array([[0.,0.,0.,0.],[0.,0.,0.,0.],[0.,0.,0.,0.]])>>>ones((2,3,4),dtype=int16)#dtypecanalsobespecifiedarray([[[1,1,1,1],[1,1,1,1],[1,1,1,1]],[[1,1,1,1],[1,1,1,1],[1,1,1,1]]],dtype=int16)>>>empty((2,3))array([[3.73603959e-262,6.02658058e-154,6.55490914e-260],[5.30498948e-313,3.14673309e-307,1.00000000e+000]])NumPy提供一个类似arange的函数返回一个数列形式的数组:2023/11/4FoundationsofMachineLearning>>>arange(10,30,5)array([10,15,20,25])>>>arange(0,2,0.3)#itacceptsfloatargumentsarray([0.,0.3,0.6,0.9,1.2,1.5,1.8])输出数组当输出一个数组时,NumPy以特定的布局用类似嵌套列表的形式显示:第一行从左到右输出每行依次自上而下输出每个切片通过一个空行与下一个隔开一维数组被打印成行,二维数组成矩阵,三维数组成矩阵列表。2023/11/4FoundationsofMachineLearning2023/11/4FoundationsofMachineLearning>>>a=arange(6)#1darray>>>printa[012345]>>>>>>b=arange(12).reshape(4,3)#2darray>>>printb[[012][345][678][91011]]基本运算数组的算术运算是按元素逐个运算。数组运算后将创建包含运算结果的新数组。2023/11/4FoundationsofMachineLearning>>>a=array([20,30,40,50])>>>b=arange(4)>>>barray([0,1,2,3])>>>c=a-b>>>carray([20,29,38,47])>>>b**2array([0,1,4,9])>>>10*sin(a)array([9.12945251,-9.88031624,7.4511316,-2.62374854])>>>a<35array([True,True,False,False],dtype=bool)与其他矩阵语言不同,NumPy中的乘法运算符*按元素逐个计算,矩阵乘法可以使用dot函数或创建矩阵对象实现2023/11/4FoundationsofMachineLearning>>>A=array([[1,1],...[0,1]])>>>B=array([[2,0],...[3,4]])>>>A*B#elementwiseproductarray([[2,0],[0,4]])>>>dot(A,B)#matrixproductarray([[5,4],[3,4]])有些操作符如+=和*=用来更改已存在数组而不创建一个新的数组。2023/11/4FoundationsofMachineLearning>>>a=ones((2,3),dtype=int)>>>b=random.random((2,3))>>>a*=3>>>aarray([[3,3,3],[3,3,3]])>>>b+=a>>>barray([[3.69092703,3.8324276,3.0114541],[3.18679111,3.3039349,3.37600289]])>>>a+=b#bisconvertedtointegertype>>>aarray([[6,6,6],[6,6,6]])当数组中存储的是不同类型的元素时,数组将使用占用更多位(bit)的数据类型作为其本身的数据类型,也就是偏向更精确的数据类型(这种行为叫做upcast)。2023/11/4FoundationsofMachineLearning>>>a=ones(3,dtype=int32)>>>b=linspace(0,pi,3)>>>'float64'>>>c=a+b>>>carray([1.,2.57079633,4.14159265])>>>'float64'>>>d=exp(c*1j)>>>darray([0.54030231+0.84147098j,-0.84147098+0.54030231j,-0.54030231-0.84147098j])>>>'complex128'许多非数组运算,如计算数组所有元素之和,都作为ndarray类的方法来实现,使用时需要用ndarray类的实例来调用这些方法。2023/11/4FoundationsofMachineLearning>>>a=random.random((2,3))>>>aarray([[0.6903007,0.39168346,0.16524769],[0.48819875,0.77188505,0.94792155]])>>>a.sum()3.4552372100521485>>>a.min()0.16524768654743593>>>a.max()0.9479215542670073这些运算将数组看作是一维线性列表。但可通过指定axis参数(即数组的行)对指定的轴做相应的运算:2023/11/4FoundationsofMachineLearning>>>b=arange(12).reshape(3,4)>>>barray([[0,1,2,3],[4,5,6,7],[8,9,10,11]])>>>>>>b.sum(axis=0)#sumofeachcolumnarray([12,15,18,21])>>>>>>b.min(axis=1)#minofeachrowarray([0,4,8])>>>>>>b.cumsum(axis=1)#cumulativesumalongeachrowarray([[0,1,3,6],[4,9,15,22],[8,17,27,38]])索引,切片和迭代和列表和其它Python序列一样,一维数组可以进行索引、切片和迭代操作。2023/11/4FoundationsofMachineLearning>>>a=arange(10)**3>>>aarray([0,1,8,27,64,125,216,343,512,729])>>>a[2]8>>>a[2:5]array([8,27,64])>>>a[:6:2]=-1000#equivalenttoa[0:6:2]=-1000;fromstarttoposition6,exclusive,setevery2ndelementto-1000>>>aarray([-1000,1,-1000,27,-1000,125,216,343,512,729])>>>a[::-1]#reversedaarray([729,512,343,216,125,-1000,27,-1000,1,-1000])>>>foriina:...printi**(1/3.),...nan1.0nan3.0nan5.06.07.08.09.0多维数组可以每个轴有一个索引。这些索引由一个逗号分割的元组给出。2023/11/4FoundationsofMachineLearning>>deff(x,y):...return10*x+y...>>>b=fromfunction(f,(5,4),dtype=int)>>>barray([[0,1,2,3],[10,11,12,13],[20,21,22,23],[30,31,32,33],[40,41,42,43]])>>>b[2,3]23>>>b[0:5,1]#eachrowinthesecondcolumnofbarray([1,11,21,31,41])>>>b[:,1]#equivalenttothepreviousexamplearray([1,11,21,31,41])>>>b[1:3,:]#每列的第二和第三个元素barray([[10,11,12,13],[20,21,22,23]])形状(shape)操作数组的形状取决于其每个轴上的元素个数:2023/11/4FoundationsofMachineLearning>>>a=floor(10*random.random((3,4)))>>>aarray([[7.,5.,9.,3.],[7.,2.,7.,8.],[6.,8.,3.,2.]])>>>a.shape(3,4)可以用多种方式修改数组的形状:2023/11/4FoundationsofMachineLearning>>>a.ravel()#flattenthearrayarray([7.,5.,9.,3.,7.,2.,7.,8.,6.,8.,3.,2.])>>>a.shape=(6,2)>>>a.transpose()array([[7.,9.,7.,7.,6.,3.],[5.,3.,2.,8.,8.,2.]])reshape函数改变调用数组的形状并返回该数组,原数组不变;而resize函数改变调用数组自身。2023/11/4FoundationsofMachineLearning>>>aarray([[7.,5.],[9.,3.],[7.,2.],[7.,8.],[6.,8.],[3.,2.]])>>>a.resize((2,6))>>>aarray([[7.,5.,9.,3.,7.,2.],[7.,8.,6.,8.,3.,2.]])StackingtogetherdifferentarraysSeveralarrayscanbestackedtogetheralongdifferentaxes:2023/11/4FoundationsofMachineLearning>>>a=floor(10*random.random((2,2)))>>>aarray([[1.,1.],[5.,8.]])>>>b=floor(10*random.random((2,2)))>>>barray([[3.,3.],[6.,0.]])>>>vstack((a,b))array([[1.,1.],[5.,8.],[3.,3.],[6.,0.]])>>>hstack((a,b))array([[1.,1.,3.,3.],[5.,8.,6.,0.]])Thefunctioncolumn_stackstacks1Darraysascolumnsintoa2Darray.Itisequivalenttovstackonlyfor1Darrays:2023/11/4FoundationsofMachineLearning>>>column_stack((a,b))#With2Darraysarray([[1.,1.,3.,3.],[5.,8.,6.,0.]])>>>a=array([4.,2.])>>>b=array([2.,8.])>>>a[:,newaxis]#Thisallowstohavea2Dcolumnsvectorarray([[4.],[2.]])>>>column_stack((a[:,newaxis],b[:,newaxis]))array([[4.,2.],[2.,8.]])>>>vstack((a[:,newaxis],b[:,newaxis]))#Behaviorofvstackisdifferentarray([[4.],[2.],[2.],[8.]])Splittingonearrayintoseveralsmallerones2023/11/4FoundationsofMachineLearning>>>a=floor(10*random.random((2,12)))>>>aarray([[8.,8.,3.,9.,0.,4.,3.,0.,0.,6.,4.,4.],[0.,3.,2.,9.,6.,0.,4.,5.,7.,5.,1.,4.]])>>>hsplit(a,3)#Splitainto3[array([[8.,8.,3.,9.],[0.,3.,2.,9.]]),array([[0.,4.,3.,0.],[6.,0.,4.,5.]]),array([[0.,6.,4.,4.],[7.,5.,1.,4.]])]>>>hsplit(a,(3,4))#Splitaafterthethirdandthefourthcolumn[array([[8.,8.,3.],[0.,3.,2.]]),array([[9.],[9.]]),array([[0.,4.,3.,0.,0.,6.,4.,4.],[6.,0.,4.,5.,7.,5.,1.,4.]])]CopiesandViewsSimpleassignmentsmakenocopyofarrayobjectsoroftheirdata.2023/11/4FoundationsofMachineLearning>>>a=arange(12)>>>b=a#nonewobjectiscreated>>>bisa#aandbaretwonamesforthesamendarrayobjectTrue>>>b.shape=3,4#changestheshapeofa>>>a.shape(3,4)Pythonpassesmutableobjectsasreferences,sofunctioncallsmakenocopy.2023/11/4FoundationsofMachineLearning>>>deff(x):...printid(x)...>>>id(a)#idisauniqueidentifierofanobject148293216>>>f(a)148293216VieworShallowCopyDifferentarrayobjectscansharethesamedata.Theviewmethodcreatesanewarrayobjectthatlooksatthesamedata.2023/11/4FoundationsofMachineLearning>>>c=a.view()>>>cisaFalse>>>c.baseisa#cisaviewofthedataownedbyaTrue>>>c.flags.owndataFalse>>>>>>c.shape=2,6#a'sshapedoesn'tchange>>>a.shape(3,4)>>>c[0,4]=1234#a'sdatachanges>>>aarray([[0,1,
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025企业临时工劳动合同模板
- 2025年合同终止劳动合同范本
- 2025年新版事业单位劳动合同
- 2025船舶抵押借款合同范本
- 2025二手车买卖合同范本 城市供用电合同(示范文本)
- 2025成都市家具买卖合同范本
- 项目招商合作协议书
- 影视公司合作协议书
- 2025餐厅家具采购合同模板
- 购股协议合同范本
- GB/T 11981-2024建筑用轻钢龙骨
- 人教版六年级语文上册第六单元习作:《学写倡议书》授课课件
- 2024年安徽省广播电视行业职业技能大赛(有线广播电视机线员)考试题库(含答案)
- 广东省惠州市博罗县华侨中学2024-2025学年高二上学期同步检测生物学试题(含答案)
- 幼儿园童话故事《海的女儿》
- 尊重学术道德遵守学术规范学习通超星期末考试答案章节答案2024年
- 肺癌(肺恶性肿瘤)中医临床路径
- 法院司法审计申请书范文
- 福建省福州市台江区华伦中学2025届九年级化学第一学期期中监测试题含解析
- 可重复使用运载火箭的设计与建造
- 二年级上册美术教学设计-第4课 水中倒影丨赣美版
评论
0/150
提交评论