You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

math_ops.py 204 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849
  1. # Copyright 2020-2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """math operations, the function docs are adapted from Numpy API."""
  16. import operator
  17. import functools
  18. import itertools
  19. import sys
  20. from numpy import dtype as nptype
  21. from ..ops import operations as P
  22. from ..ops import functional as F
  23. from ..ops import composite as C
  24. from ..ops.primitive import constexpr
  25. from ..common import dtype as mstype
  26. from ..common import Tensor
  27. from .._c_expression import typing
  28. from .dtypes import nan, pi, dtype_map, inf
  29. from .array_creations import asarray_const, ones, zeros, empty, full, full_like, diag, \
  30. arange, histogram_bin_edges, eye
  31. from .array_ops import where as where_
  32. from .array_ops import ravel, expand_dims, moveaxis, concatenate, flip, stack, atleast_1d, \
  33. split
  34. from .utils_const import _infer_out_shape, _check_axis_valid, _get_device, \
  35. _check_shape_aligned, _raise_type_error, _check_same_type, _check_is_float, \
  36. _raise_value_error, _promote, _check_axis_type, _canonicalize_axis, \
  37. _is_shape_empty, _check_is_int, _expanded_shape, _check_axis_in_range, \
  38. _check_dtype, _list_comprehensions, _tuple_setitem, _add_unit_axes, _seq_prod, \
  39. _make_tensor, _promote_for_trigonometric, _raise_runtime_error, _max, _type_convert, \
  40. _raise_unimplemented_error, _abs, _in, _tuple_slice
  41. from .utils import _expand, _broadcast_to, _broadcast_to_shape, _check_input_tensor, \
  42. _to_tensor, _to_tensor_origin_dtype, _isnan
  43. ZERO_TENSOR = asarray_const(0)
  44. _mean_keepdims = P.ReduceMean(True)
  45. _matmul = P.MatMul(False, False)
  46. _matmul_t = P.MatMul(False, True)
  47. _reduce_sum_default = P.ReduceSum()
  48. _reduce_sum_keepdims = P.ReduceSum(True)
  49. _reduce_min_default = P.ReduceMin()
  50. _reduce_min_keepdims = P.ReduceMin(True)
  51. _reduce_max_default = P.ReduceMax()
  52. _reduce_max_keepdims = P.ReduceMax(True)
  53. _cumsum_default = P.CumSum()
  54. _concat = P.Concat(-1)
  55. _cumprod_default = P.CumProd()
  56. _round = P.Round()
  57. _rint = P.Rint()
  58. def absolute(x, dtype=None):
  59. """
  60. Calculates the absolute value element-wise.
  61. Note:
  62. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  63. not supported.
  64. Currently the backend kernel only supports float calculation, if the input
  65. is not a `float`, then it will be casted to :class:`mstype.float32` and casted back.
  66. Args:
  67. x (Tensor): Tensor to be used for calculation.
  68. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  69. output Tensor.
  70. Returns:
  71. Tensor.
  72. Raises:
  73. TypeError: If input arguments have types not specified above.
  74. Supported Platforms:
  75. ``Ascend`` ``GPU`` ``CPU``
  76. Examples:
  77. >>> import mindspore.numpy as np
  78. >>> x = np.asarray([1, 2, 3, -4, -5], np.float32)
  79. >>> output = np.absolute(x)
  80. >>> print(output)
  81. [1. 2. 3. 4. 5.]
  82. """
  83. original_dtype = x.dtype
  84. if not _check_is_float(original_dtype) and dtype is None:
  85. x = x.astype(mstype.float32)
  86. return _apply_tensor_op(F.absolute, x, dtype=dtype).astype(original_dtype)
  87. return _apply_tensor_op(F.absolute, x, dtype=dtype)
  88. def count_nonzero(x, axis=None, keepdims=False):
  89. """
  90. Counts the number of non-zero values in the tensor `x`.
  91. Args:
  92. x (Tensor): The tensor for which to count non-zeros.
  93. axis (Union[int,tuple], optional): Axis or tuple of axes along which to
  94. count non-zeros. Default is None, meaning that non-zeros will be counted
  95. along a flattened version of `x`.
  96. keepdims (bool, optional): If this is set to True, the axes that are counted
  97. are left in the result as dimensions with size one. With this option,
  98. the result will broadcast correctly against `x`.
  99. Returns:
  100. Tensor, indicating number of non-zero values in the `x` along a given axis.
  101. Otherwise, the total number of non-zero values in `x` is returned.
  102. Supported Platforms:
  103. ``Ascend`` ``GPU`` ``CPU``
  104. Examples:
  105. >>> import mindspore.numpy as np
  106. >>> x = np.asarray([1, 2, 3, -4, 0, 3, 2, 0])
  107. >>> output = np.count_nonzero(x)
  108. >>> print(output)
  109. 6
  110. """
  111. if _is_shape_empty(x.shape):
  112. return ZERO_TENSOR
  113. if axis is None:
  114. axis = ()
  115. return C.count_nonzero(x=x, axis=axis, keep_dims=keepdims)
  116. def clip(x, xmin, xmax, dtype=None):
  117. """
  118. Clips (limits) the values in an array.
  119. Given an interval, values outside the interval are clipped to the interval edges.
  120. For example, if an interval of :math:`[0, 1]` is specified, values smaller than 0 become 0,
  121. and values larger than 1 become 1.
  122. Args:
  123. x (Tensor): Tensor containing elements to clip.
  124. xmin (Tensor, scalar, None): Minimum value. If None, clipping is not performed
  125. on lower interval edge. Not more than one of `xmin` and `xmax` may be None.
  126. xmax (Tensor, scalar, None): Maximum value. If None, clipping is not performed
  127. on upper interval edge. Not more than one of `xmin` and `xmax` may be None.
  128. If `xmin` or `xmax` are tensors, then the three tensors will be broadcasted
  129. to match their shapes.
  130. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  131. output Tensor.
  132. Returns:
  133. Tensor, a tensor with the elements of `x`, but where values
  134. < `xmin` are replaced with `xmin`, and those > `xmax` with `xmax`.
  135. Supported Platforms:
  136. ``Ascend`` ``GPU`` ``CPU``
  137. Examples:
  138. >>> import mindspore.numpy as np
  139. >>> x = np.asarray([1, 2, 3, -4, 0, 3, 2, 0])
  140. >>> output = np.clip(x, 0, 2)
  141. >>> print(output)
  142. [1 2 2 0 0 2 2 0]
  143. """
  144. if xmin is None and xmax is None:
  145. _raise_value_error("One of max or min must be given.")
  146. if xmin is not None:
  147. x = maximum(x, xmin, dtype=dtype)
  148. if xmax is not None:
  149. x = minimum(x, xmax, dtype=dtype)
  150. return x
  151. def deg2rad(x, dtype=None):
  152. """
  153. Converts angles from degrees to radians.
  154. Args:
  155. x (Tensor): Angles in degrees.
  156. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  157. output Tensor.
  158. Returns:
  159. Tensor, the corresponding angle in radians. This is a tensor scalar if `x`
  160. is a tensor scalar.
  161. Raises:
  162. TypeError: if `x` is not a tensor.
  163. Supported Platforms:
  164. ``Ascend`` ``GPU`` ``CPU``
  165. Examples:
  166. >>> import mindspore.numpy as np
  167. >>> x = np.asarray([1, 2, 3, -4, -5])
  168. >>> output = np.deg2rad(x)
  169. >>> print(output)
  170. [ 0.01745329 0.03490658 0.05235988 -0.06981317 -0.08726647]
  171. """
  172. _check_input_tensor(x)
  173. def convert(a):
  174. return a * pi / 180.0
  175. return _apply_tensor_op(convert, x, dtype=dtype)
  176. def rad2deg(x, dtype=None):
  177. """
  178. Converts angles from radians to degrees.
  179. Args:
  180. x (Tensor): Angles in radians.
  181. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  182. output Tensor.
  183. Returns:
  184. Tensor, the corresponding angle in degrees. This is a tensor scalar if `x`
  185. is a tensor scalar.
  186. Supported Platforms:
  187. ``Ascend`` ``GPU`` ``CPU``
  188. Examples:
  189. >>> import mindspore.numpy as np
  190. >>> x = np.asarray([1, 2, 3, -4, -5])
  191. >>> output = np.rad2deg(x)
  192. >>> print(output)
  193. [ 57.295776 114.59155 171.88733 -229.1831 -286.47888 ]
  194. """
  195. _check_input_tensor(x)
  196. def convert(a):
  197. return a * 180.0 / pi
  198. return _apply_tensor_op(convert, x, dtype=dtype)
  199. def add(x1, x2, dtype=None):
  200. """
  201. Adds arguments element-wise.
  202. Note:
  203. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  204. not supported.
  205. Args:
  206. x1 (Tensor): input to be added.
  207. x2 (Tensor): input to be added.
  208. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  209. output Tensor.
  210. Returns:
  211. Tensor or scalar, the sum of `x1` and `x2`, element-wise. This is a scalar
  212. if both `x1` and `x2` are scalars.
  213. Supported Platforms:
  214. ``Ascend`` ``GPU`` ``CPU``
  215. Examples:
  216. >>> import mindspore.numpy as np
  217. >>> x1 = np.full((3, 2), [1, 2])
  218. >>> x2 = np.full((3, 2), [3, 4])
  219. >>> output = np.add(x1, x2)
  220. >>> print(output)
  221. [[4 6]
  222. [4 6]
  223. [4 6]]
  224. """
  225. # broadcast is not fully supported in tensor_add on CPU,
  226. # so we use tensor_sub as a substitute solution
  227. if _get_device() == 'CPU':
  228. return subtract(x1, F.neg_tensor(_to_tensor(x2)), dtype=dtype)
  229. return _apply_tensor_op(F.tensor_add, x1, x2, dtype=dtype)
  230. def subtract(x1, x2, dtype=None):
  231. """
  232. Subtracts arguments, element-wise.
  233. Note:
  234. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  235. not supported.
  236. Args:
  237. x1 (Tensor): the input to be subtracted from.
  238. x2 (Tensor): the input to be subtracted by.
  239. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  240. output Tensor.
  241. Returns:
  242. Tensor or scalar, the difference of `x1` and `x2`, element-wise. This is a
  243. scalar if both `x1` and `x2` are scalars.
  244. Supported Platforms:
  245. ``Ascend`` ``GPU`` ``CPU``
  246. Examples:
  247. >>> import mindspore.numpy as np
  248. >>> x1 = np.full((3, 2), [1, 2])
  249. >>> x2 = np.full((3, 2), [3, 4])
  250. >>> output = np.subtract(x1, x2)
  251. >>> print(output)
  252. [[-2 -2]
  253. [-2 -2]
  254. [-2 -2]]
  255. """
  256. return _apply_tensor_op(F.tensor_sub, x1, x2, dtype=dtype)
  257. def multiply(x1, x2, dtype=None):
  258. """
  259. Multiplies arguments element-wise.
  260. Note:
  261. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  262. not supported.
  263. Args:
  264. x1 (Tensor): input tensor to be multiplied.
  265. x2 (Tensor): input tensor to be multiplied.
  266. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  267. output Tensor.
  268. Returns:
  269. Tensor or scalar, the product of `x1` and `x2`, element-wise. This is a scalar
  270. if both `x1` and `x2` are scalars.
  271. Supported Platforms:
  272. ``Ascend`` ``GPU`` ``CPU``
  273. Examples:
  274. >>> import mindspore.numpy as np
  275. >>> x1 = np.full((3, 2), [1, 2])
  276. >>> x2 = np.full((3, 2), [3, 4])
  277. >>> output = np.multiply(x1, x2)
  278. >>> print(output)
  279. [[3 8]
  280. [3 8]
  281. [3 8]]
  282. """
  283. if _get_device() == 'CPU':
  284. _check_input_tensor(x1, x2)
  285. # broadcast is not fully supported on CPU backend,
  286. # and explicit broadcasting is performed
  287. shape_out = _infer_out_shape(F.shape(x1), F.shape(x2))
  288. x1 = _broadcast_to_shape(x1, shape_out)
  289. x2 = _broadcast_to_shape(x2, shape_out)
  290. return _apply_tensor_op(F.tensor_mul, x1, x2, dtype=dtype)
  291. def divide(x1, x2, dtype=None):
  292. """
  293. Returns a true division of the inputs, element-wise.
  294. Instead of the Python traditional ‘floor division’, this returns a true
  295. division.
  296. Note:
  297. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  298. not supported.
  299. Args:
  300. x1 (Tensor): the divident.
  301. x2 (Tensor): the divisor.
  302. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  303. output Tensor.
  304. Returns:
  305. Tensor or scalar, this is a scalar if both `x1` and `x2` are scalars.
  306. Supported Platforms:
  307. ``Ascend`` ``GPU`` ``CPU``
  308. Examples:
  309. >>> import mindspore.numpy as np
  310. >>> x1 = np.full((3, 2), [1, 2])
  311. >>> x2 = np.full((3, 2), [3, 4])
  312. >>> output = np.divide(x1, x2)
  313. >>> print(output)
  314. [[0.33333334 0.5 ]
  315. [0.33333334 0.5 ]
  316. [0.33333334 0.5 ]]
  317. """
  318. x1, x2 = _to_tensor(x1, x2)
  319. if not _check_is_float(F.dtype(x1)) and not _check_is_float(F.dtype(x2)):
  320. x1 = F.cast(x1, mstype.float32)
  321. x2 = F.cast(x2, mstype.float32)
  322. return _apply_tensor_op(F.tensor_div, x1, x2, dtype=dtype)
  323. def true_divide(x1, x2, dtype=None):
  324. """
  325. Returns a true division of the inputs, element-wise.
  326. Instead of the Python traditional ‘floor division’, this returns a true
  327. division.
  328. Note:
  329. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  330. not supported.
  331. Args:
  332. x1 (Tensor): the divident.
  333. x2 (Tensor): the divisor.
  334. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  335. output Tensor.
  336. Returns:
  337. Tensor or scalar, this is a scalar if both `x1` and `x2` are scalars.
  338. Supported Platforms:
  339. ``Ascend`` ``GPU`` ``CPU``
  340. Examples:
  341. >>> import mindspore.numpy as np
  342. >>> x1 = np.full((3, 2), [1, 2])
  343. >>> x2 = np.full((3, 2), [3, 4])
  344. >>> output = np.true_divide(x1, x2)
  345. >>> print(output)
  346. [[0.33333334 0.5 ]
  347. [0.33333334 0.5 ]
  348. [0.33333334 0.5 ]]
  349. """
  350. return divide(x1, x2, dtype=dtype)
  351. def power(x1, x2, dtype=None):
  352. """
  353. First array elements raised to powers from second array, element-wise.
  354. Raises each base in `x1` to the positionally-corresponding power in `x2`.
  355. Note:
  356. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  357. not supported.
  358. On GPU, the supported dtypes are np.float16, and np.float32.
  359. Args:
  360. x1 (Tensor): the bases.
  361. x2 (Tensor): the exponents.
  362. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  363. output Tensor.
  364. Returns:
  365. Tensor or scalar, the bases in `x1` raised to the exponents in `x2`. This
  366. is a scalar if both `x1` and `x2` are scalars.
  367. Supported Platforms:
  368. ``Ascend`` ``GPU`` ``CPU``
  369. Examples:
  370. >>> import mindspore.numpy as np
  371. >>> x1 = np.full((3, 2), [1, 2]).astype('float32')
  372. >>> x2 = np.full((3, 2), [3, 4]).astype('float32')
  373. >>> output = np.power(x1, x2)
  374. >>> print(output)
  375. [[ 1. 16.]
  376. [ 1. 16.]
  377. [ 1. 16.]]
  378. """
  379. return _apply_tensor_op(F.tensor_pow, x1, x2, dtype=dtype)
  380. def float_power(x1, x2, dtype=None):
  381. """
  382. First array elements raised to powers from second array, element-wise.
  383. Raise each base in `x1` to the positionally-corresponding power in `x2`. `x1` and
  384. `x2` must be broadcastable to the same shape. This differs from the power
  385. function in that integers, float16, and float64 are promoted to floats with
  386. a minimum precision of float32 so that the result is always inexact. The
  387. intent is that the function will return a usable result for negative powers
  388. and seldom overflow for positive powers.
  389. Note:
  390. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  391. not supported.
  392. Integers and floats are promoted to float32 instead of float64.
  393. Args:
  394. x1 (Tensor): the bases.
  395. x2 (Tensor): the exponenets.
  396. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  397. output Tensor.
  398. Returns:
  399. Tensor or scalar, the bases in `x1` raised to the exponents in `x2`. This
  400. is a scalar if both `x1` and `x2` are scalars.
  401. Supported Platforms:
  402. ``Ascend`` ``GPU`` ``CPU``
  403. Examples:
  404. >>> import mindspore.numpy as np
  405. >>> x1 = np.arange(6)
  406. >>> x2 = np.array(3)
  407. >>> output = np.float_power(x1, x2)
  408. >>> print(output)
  409. [ 0. 1. 8. 27. 64. 125.]
  410. """
  411. if not _check_same_type(F.dtype(x1), mstype.float32):
  412. x1 = F.cast(x1, mstype.float32)
  413. if not _check_same_type(F.dtype(x2), mstype.float32):
  414. x2 = F.cast(x2, mstype.float32)
  415. return _apply_tensor_op(F.tensor_pow, x1, x2, dtype=dtype)
  416. def minimum(x1, x2, dtype=None):
  417. """
  418. Element-wise minimum of tensor elements.
  419. Compares two tensors and returns a new tensor containing the element-wise minima.
  420. Note:
  421. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  422. not supported.
  423. On Ascend, input arrays containing inf or NaN are not supported.
  424. Args:
  425. x1 (Tensor): first input tensor to be compared.
  426. x2 (Tensor): second input tensor to be compared.
  427. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  428. output Tensor.
  429. Returns:
  430. Tensor, element-wise minimum of `x1` and `x2`.
  431. Raises:
  432. TypeError: If inputs have types not specified above.
  433. ValueError: If the shapes of `x1` and `x2` cannot be broadcast.
  434. Supported Platforms:
  435. ``Ascend`` ``GPU`` ``CPU``
  436. Examples:
  437. >>> import mindspore.numpy as np
  438. >>> a = np.asarray([1, 2])
  439. >>> b = np.asarray([[1, 3],[1, 4]])
  440. >>> print(np.minimum(a, b))
  441. [[1 2]
  442. [1 2]]
  443. """
  444. if isinstance(x1, (int, float, bool, list, tuple)):
  445. x1 = asarray_const(x1)
  446. elif not isinstance(x1, Tensor):
  447. _raise_type_error("Input x1 is expected to be array_like")
  448. if isinstance(x2, (int, float, bool, list, tuple)):
  449. x2 = asarray_const(x2)
  450. elif not isinstance(x2, Tensor):
  451. _raise_type_error("Input x2 is expected to be array_like")
  452. # if both are scalars, expand x1 to 1d tensor, since cpu kernel doesn't support
  453. # comparisons with 2 scalars
  454. if x1.ndim == 0 and x2.ndim == 0:
  455. x1 = expand_dims(x1, 0)
  456. return _apply_tensor_op(functools.partial(_prop_nan, F.minimum), x1, x2, dtype=dtype).squeeze()
  457. if x1.ndim == 0:
  458. dtype = x2.dtype
  459. elif x2.ndim == 0:
  460. dtype = x1.dtype
  461. return _apply_tensor_op(functools.partial(_prop_nan, F.minimum), x1, x2, dtype=dtype)
  462. def mean(a, axis=None, keepdims=False, dtype=None):
  463. """
  464. Computes the arithmetic mean along the specified axis.
  465. Returns the average of the array elements. The average is taken
  466. over the flattened array by default, otherwise over the specified
  467. axis.
  468. Note:
  469. Numpy arguments `out` is not supported.
  470. On GPU, the supported dtypes are np.float16, and np.float32.
  471. Args:
  472. a (Tensor): input tensor containing numbers whose mean is desired.
  473. If a is not an array, a conversion is attempted.
  474. axis (None or int or tuple of ints, optional): Axis or axes along
  475. which the means are computed. The default is to compute
  476. the mean of the flattened array. If this is a tuple of
  477. ints, a mean is performed over multiple axes.
  478. keepdims (bool, optional): If this is set to True, the axes which
  479. are reduced are left in the result as dimensions with
  480. size one. With this option, the result will broadcast
  481. correctly against the input tensor.
  482. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  483. output Tensor.
  484. Returns:
  485. Tensor or scalar, an array containing the mean values.
  486. Raises:
  487. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  488. if the axes contain duplicates.
  489. Supported Platforms:
  490. ``Ascend`` ``GPU`` ``CPU``
  491. Examples:
  492. >>> import mindspore.numpy as np
  493. >>> a = np.arange(6, dtype='float32')
  494. >>> output = np.mean(a, 0)
  495. >>> print(output)
  496. 2.5
  497. """
  498. return _reduce(a, P.ReduceMean(keepdims), axis=axis, keepdims=keepdims, dtype=dtype)
  499. def inner(a, b):
  500. """
  501. Returns the inner product of two tensors.
  502. Ordinary inner product of vectors for 1-D tensors (without complex
  503. conjugation), in higher dimensions a sum product over the last
  504. axes.
  505. Note:
  506. Numpy argument `out` is not supported.
  507. On GPU, the supported dtypes are np.float16, and np.float32.
  508. On CPU, the supported dtypes are np.float16, np.float32, and
  509. np.float64.
  510. Args:
  511. a (Tensor): input tensor. If `a` and `b` are nonscalar, their last
  512. dimensions must match.
  513. b (Tensor): input tensor. If `a` and `b` are nonscalar, their last
  514. dimensions must match.
  515. Returns:
  516. Tensor or scalar.
  517. Raises:
  518. ValueError: if ``x1.shape[-1] != x2.shape[-1]``.
  519. Supported Platforms:
  520. ``Ascend`` ``GPU`` ``CPU``
  521. Examples:
  522. >>> import mindspore.numpy as np
  523. >>> a = np.ones((5, 3))
  524. >>> b = np.ones((2, 7, 3))
  525. >>> output = np.inner(a, b)
  526. >>> print(output)
  527. [[[3. 3. 3. 3. 3. 3. 3.]
  528. [3. 3. 3. 3. 3. 3. 3.]]
  529. [[3. 3. 3. 3. 3. 3. 3.]
  530. [3. 3. 3. 3. 3. 3. 3.]]
  531. [[3. 3. 3. 3. 3. 3. 3.]
  532. [3. 3. 3. 3. 3. 3. 3.]]
  533. [[3. 3. 3. 3. 3. 3. 3.]
  534. [3. 3. 3. 3. 3. 3. 3.]]
  535. [[3. 3. 3. 3. 3. 3. 3.]
  536. [3. 3. 3. 3. 3. 3. 3.]]]
  537. """
  538. if F.rank(a) == 0 or F.rank(b) == 0:
  539. return F.tensor_mul(a, b)
  540. _check_shape_aligned(F.shape(a), F.shape(b))
  541. aligned_shape_a = (F.shape_mul(F.shape(a)[:-1]), F.shape(a)[-1])
  542. aligned_shape_b = (F.shape_mul(F.shape(b)[:-1]), F.shape(a)[-1])
  543. a_aligned = F.reshape(a, aligned_shape_a)
  544. b_aligned = F.reshape(b, aligned_shape_b)
  545. res = _matmul_t(a_aligned, b_aligned)
  546. res = F.reshape(res, F.shape(a)[:-1] + F.shape(b)[:-1])
  547. return res
  548. def dot(a, b):
  549. """
  550. Returns the dot product of two arrays.
  551. Specifically,
  552. If both `a` and `b` are 1-D arrays, it is inner product of vectors
  553. (without complex conjugation).
  554. If both `a` and `b` are 2-D arrays, it is matrix multiplication.
  555. If either `a` or `b` is 0-D (scalar), it is equivalent to multiply.
  556. If `a` is an `N-D` array and `b` is a 1-D array, it is a sum product
  557. over the last axis of `a` and `b`.
  558. If `a` is an `N-D` array and `b` is an `M-D` array (where ``M>=2``), it is a
  559. sum product over the last axis of `a` and the second-to-last axis of `b`:
  560. ``dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])``
  561. Note:
  562. Numpy argument `out` is not supported.
  563. On GPU, the supported dtypes are np.float16, and np.float32.
  564. On CPU, the supported dtypes are np.float16, np.float32, and
  565. np.float64.
  566. Args:
  567. a (Tensor): input tensor
  568. b (Tensor): input tensor
  569. Returns:
  570. Tensor or scalar, the dot product of `a` and `b`. If `a` and `b` are
  571. both scalars or both 1-D arrays then a scalar is returned;
  572. otherwise an array is returned
  573. Raises:
  574. ValueError: If the last dimension of `a` is not the same size
  575. as the second-to-last dimension of `b`.
  576. Supported Platforms:
  577. ``Ascend`` ``GPU`` ``CPU``
  578. Examples:
  579. >>> import mindspore.numpy as np
  580. >>> a = np.full((1, 3), 7).astype('float32')
  581. >>> b = np.full((2, 3, 4), 5).astype('float32')
  582. >>> output = np.dot(a, b)
  583. >>> print(output)
  584. [[[105. 105. 105. 105.]
  585. [105. 105. 105. 105.]]]
  586. """
  587. ndim_a, ndim_b = F.rank(a), F.rank(b)
  588. if ndim_a == 0 or ndim_b == 0:
  589. return F.tensor_mul(a, b)
  590. if ndim_a > 0 and ndim_b >= 2:
  591. perm = F.make_range(ndim_b)
  592. perm = perm[:-2] + (perm[-1],) + (perm[-2],)
  593. b = F.transpose(b, perm)
  594. if F.shape(a)[-1] != F.shape(b)[-1]:
  595. _raise_value_error('shapes are not aligned')
  596. a_aligned = F.reshape(a, (-1, F.shape(a)[-1]))
  597. b_aligned = F.reshape(b, (-1, F.shape(b)[-1]))
  598. res = _matmul_t(a_aligned, b_aligned)
  599. res = F.reshape(res, F.shape(a)[:-1] + F.shape(b)[:-1])
  600. return res
  601. def outer(a, b):
  602. """
  603. Computes the outer product of two vectors.
  604. Given two vectors, ``a = [a0, a1, ..., aM]`` and ``b = [b0, b1, ..., bN]``,
  605. the outer product is:
  606. ``[[a0*b0 a0*b1 ... a0*bN ]``
  607. ``[a1*b0 . ]``
  608. ``[ ... . ]``
  609. ``[aM*b0 aM*bN ]]``
  610. Note:
  611. Numpy argument ``out`` is not supported.
  612. On GPU, the supported dtypes are np.float16, and np.float32.
  613. On CPU, the supported dtypes are np.float16, np.float32, and
  614. np.float64.
  615. Args:
  616. a (Tensor): first input vector. Input is flattened if not
  617. already 1-dimensional.
  618. b (Tensor): second input vector. Input is flattened if not
  619. already 1-dimensional.
  620. Returns:
  621. Tensor or scalar, ``out[i, j] = a[i] * b[j]``.
  622. Raises:
  623. TypeError: if the input is not a tensor.
  624. Supported Platforms:
  625. ``Ascend`` ``GPU`` ``CPU``
  626. Examples:
  627. >>> import mindspore.numpy as np
  628. >>> a = np.full(7, 2).astype('float32')
  629. >>> b = np.full(4, 3).astype('float32')
  630. >>> output = np.outer(a, b)
  631. >>> print(output)
  632. [[6. 6. 6. 6.]
  633. [6. 6. 6. 6.]
  634. [6. 6. 6. 6.]
  635. [6. 6. 6. 6.]
  636. [6. 6. 6. 6.]
  637. [6. 6. 6. 6.]
  638. [6. 6. 6. 6.]]
  639. """
  640. _check_input_tensor(a, b)
  641. if F.rank(a) != 1:
  642. a = ravel(a)
  643. if F.rank(b) != 1:
  644. b = ravel(b)
  645. a = F.reshape(a, (F.shape(a)[0], 1))
  646. b = _expand(b, 2)
  647. return _matmul(a, b)
  648. def tensordot(a, b, axes=2):
  649. """
  650. Computes tensor dot product along specified axes.
  651. Given two tensors, `a` and `b`, and an array_like object containing two array_like
  652. objects, `(a_axes, b_axes)`, sum the products of `a`’s and `b`’s elements (components)
  653. over the axes specified by `a_axes` and `b_axes`. The third argument can be a single
  654. non-negative integer_like scalar, `N`; if it is such, then the last `N` dimensions of
  655. `a` and the first `N` dimensions of `b` are summed over.
  656. Three common use cases are:
  657. - ``axes = 0`` : tensor product
  658. - ``axes = 1`` : tensor dot product
  659. - ``axes = 2`` : (default) tensor double contraction
  660. When axes is integer_like, the sequence for evaluation will be: first the `-Nth`
  661. axis in `a` and 0th axis in `b`, and the -1th axis in `a` and `Nth` axis in `b` last.
  662. When there is more than one axis to sum over - and they are not the last (first)
  663. axes of `a` `(b)` - the argument axes should consist of two sequences of the same
  664. length, with the first axis to sum over given first in both sequences, the second
  665. axis second, and so forth.
  666. The shape of the result consists of the non-contracted axes of the first tensor,
  667. followed by the non-contracted axes of the second.
  668. Note:
  669. On CPU, the supported dypes are np.float16 and np.float32.
  670. On GPU, the supported dypes are np.float16 and np.float32.
  671. Args:
  672. a (Tensor): Tensor to "dot".
  673. b (Tensor): Tensor to “dot”.
  674. axes (int or sequence of ints):
  675. integer_like: If an int `N`, sum over the last `N` axes of `a` and the first `N`
  676. axes of `b` in order. The sizes of the corresponding axes must match.
  677. sequence of ints: Or, a list of axes to be summed over, first sequence
  678. applying to `a`, second to `b`. Both elements `array_like` must be of the same
  679. length.
  680. Returns:
  681. Tensor, or list of tensors, the tensor dot product of the input.
  682. Supported Platforms:
  683. ``Ascend`` ``GPU`` ``CPU``
  684. Examples:
  685. >>> import mindspore.numpy as np
  686. >>> a = np.ones((3, 4, 5))
  687. >>> b = np.ones((4, 3, 2))
  688. >>> output = np.tensordot(a, b, axes=([1,0],[0,1]))
  689. >>> print(output.shape)
  690. (5, 2)
  691. """
  692. if F.rank(a)*F.rank(b) == 0 and axes == 0:
  693. return F.tensor_mul(a, b)
  694. return C.tensor_dot(a, b, axes)
  695. def std(x, axis=None, ddof=0, keepdims=False):
  696. """
  697. Computes the standard deviation along the specified axis.
  698. The standard deviation is the square root of the average of the squared deviations
  699. from the mean, i.e., :math:`std = sqrt(mean(abs(x - x.mean())**2))`.
  700. Returns the standard deviation, which is computed for the flattened array by default,
  701. otherwise over the specified axis.
  702. Note:
  703. Numpy arguments `dtype`, `out` and `where` are not supported.
  704. Args:
  705. x (Tensor): A Tensor to be calculated.
  706. axis (Union[None, int, tuple(int)]): Axis or axes along which the standard
  707. deviation is computed. Default: `None`.
  708. If `None`, compute the standard deviation of the flattened array.
  709. ddof (int): Means Delta Degrees of Freedom. The divisor used in calculations is :math:`N - ddof`,
  710. where :math:`N` represents the number of elements. Default: 0.
  711. keepdims: Default: `False`.
  712. Returns:
  713. Standard deviation tensor.
  714. Supported Platforms:
  715. ``Ascend`` ``GPU`` ``CPU``
  716. Examples:
  717. >>> import mindspore.numpy as np
  718. >>> input_x = np.array([1., 2., 3., 4.])
  719. >>> output = np.std(input_x)
  720. >>> print(output)
  721. 1.118034
  722. """
  723. x = _to_tensor(x)
  724. return x.std(axis, ddof, keepdims)
  725. def var(x, axis=None, ddof=0, keepdims=False):
  726. """
  727. Computes the variance along the specified axis.
  728. The variance is the average of the squared deviations from the mean, i.e.,
  729. :math:`var = mean(abs(x - x.mean())**2)`.
  730. Returns the variance, which is computed for the flattened array by default,
  731. otherwise over the specified axis.
  732. Note:
  733. Numpy arguments `dtype`, `out` and `where` are not supported.
  734. Args:
  735. x (Tensor): A Tensor to be calculated.
  736. axis (Union[None, int, tuple(int)]): Axis or axes along which the variance is computed.
  737. The default is to compute the variance of the flattened array. Default: `None`.
  738. ddof (int): Means Delta Degrees of Freedom. Default: 0.
  739. The divisor used in calculations is :math:`N - ddof`, where :math:`N` represents the number of elements.
  740. keepdims (bool): Default: `False`.
  741. Supported Platforms:
  742. ``Ascend`` ``GPU`` ``CPU``
  743. Returns:
  744. Standard deviation tensor.
  745. Examples:
  746. >>> import mindspore.numpy as np
  747. >>> input_x = np.array([1., 2., 3., 4.])
  748. >>> output = np.var(input_x)
  749. >>> print(output)
  750. 1.25
  751. """
  752. x = _to_tensor(x)
  753. return x.var(axis, ddof, keepdims)
  754. def ptp(x, axis=None, keepdims=False):
  755. """
  756. Range of values (maximum - minimum) along an axis.
  757. The name of the function comes from the acronym for ‘peak to peak’.
  758. Note:
  759. Numpy arguments `dtype` and `out` are not supported.
  760. Args:
  761. x (Tensor): Input tensor.
  762. axis (Union[None, int, tuple(int)]): Axis or axes along which the range is computed.
  763. The default is to compute the variance of the flattened array. Default: None.
  764. keepdims (bool): Default is False.
  765. Returns:
  766. Tensor.
  767. Raises:
  768. TypeError: if inputs have types not specified above.
  769. Supported Platforms:
  770. ``Ascend`` ``GPU`` ``CPU``
  771. Examples:
  772. >>> import mindspore.numpy as np
  773. >>> x = np.array([[4.0, 9.0, 2.0, 10.0], [6.0, 9.0, 7.0, 12.0]])
  774. >>> print(np.ptp(x, axis=1))
  775. [8. 6.]
  776. >>> print(np.ptp(x, axis=0))
  777. [2. 0. 5. 2.]
  778. """
  779. _check_input_tensor(x)
  780. return x.ptp(axis, keepdims)
  781. def average(x, axis=None, weights=None, returned=False):
  782. """
  783. Computes the weighted average along the specified axis.
  784. Args:
  785. x (Tensor): A Tensor to be averaged.
  786. axis (Union[None, int, tuple(int)]): Axis along which to average `x`. Default: `None`.
  787. If the axis is `None`, it will average over all of the elements of the tensor `x`.
  788. If the axis is negative, it counts from the last to the first axis.
  789. weights (Union[None, Tensor]): Weights associated with the values in `x`. Default: `None`.
  790. If `weights` is `None`, all the data in `x` are assumed to have a weight equal to one.
  791. If `weights` is 1-D tensor, the length must be the same as the given axis.
  792. Otherwise, `weights` should have the same shape as `x`.
  793. returned (bool): Default: `False`.
  794. If `True`, the tuple (average, sum_of_weights) is returned.
  795. If `False`, only the average is returned.
  796. Returns:
  797. Averaged Tensor. If returned is `True`, return tuple.
  798. Supported Platforms:
  799. ``Ascend`` ``GPU`` ``CPU``
  800. Examples:
  801. >>> import mindspore.numpy as np
  802. >>> input_x = np.array([[1., 2.], [3., 4.]])
  803. >>> output = np.average(input_x, axis=0, weights=input_x, returned=True)
  804. >>> print(output)
  805. (Tensor(shape=[2], dtype=Float32, value= [ 2.50000000e+00, 3.33333325e+00]),
  806. Tensor(shape=[2], dtype=Float32, value= [ 4.00000000e+00, 6.00000000e+00]))
  807. """
  808. _check_input_tensor(x)
  809. if axis is not None:
  810. _check_axis_type(axis, True, True, False)
  811. axis = _canonicalize_axis(axis, x.ndim)
  812. x_avg = full((), nan, F.dtype(x))
  813. sum_of_weights = None
  814. if weights is None:
  815. x_avg = mean(x, axis)
  816. sum_of_weights = compute_weights_for_mean(x, x_avg, axis)
  817. else:
  818. _check_input_tensor(weights)
  819. if x.shape == weights.shape:
  820. x_avg, sum_of_weights = comput_avg(x, axis, weights)
  821. elif F.rank(weights) == 1:
  822. if not isinstance(axis, int):
  823. _raise_type_error("Axis must be specified when shapes of x and weights differ.")
  824. perm = _expanded_shape(x.ndim, weights.shape[0], axis)
  825. weights = weights.reshape(perm)
  826. x_avg, sum_of_weights = comput_avg(x, axis, weights)
  827. else:
  828. _raise_type_error("Weights should be None, 1-D or the same shape as input x.")
  829. if returned:
  830. if x_avg.shape != sum_of_weights.shape:
  831. sum_of_weights = _broadcast_to(sum_of_weights, sum_of_weights.shape, x_avg.shape, x_avg.ndim)
  832. return (x_avg, sum_of_weights)
  833. return x_avg
  834. def compute_weights_for_mean(x, x_avg, axis):
  835. """Computes weights for np.average."""
  836. if axis is None:
  837. sum_of_weights = full((), x.size, F.dtype(x))
  838. else:
  839. fill_value = 1
  840. if isinstance(axis, int) or (isinstance(axis, tuple) and F.tuple_len(axis) == 1):
  841. fill_value = x.shape[axis] if isinstance(axis, int) else x.shape[axis[0]]
  842. elif axis is None:
  843. for sh in x.shape:
  844. fill_value *= sh
  845. else:
  846. for ax in axis:
  847. fill_value *= x.shape[ax]
  848. sum_of_weights = full_like(x_avg, fill_value, F.dtype(x))
  849. return sum_of_weights
  850. def comput_avg(x, axis, weights):
  851. """Computes average value of input x with given parameters."""
  852. axis = () if axis is None else axis
  853. x_mul = F.tensor_mul(x, weights)
  854. x_sum = _reduce_sum_default(x_mul, axis)
  855. sum_of_weights = _reduce_sum_default(weights, axis)
  856. x_avg = F.tensor_div(x_sum, sum_of_weights)
  857. return x_avg, sum_of_weights
  858. def matmul(x1, x2, dtype=None):
  859. """
  860. Returns the matrix product of two arrays.
  861. Note:
  862. Numpy arguments `out`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  863. not supported.
  864. On GPU, the supported dtypes are np.float16 and np.float32.
  865. On CPU, the supported dtypes are np.float16 and np.float32.
  866. Args:
  867. x1 (Tensor): Input tensor, scalar not allowed.
  868. x2 (Tensor): Input tensor, scalar not allowed.
  869. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  870. output Tensor.
  871. Returns:
  872. Tensor or scalar, the matrix product of the inputs. This is a scalar only
  873. when both `x1`, `x2` are 1-d vectors.
  874. Raises:
  875. ValueError: If the last dimension of `x1` is not the same size as the
  876. second-to-last dimension of `x2`, or if a scalar value is passed in.
  877. Supported Platforms:
  878. ``Ascend`` ``GPU`` ``CPU``
  879. Examples:
  880. >>> import mindspore.numpy as np
  881. >>> x1 = np.arange(2*3*4).reshape(2, 3, 4).astype('float32')
  882. >>> x2 = np.arange(4*5).reshape(4, 5).astype('float32')
  883. >>> output = np.matmul(x1, x2)
  884. >>> print(output)
  885. [[[ 70. 76. 82. 88. 94.]
  886. [ 190. 212. 234. 256. 278.]
  887. [ 310. 348. 386. 424. 462.]]
  888. [[ 430. 484. 538. 592. 646.]
  889. [ 550. 620. 690. 760. 830.]
  890. [ 670. 756. 842. 928. 1014.]]]
  891. """
  892. return C.matmul(x1, x2, dtype=dtype)
  893. def square(x, dtype=None):
  894. """
  895. Returns the element-wise square of the input.
  896. Note:
  897. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  898. not supported.
  899. On GPU, the supported dtypes are np.float16 and np.float32.
  900. Args:
  901. x (Tensor): Input data.
  902. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  903. output Tensor.
  904. Returns:
  905. Tensor or scalar, element-wise ``x*x``, of the same shape and dtype as `x`.
  906. This is a scalar if `x` is a scalar..
  907. Supported Platforms:
  908. ``Ascend`` ``GPU`` ``CPU``
  909. Examples:
  910. >>> import mindspore.numpy as np
  911. >>> x = np.square(np.arange(6).reshape(2, 3).astype('float32'))
  912. >>> print(x)
  913. [[ 0. 1. 4.]
  914. [ 9. 16. 25.]]
  915. """
  916. return _apply_tensor_op(F.square, x, dtype=dtype)
  917. def sqrt(x, dtype=None):
  918. """
  919. Returns the non-negative square-root of an array, element-wise.
  920. Note:
  921. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  922. not supported.
  923. On GPU, the supported dtypes are np.float16 and np.float32.
  924. Args:
  925. x (Tensor): The values whose square-roots are required.
  926. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  927. output Tensor.
  928. Returns:
  929. Tensor or scalar, an array of the same shape as `x`, containing the positive
  930. square-root of each element in `x`. For negative elements, nan is returned.
  931. This is a scalar if `x` is a scalar.
  932. Supported Platforms:
  933. ``Ascend`` ``GPU`` ``CPU``
  934. Examples:
  935. >>> import mindspore.numpy as np
  936. >>> x = np.arange(6).reshape(2, 3).astype('float32')
  937. >>> x_squared = np.square(x)
  938. >>> output = np.sqrt(x_squared)
  939. >>> print(output)
  940. [[ 0. 1. 2.]
  941. [ 3. 4. 5.]]
  942. """
  943. return _apply_tensor_op(F.sqrt, x, dtype=dtype)
  944. def reciprocal(x, dtype=None):
  945. """
  946. Returns the reciprocal of the argument, element-wise.
  947. Calculates ``1/x``.
  948. Note:
  949. Numpy arguments `casting`, `order`, `subok`, `signature`, and `extobj` are
  950. not supported.
  951. When `where` is provided, `out` must have a tensor value. `out` is not supported
  952. for storing the result, however it can be used in combination with `where` to set
  953. the value at indices for which `where` is set to False.
  954. Args:
  955. x (Tensor): Input array. For integer arguments with absolute value larger
  956. than 1 the result is always zero because of the way Python handles
  957. integer division. For integer zero the result is an overflow.
  958. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  959. output Tensor.
  960. Returns:
  961. Tensor or scalar, this is a scalar if `x` is a scalar.
  962. Supported Platforms:
  963. ``Ascend`` ``GPU`` ``CPU``
  964. Examples:
  965. >>> import mindspore.numpy as np
  966. >>> x = np.arange(1, 7).reshape(2, 3).astype('float32')
  967. >>> output = np.reciprocal(x)
  968. >>> print(output)
  969. [[1. 0.5 0.33333334]
  970. [0.25 0.2 0.16666667]]
  971. """
  972. return _apply_tensor_op(lambda x: F.tensor_div(1, x), x, dtype=dtype)
  973. def log(x, dtype=None):
  974. """
  975. Returns the natural logarithm, element-wise.
  976. The natural logarithm log is the inverse of the exponential function, so that
  977. ``log(exp(x)) = x``. The natural logarithm is logarithm in base e.
  978. Note:
  979. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  980. not supported.
  981. On GPU, the supported dtypes are np.float16, and np.float32.
  982. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  983. Args:
  984. x (Tensor): Input array.
  985. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  986. output Tensor.
  987. Returns:
  988. Tensor or scalar, the natural logarithm of `x`, element-wise. This is a
  989. scalar if `x` is a scalar.
  990. Supported Platforms:
  991. ``Ascend`` ``GPU`` ``CPU``
  992. Examples:
  993. >>> import mindspore.numpy as np
  994. >>> x = np.array([2, 3, 4]).astype('float32')
  995. >>> output = np.log(x)
  996. >>> print(output)
  997. [0.69314575 1.09861 1.3862929 ]
  998. """
  999. return _apply_tensor_op(F.log, x, dtype=dtype)
  1000. def _prop_nan(fn, x1, x2):
  1001. """Selects NaN if either element is NaN"""
  1002. has_nan = F.logical_or(_isnan(x1), _isnan(x2))
  1003. nan_tensor = F.fill(_promote(F.dtype(x1), F.dtype(x2)), F.shape(has_nan), nan)
  1004. res = fn(x1, x2)
  1005. return F.select(has_nan, nan_tensor, res)
  1006. def maximum(x1, x2, dtype=None):
  1007. """
  1008. Returns the element-wise maximum of array elements.
  1009. Compares two arrays and returns a new array containing the element-wise maxima.
  1010. Note:
  1011. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1012. not supported.
  1013. On Ascend, input arrays containing inf or NaN are not supported.
  1014. Args:
  1015. x1 (Tensor): Input array
  1016. x2 (Tensor): The array holding the elements to be compared. If
  1017. ``x1.shape != x2.shape``, they must be broadcastable to a common shape
  1018. (which becomes the shape of the output).
  1019. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1020. output Tensor.
  1021. Returns:
  1022. Tensor or scalar, the maximum of `x1` and `x2`, element-wise. This is a scalar
  1023. if both `x1` and `x2` are scalars.
  1024. Supported Platforms:
  1025. ``Ascend`` ``GPU`` ``CPU``
  1026. Examples:
  1027. >>> import mindspore.numpy as np
  1028. >>> output = np.maximum(np.array([2, 3, 4]), np.array([1, 5, 2]))
  1029. >>> print(output)
  1030. [2 5 4]
  1031. """
  1032. if isinstance(x1, (int, float, bool, list, tuple)):
  1033. x1 = asarray_const(x1)
  1034. elif not isinstance(x1, Tensor):
  1035. _raise_type_error("Input x1 is expected to be array_like")
  1036. if isinstance(x2, (int, float, bool, list, tuple)):
  1037. x2 = asarray_const(x2)
  1038. elif not isinstance(x2, Tensor):
  1039. _raise_type_error("Input x2 is expected to be array_like")
  1040. # F.maximum does not support when both operands are scalar
  1041. if x1.ndim == 0 and x2.ndim == 0:
  1042. x1 = expand_dims(x1, 0)
  1043. return _apply_tensor_op(functools.partial(_prop_nan, F.maximum), x1, x2, dtype=dtype).squeeze()
  1044. if x1.ndim == 0:
  1045. dtype = x2.dtype
  1046. elif x2.ndim == 0:
  1047. dtype = x1.dtype
  1048. return _apply_tensor_op(functools.partial(_prop_nan, F.maximum), x1, x2, dtype=dtype)
  1049. def heaviside(x1, x2, dtype=None):
  1050. """
  1051. Computes the Heaviside step function.
  1052. Note:
  1053. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1054. not supported.
  1055. Args:
  1056. x1 (Tensor): Input values.
  1057. x2 (Tensor): The value of the function when `x1` is 0. If
  1058. ``x1.shape != x2.shape``, they must be broadcastable to a common shape
  1059. (which becomes the shape of the output).
  1060. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1061. output Tensor.
  1062. Returns:
  1063. Tensor or scalar, the output array, element-wise Heaviside step function
  1064. of `x1`. This is a scalar if both `x1` and `x2` are scalars.
  1065. Supported Platforms:
  1066. ``Ascend`` ``GPU`` ``CPU``
  1067. Examples:
  1068. >>> import mindspore.numpy as np
  1069. >>> output = np.heaviside(np.array([-1.5, 0, 2.0]), np.array(0.5))
  1070. >>> print(output)
  1071. [0. 0.5 1. ]
  1072. >>> output = np.heaviside(np.array([-1.5, 0, 2.0]), np.array(1))
  1073. >>> print(output)
  1074. [0. 1. 1.]
  1075. """
  1076. def _heaviside(x1, x2):
  1077. """Computes heaviside without passing keyword arguments"""
  1078. # performs type promotion
  1079. dtype1 = F.dtype(x1)
  1080. dtype2 = F.dtype(x2)
  1081. dtype_out = _promote(dtype1, dtype2)
  1082. if not _check_same_type(dtype1, dtype_out):
  1083. x1 = F.cast(x1, dtype_out)
  1084. if not _check_same_type(dtype2, dtype_out):
  1085. x2 = F.cast(x2, dtype_out)
  1086. # performs broadcast
  1087. shape_out = _infer_out_shape(F.shape(x1), F.shape(x2))
  1088. x1 = _broadcast_to_shape(x1, shape_out)
  1089. x2 = _broadcast_to_shape(x2, shape_out)
  1090. x2 = F.select(x1 < 0, zeros(shape_out, dtype_out), x2)
  1091. x2 = F.select(x1 > 0, ones(shape_out, dtype_out), x2)
  1092. return x2
  1093. return _apply_tensor_op(_heaviside, x1, x2, dtype=dtype)
  1094. def amax(a, axis=None, keepdims=False, initial=None, where=True):
  1095. """
  1096. Returns the maximum of an array or maximum along an axis.
  1097. Note:
  1098. Numpy argument `out` is not supported.
  1099. On GPU, the supported dtypes are np.float16, and np.float32.
  1100. Args:
  1101. a (Tensor): Input data.
  1102. axis (None or int or tuple of ints, optional): defaults to None. Axis or
  1103. axes along which to operate. By default, flattened input is used. If
  1104. this is a tuple of ints, the maximum is selected over multiple axes,
  1105. instead of a single axis or all the axes as before.
  1106. keepdims (boolean, optional): defaults to False.
  1107. If this is set to True, the axes which are reduced are left in the
  1108. result as dimensions with size one. With this option, the result will
  1109. broadcast correctly against the input array.
  1110. initial (scalar, optional):
  1111. The minimum value of an output element. Must be present to allow
  1112. computation on empty slice.
  1113. where (boolean Tensor, optional): defaults to True.
  1114. A boolean array which is broadcasted to match the dimensions of array,
  1115. and selects elements to include in the reduction. If non-default value
  1116. is passed, initial must also be provided.
  1117. Returns:
  1118. Tensor or scalar, maximum of `a`. If `axis` is None, the result is a scalar
  1119. value. If `axis` is given, the result is an array of dimension ``a.ndim - 1``.
  1120. Raises:
  1121. TypeError: if the input is not a tensor.
  1122. Supported Platforms:
  1123. ``Ascend`` ``GPU`` ``CPU``
  1124. Examples:
  1125. >>> import mindspore.numpy as np
  1126. >>> a = np.arange(4).reshape((2,2)).astype('float32')
  1127. >>> output = np.amax(a)
  1128. >>> print(output)
  1129. 3.0
  1130. >>> output = np.amax(a, axis=0)
  1131. >>> print(output)
  1132. [2. 3.]
  1133. >>> output = np.amax(a, axis=1)
  1134. >>> print(output)
  1135. [1. 3.]
  1136. >>> output = np.amax(a, where=np.array([False, True]), initial=-1, axis=0)
  1137. >>> print(output)
  1138. [-1. 3.]
  1139. """
  1140. return a.max(axis, keepdims, initial, where)
  1141. def amin(a, axis=None, keepdims=False, initial=None, where=True):
  1142. """
  1143. Returns the minimum of an array or minimum along an axis.
  1144. Note:
  1145. Numpy argument `out` is not supported.
  1146. On GPU, the supported dtypes are np.float16, and np.float32.
  1147. Args:
  1148. a (Tensor): Input data.
  1149. axis (None or int or tuple of ints, optional): defaults to None. Axis or
  1150. axes along which to operate. By default, flattened input is used. If
  1151. this is a tuple of ints, the minimum is selected over multiple axes,
  1152. instead of a single axis or all the axes as before.
  1153. keepdims (boolean, optional): defaults to False.
  1154. If this is set to True, the axes which are reduced are left in the
  1155. result as dimensions with size one. With this option, the result will
  1156. broadcast correctly against the input array.
  1157. initial (scalar, optional):
  1158. The maximum value of an output element. Must be present to allow
  1159. computation on empty slice.
  1160. where (boolean Tensor, optional): defaults to True.
  1161. A boolean array which is broadcasted to match the dimensions of array,
  1162. and selects elements to include in the reduction. If non-default value
  1163. is passed, initial must also be provided.
  1164. Returns:
  1165. Tensor or scalar, minimum of `a`. If axis is None, the result is a scalar
  1166. value. If `axis` is given, the result is an array of dimension ``a.ndim - 1``.
  1167. Raises:
  1168. TypeError: if the input is not a tensor.
  1169. Supported Platforms:
  1170. ``Ascend`` ``GPU`` ``CPU``
  1171. Examples:
  1172. >>> import mindspore.numpy as np
  1173. >>> a = np.arange(4).reshape((2,2)).astype('float32')
  1174. >>> output = np.amin(a)
  1175. >>> print(output)
  1176. 0.0
  1177. >>> output = np.amin(a, axis=0)
  1178. >>> print(output)
  1179. [0. 1.]
  1180. >>> output = np.amin(a, axis=1)
  1181. >>> print(output)
  1182. [0. 2.]
  1183. >>> output = np.amin(a, where=np.array([False, True]), initial=10, axis=0)
  1184. >>> print(output)
  1185. [10. 1.]
  1186. """
  1187. return a.min(axis, keepdims, initial, where)
  1188. def hypot(x1, x2, dtype=None):
  1189. """
  1190. Given the “legs” of a right triangle, returns its hypotenuse.
  1191. Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or `x2` is scalar_like
  1192. (i.e., unambiguously cast-able to a scalar type), it is broadcast for use
  1193. with each element of the other argument. (See Examples)
  1194. Note:
  1195. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1196. not supported.
  1197. On GPU, the supported dtypes are np.float16 and np.float32.
  1198. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  1199. Args:
  1200. x1 (Tensor): Leg of the traingle(s).
  1201. x2 (Tensor): Leg of the triangle(s). If ``x1.shape != x2.shape``, they
  1202. must be broadcastable to a common shape (which becomes the shape of
  1203. the output).
  1204. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1205. output Tensor.
  1206. Returns:
  1207. Tensor or scalar, the hypotenuse of the triangle(s). This is a scalar if
  1208. both `x1` and `x2` are scalars.
  1209. Supported Platforms:
  1210. ``Ascend`` ``GPU`` ``CPU``
  1211. Examples:
  1212. >>> import mindspore.numpy as np
  1213. >>> output = np.hypot(3*np.ones((3, 3)), 4*np.ones((3, 3)))
  1214. >>> print(output)
  1215. [[5. 5. 5.]
  1216. [5. 5. 5.]
  1217. [5. 5. 5.]]
  1218. >>> output = np.hypot(3*np.ones((3, 3)), np.array([4.0]))
  1219. >>> print(output)
  1220. [[5. 5. 5.]
  1221. [5. 5. 5.]
  1222. [5. 5. 5.]]
  1223. """
  1224. def _hypot(x1, x2):
  1225. """Computes hypotenuse without passing keyword arguments"""
  1226. if _get_device() == 'CPU':
  1227. # broadcast is not fully supported in tensor_add on CPU,
  1228. # so we use tensor_sub as a substitute solution
  1229. return F.sqrt(F.tensor_sub(F.square(x1), F.neg_tensor(F.square(x2))))
  1230. return F.sqrt(F.tensor_add(F.square(x1), F.square(x2)))
  1231. return _apply_tensor_op(_hypot, x1, x2, dtype=dtype)
  1232. def floor(x, dtype=None):
  1233. """
  1234. Returns the floor of the input, element-wise.
  1235. The floor of the scalar `x` is the largest integer `i`, such that ``i <= x``.
  1236. Note:
  1237. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1238. not supported.
  1239. On GPU, the supported dtypes are np.float16 and np.float32.
  1240. On CPU, the supported dtypes are np.float16, np.float32, and np.float64.
  1241. Args:
  1242. x (Tensor): input data.
  1243. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1244. output Tensor.
  1245. Returns:
  1246. Tensor or scalar, the floor of each element in `x`. This is a scalar if `x`
  1247. is a scalar.
  1248. Supported Platforms:
  1249. ``Ascend`` ``GPU`` ``CPU``
  1250. Examples:
  1251. >>> import mindspore.numpy as np
  1252. >>> output = np.floor(np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]))
  1253. >>> print(output)
  1254. [-2. -2. -1. 0. 1. 1. 2.]
  1255. """
  1256. return _apply_tensor_op(F.floor, x, dtype=dtype)
  1257. def floor_divide(x1, x2, dtype=None):
  1258. """
  1259. Returns the largest integer smaller or equal to the division of the inputs.
  1260. It is equivalent to the Python // operator and pairs with the
  1261. Python % (remainder), function so that ``a = a % b + b * (a // b)`` up to roundoff.
  1262. Note:
  1263. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1264. not supported.
  1265. Args:
  1266. x1 (Tensor): Input array.
  1267. x2 (Tensor): Input array.
  1268. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1269. output Tensor.
  1270. Returns:
  1271. Tensor or scalar.
  1272. Supported Platforms:
  1273. ``Ascend`` ``GPU`` ``CPU``
  1274. Examples:
  1275. >>> import mindspore.numpy as np
  1276. >>> output = np.floor_divide(np.array([1., 2., 3., 4.]), np.array(2.5))
  1277. >>> print(output)
  1278. [0. 0. 1. 1.]
  1279. """
  1280. return _apply_tensor_op(F.tensor_floordiv, x1, x2, dtype=dtype)
  1281. def _remainder(x1, x2, c_style=False):
  1282. """Computes remainder without applying keyword arguments."""
  1283. dtype = _promote(F.dtype(x1), F.dtype(x2))
  1284. if not _check_is_float(dtype):
  1285. x1 = F.cast(x1, mstype.float32)
  1286. x2 = F.cast(x2, mstype.float32)
  1287. quotient = F.tensor_div(x1, x2)
  1288. if c_style:
  1289. quotient = fix(quotient)
  1290. else:
  1291. quotient = F.floor(quotient)
  1292. prod = F.tensor_mul(x2, quotient)
  1293. res = F.tensor_sub(x1, prod)
  1294. if _check_is_int(dtype):
  1295. zeros_tensor = zeros(F.shape(quotient), F.dtype(quotient))
  1296. x2_zeros = F.equal(x2, zeros_tensor)
  1297. res = F.select(x2_zeros, zeros_tensor, res)
  1298. if not _check_same_type(F.dtype(res), dtype):
  1299. res = F.cast(res, dtype)
  1300. return res
  1301. def remainder(x1, x2, dtype=None):
  1302. """
  1303. Returns element-wise remainder of division.
  1304. Computes the remainder complementary to the floor_divide function. It is
  1305. equivalent to the Python modulus operator ``x1 % x2`` and has the same sign
  1306. as the divisor `x2`. The MATLAB function equivalent to np.remainder is mod.
  1307. Note:
  1308. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1309. not supported.
  1310. Args:
  1311. x1 (Tensor): input array.
  1312. x2 (Tensor): input array.
  1313. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1314. output Tensor.
  1315. Returns:
  1316. Tensor or scalar, the element-wise remainder of the quotient
  1317. ``floor_divide(x1, x2)``. This is a scalar if both `x1` and `x2` are scalars.
  1318. Supported Platforms:
  1319. ``Ascend`` ``GPU`` ``CPU``
  1320. Examples:
  1321. >>> import mindspore.numpy as np
  1322. >>> output = np.remainder(np.array([4, 7]), np.array([2, 3]))
  1323. >>> print(output)
  1324. [0 1]
  1325. >>> output = np.remainder(np.arange(7), np.array(5))
  1326. >>> print(output)
  1327. [0 1 2 3 4 0 1]
  1328. """
  1329. return _apply_tensor_op(_remainder, x1, x2, dtype=dtype)
  1330. def fix(x):
  1331. """
  1332. Rounds to nearest integer towards zero.
  1333. Rounds an array of floats element-wise to nearest integer towards zero. The
  1334. rounded values are returned as floats.
  1335. Note:
  1336. Numpy argument `out` is not supported.
  1337. Args:
  1338. x (Tensor): An array of floats to be rounded.
  1339. Returns:
  1340. Tensor.
  1341. Raises:
  1342. TypeError: if the input is not a tensor.
  1343. Supported Platforms:
  1344. ``Ascend`` ``GPU`` ``CPU``
  1345. Examples:
  1346. >>> import mindspore.numpy as np
  1347. >>> output = np.fix(np.array([2.1, 2.9, -2.1, -2.9]))
  1348. >>> print(output)
  1349. [ 2. 2. -2. -2.]
  1350. """
  1351. _check_input_tensor(x)
  1352. if not _check_is_float(F.dtype(x)):
  1353. x = F.cast(x, mstype.float32)
  1354. floored = F.floor(x)
  1355. # change to F.ceil once supported on CPU.
  1356. ceiled = F.neg_tensor(F.floor(F.neg_tensor(x)))
  1357. is_neg = F.tensor_lt(x, zeros(F.shape(x), F.dtype(x)))
  1358. return F.select(is_neg, ceiled, floored)
  1359. def fmod(x1, x2, dtype=None):
  1360. """
  1361. Returns the element-wise remainder of division.
  1362. This is the NumPy implementation of the C library function fmod, the remainder
  1363. has the same sign as the dividend `x1`. It is equivalent to the Matlab(TM) rem
  1364. function and should not be confused with the Python modulus operator ``x1 % x2``.
  1365. Note:
  1366. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1367. not supported.
  1368. Args:
  1369. x1 (Tensor)
  1370. x2 (Tensor): input arrays.
  1371. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1372. output Tensor.
  1373. Returns:
  1374. Tensor or scalar, the remainder of the division of `x1` by `x2`. This is a
  1375. scalar if both `x1` and `x2` are scalars.
  1376. Supported Platforms:
  1377. ``Ascend`` ``GPU`` ``CPU``
  1378. Examples:
  1379. >>> import mindspore.numpy as np
  1380. >>> output = np.fmod(np.array([-3, -2, -1, 1, 2, 3]), np.array(2))
  1381. >>> print(output)
  1382. [-1 0 -1 1 0 1]
  1383. """
  1384. return _apply_tensor_op(lambda x1, x2: _remainder(x1, x2, c_style=True), x1, x2, dtype=dtype)
  1385. def trunc(x, dtype=None):
  1386. """
  1387. Returns the truncated value of the input, element-wise.
  1388. The truncated value of the scalar `x` is the nearest integer `i` which is closer to zero
  1389. than `x` is. In short, the fractional part of the signed number `x` is discarded.
  1390. Note:
  1391. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1392. not supported.
  1393. Args:
  1394. x (Tensor): input data.
  1395. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1396. output Tensor.
  1397. Returns:
  1398. Tensor or scalar, the truncated value of each element in `x`. This is a scalar if `x` is
  1399. a scalar.
  1400. Supported Platforms:
  1401. ``Ascend`` ``GPU`` ``CPU``
  1402. Examples:
  1403. >>> import mindspore.numpy as np
  1404. >>> output = np.trunc(np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]))
  1405. >>> print(output)
  1406. [-1. -1. -0. 0. 1. 1. 2.]
  1407. """
  1408. return _apply_tensor_op(fix, x, dtype=dtype)
  1409. def exp(x, dtype=None):
  1410. """
  1411. Calculates the exponential of all elements in the input array.
  1412. Note:
  1413. Numpy arguments `casting`, `order`, `subok`, `signature`, and `extobj` are
  1414. not supported.
  1415. When `where` is provided, `out` must have a tensor value. `out` is not supported
  1416. for storing the result, however it can be used in combination with `where` to set
  1417. the value at indices for which `where` is set to False.
  1418. On GPU, the supported dtypes are np.float16, and np.float32.
  1419. On CPU, the supported dtypes are np.float16, np.float32, np.float64.
  1420. Args:
  1421. x (Tensor): input data.
  1422. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1423. output Tensor.
  1424. Returns:
  1425. Tensor or scalar, element-wise exponential of `x`. This is a scalar if both
  1426. `x1` and `x2` are scalars.
  1427. Supported Platforms:
  1428. ``Ascend`` ``GPU`` ``CPU``
  1429. Examples:
  1430. >>> import mindspore.numpy as np
  1431. >>> output = np.exp(np.arange(5).astype(np.float32))
  1432. >>> print(output)
  1433. [ 1. 2.718282 7.3890557 20.085537 54.598145 ]
  1434. """
  1435. return _apply_tensor_op(F.tensor_exp, x, dtype=dtype)
  1436. def expm1(x, dtype=None):
  1437. """
  1438. Calculates ``exp(x) - 1`` for all elements in the array.
  1439. Note:
  1440. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1441. not supported.
  1442. On GPU, the supported dtypes are np.float16, and np.float32.
  1443. On CPU, the supported dtypes are np.float16, and np.float32.
  1444. Args:
  1445. x (Tensor): input data.
  1446. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1447. output Tensor.
  1448. Returns:
  1449. Tensor or scalar, element-wise exponential minus one, ``out = exp(x) - 1``.
  1450. This is a scalar if both `x1` and `x2` are scalars.
  1451. Supported Platforms:
  1452. ``Ascend`` ``GPU`` ``CPU``
  1453. Examples:
  1454. >>> import mindspore.numpy as np
  1455. >>> output = np.expm1(np.arange(5).astype(np.float32))
  1456. >>> print(output)
  1457. [ 0. 1.7182819 6.389056 19.085537 53.59815 ]
  1458. """
  1459. return _apply_tensor_op(F.tensor_expm1, x, dtype=dtype)
  1460. def divmod_(x1, x2, dtype=None):
  1461. """
  1462. Returns element-wise quotient and remainder simultaneously.
  1463. Args:
  1464. x1(Union[Tensor]): Dividend tensor.
  1465. x2(Union[Tensor, int, float, bool]): Divisor. If ``x1.shape != x2.shape``,
  1466. they must be broadcastable to a common shape.
  1467. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1468. output Tensor.
  1469. Returns:
  1470. Element-wise quotient and remainder from floor division, in format of (quotient, remainder)
  1471. Raises:
  1472. TypeError: if `x1` and `x2` are not Tensor or scalar.
  1473. Supported Platforms:
  1474. ``Ascend`` ``GPU`` ``CPU``
  1475. Examples:
  1476. >>> import mindspore.numpy as np
  1477. >>> a = np.array([1, 2, 3, 4, 5])
  1478. >>> print(np.divmod(a, 1.5))
  1479. (Tensor(shape=[5], dtype=Float32,
  1480. value= [ 0.00000000e+00, 1.00000000e+00, 2.00000000e+00, 2.00000000e+00, 3.00000000e+00]),
  1481. Tensor(shape=[5], dtype=Float32,
  1482. value= [ 1.00000000e+00, 5.00000000e-01, 0.00000000e+00, 1.00000000e+00, 5.00000000e-01]))
  1483. """
  1484. q = F.tensor_floordiv(x1, x2)
  1485. r = remainder(x1, x2)
  1486. if dtype is not None:
  1487. q = q.astype(dtype)
  1488. r = r.astype(dtype)
  1489. return (q, r)
  1490. def _handle_prepend_append(combined, tensor, additional_tensor, axis):
  1491. """Concatenates prepend or append to tensor."""
  1492. if isinstance(additional_tensor, (int, float, bool)):
  1493. additional_tensor = asarray_const(additional_tensor)
  1494. elif not isinstance(additional_tensor, Tensor):
  1495. _raise_type_error("prepend must be scalar or Tensor, but got ", additional_tensor)
  1496. additional_shape = tensor.shape
  1497. additional_shape = _tuple_setitem(additional_shape, axis, 1)
  1498. additional_tensor = _broadcast_to_shape(additional_tensor, additional_shape)
  1499. combined += (additional_tensor,)
  1500. return combined
  1501. def diff(a, n=1, axis=-1, prepend=None, append=None):
  1502. """
  1503. Calculates the n-th discrete difference along the given axis.
  1504. The first difference is given by :math:`out[i] = a[i+1] - a[i]` along the given axis,
  1505. higher differences are calculated by using `diff` iteratively.
  1506. Note:
  1507. Since zero-shaped Tensor is not supported in MindSpore, a value error is raised if
  1508. an empty Tensor is encountered.
  1509. Args:
  1510. a (Tensor): Input tensor.
  1511. n (int, optional): The number of times values are differenced. If zero,
  1512. the input is returned as-is.
  1513. axis (int, optional): The axis along which the difference is taken, default
  1514. is the last axis.
  1515. prepend/append (Tensor, optional): Values to prepend or append to a along
  1516. `axis` prior to performing the difference. Scalar values are expanded to
  1517. arrays with length 1 in the direction of `axis` and the shape of the input
  1518. array in along all other axes. Otherwise the dimension and shape must
  1519. match `a` except along axis.
  1520. Returns:
  1521. The n-th differences. The shape of the output is the same as a except along
  1522. `axis` where the dimension is smaller by `n`. The type of the output is the same
  1523. as the type of the difference between any two elements of `a`. This is the same
  1524. as the type of `a` in most cases.
  1525. Raises:
  1526. TypeError: If inputs have types not specified above.
  1527. ValueError: If ``n < 0``.
  1528. Supported Platforms:
  1529. ``Ascend`` ``GPU`` ``CPU``
  1530. Examples:
  1531. >>> import mindspore.numpy as np
  1532. >>> arr = np.array([1, 3, -1, 0, 4])
  1533. >>> print(np.diff(arr, n=2))
  1534. [-6 5 3]
  1535. """
  1536. # This implementation is inspired by jax.numpy
  1537. _check_input_tensor(a)
  1538. axis = _canonicalize_axis(axis, a.ndim)
  1539. if not isinstance(n, int):
  1540. _raise_type_error("Input n should be int, but got ", n)
  1541. if n < 0:
  1542. _raise_value_error("Input n must > 0.")
  1543. if n == 0:
  1544. return a
  1545. combined = ()
  1546. if prepend is not None:
  1547. combined = _handle_prepend_append(combined, a, prepend, axis)
  1548. combined += (a,)
  1549. if append is not None:
  1550. combined = _handle_prepend_append(combined, a, append, axis)
  1551. if combined:
  1552. a = concatenate(combined, axis)
  1553. # if n > maximum length allowed, the tensor is empty, and is not supported
  1554. if n >= a.shape[axis]:
  1555. _raise_value_error("n is bigger then the specified dimension, this will result in an empty tensor.")
  1556. original_dtype = a.dtype
  1557. # will change once F.tensor_slice supports types other than float32
  1558. if not _check_is_float(original_dtype):
  1559. a = a.astype(mstype.float32)
  1560. a = moveaxis(a, axis, -1)
  1561. for _ in F.make_range(n):
  1562. slice_start = _list_comprehensions(F.rank(a) - 1, 0, True)
  1563. slice_size = F.shape(a)[:-1] + (F.shape(a)[-1] - 1,)
  1564. minuend = F.tensor_slice(a, slice_start + (1,), slice_size)
  1565. subtrahend = F.tensor_slice(a, slice_start + (0,), slice_size)
  1566. a = F.tensor_sub(minuend, subtrahend)
  1567. if not _check_is_float(original_dtype):
  1568. a = a.astype(original_dtype)
  1569. return moveaxis(a, -1, axis)
  1570. def ediff1d(ary, to_end=None, to_begin=None):
  1571. """
  1572. The differences between consecutive elements of a tensor.
  1573. Args:
  1574. ary (Tensor): If necessary, will be flattened before the differences are taken.
  1575. to_end (Tensor or scalar, optional): Number(s) to append at the end of the
  1576. returned differences.
  1577. to_begin (Tensor or scalar, optional): Number(s) to prepend at the beginning
  1578. of the returned differences.
  1579. Returns:
  1580. The differences.
  1581. Raises:
  1582. TypeError: If inputs have types not specified above.
  1583. Supported Platforms:
  1584. ``Ascend`` ``GPU`` ``CPU``
  1585. Examples:
  1586. >>> import mindspore.numpy as np
  1587. >>> arr = np.array([1, 3, -1, 0, 4])
  1588. >>> print(np.ediff1d(arr))
  1589. [ 2 -4 1 4]
  1590. """
  1591. _check_input_tensor(ary)
  1592. combined = ()
  1593. if to_begin is not None:
  1594. if isinstance(to_begin, Tensor):
  1595. to_begin = to_begin.ravel()
  1596. else:
  1597. to_begin = _to_tensor(to_begin).ravel()
  1598. to_begin = to_begin.astype(ary.dtype)
  1599. combined += (to_begin,)
  1600. combined += (diff(ary.ravel()),)
  1601. if to_end is not None:
  1602. if isinstance(to_end, Tensor):
  1603. to_end = to_end.ravel()
  1604. else:
  1605. to_end = _to_tensor(to_end).ravel()
  1606. to_end = to_end.astype(ary.dtype)
  1607. combined += (to_end,)
  1608. return P.Concat(0)(combined)
  1609. def trapz(y, x=None, dx=1.0, axis=-1):
  1610. """
  1611. Integrates along the given axis using the composite trapezoidal rule.
  1612. Integrates `y` (x) along given axis.
  1613. Args:
  1614. y (Tensor): Input array to integrate.
  1615. x (Union[int, float, bool, list, tuple, Tensor], optional): The sample points
  1616. corresponding to the `y` values. If `x` is None, the sample points are
  1617. assumed to be evenly spaced `dx` apart. The default is None.
  1618. dx (scalar, optional): The spacing between sample points when `x` is None. The
  1619. default is 1.
  1620. axis (int, optional): The axis along which to integrate.
  1621. Returns:
  1622. Tensor of float, definite integral as approximated by trapezoidal rule.
  1623. Raises:
  1624. ValueError: If axis is out of range of ``[-y.ndim, y.ndim)``.
  1625. Supported Platforms:
  1626. ``Ascend`` ``GPU`` ``CPU``
  1627. Examples:
  1628. >>> import mindspore.numpy as np
  1629. >>> a = np.arange(6).reshape(2, 3)
  1630. >>> output = np.trapz(a, x=[-2, 1, 2], axis=1)
  1631. >>> print(output)
  1632. [ 3. 15.]
  1633. >>> output = np.trapz(a, dx=3, axis=0)
  1634. >>> print(output)
  1635. [ 4.5 7.5 10.5]
  1636. """
  1637. y = _to_tensor(y)
  1638. ndim = F.rank(y)
  1639. _check_axis_in_range(axis, ndim)
  1640. axis = axis + ndim if axis < 0 else axis
  1641. y_start_axis_left = _list_comprehensions(axis, 0, True)
  1642. y_start_axis_right = _list_comprehensions(ndim - axis - 1, 0, True)
  1643. shape = F.shape(y)
  1644. y_slice_size = _tuple_setitem(shape, axis, shape[axis] - 1)
  1645. if x is not None:
  1646. x = _to_tensor(x)
  1647. dx = diff(x)
  1648. else:
  1649. dx = _to_tensor(dx)
  1650. dx = _expand(dx, ndim - axis, axis=-1)
  1651. dx = _broadcast_to_shape(dx, y_slice_size)
  1652. if not _check_is_float(F.dtype(y)):
  1653. # trapz returns float
  1654. y = F.cast(y, mstype.float32)
  1655. dx = F.cast(dx, F.dtype(y))
  1656. # product of dx and y with the last column removed
  1657. y_slice_left = F.tensor_slice(y, y_start_axis_left + (0,) + y_start_axis_right, y_slice_size)
  1658. prod_left = F.tensor_mul(y_slice_left, dx)
  1659. # product of dx and y with the first column removed
  1660. y_slice_right = F.tensor_slice(y, y_start_axis_left + (1,) + y_start_axis_right, y_slice_size)
  1661. prod_right = F.tensor_mul(y_slice_right, dx)
  1662. prod_sum = F.tensor_div(F.tensor_add(prod_left, prod_right), _to_tensor(2.0).astype(F.dtype(y)))
  1663. return F.reduce_sum(prod_sum, axis)
  1664. def _gcd(x1, x2):
  1665. """Calculates gcd without applying keyword arguments."""
  1666. dtype = _promote(F.dtype(x1), F.dtype(x2))
  1667. if not _check_is_float(dtype):
  1668. # F.reduce_sum only supports float
  1669. x1 = F.cast(x1, mstype.float32)
  1670. x2 = F.cast(x2, mstype.float32)
  1671. x1 = F.absolute(x1)
  1672. x2 = F.absolute(x2)
  1673. cond_ge = F.tensor_ge(x1, x2)
  1674. a = where_(cond_ge, x1, x2)
  1675. b = where_(cond_ge, x2, x1)
  1676. b = where_(F.equal(b, ZERO_TENSOR), a, b)
  1677. r = _remainder(a, b)
  1678. while F.tensor_gt(F.reduce_sum(r), ZERO_TENSOR):
  1679. r = _remainder(a, b)
  1680. has_terminated = F.equal(r, ZERO_TENSOR)
  1681. a = where_(has_terminated, a, b)
  1682. b = where_(has_terminated, b, r)
  1683. if not _check_same_type(F.dtype(b), dtype):
  1684. b = F.cast(b, dtype)
  1685. return b
  1686. def gcd(x1, x2, dtype=None):
  1687. """
  1688. Returns the greatest common divisor of ``|x1|`` and ``|x2|``.
  1689. Note:
  1690. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1691. not supported.
  1692. Args:
  1693. x1 (Tensor): input data.
  1694. x2 (Tensor): input data.
  1695. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1696. output Tensor.
  1697. Returns:
  1698. Tensor or scalar, the greatest common divisor of the absolute value of the inputs.
  1699. This is a scalar if both `x1` and `x2` are scalars.
  1700. Supported Platforms:
  1701. ``Ascend`` ``GPU`` ``CPU``
  1702. Examples:
  1703. >>> import mindspore.numpy as np
  1704. >>> output = np.gcd(np.arange(6), np.array(20))
  1705. >>> print(output)
  1706. [20 1 2 1 4 5]
  1707. """
  1708. return _apply_tensor_op(_gcd, x1, x2, dtype=dtype)
  1709. def lcm(x1, x2, dtype=None):
  1710. """
  1711. Returns the lowest common multiple of ``|x1|`` and ``|x2|``.
  1712. Note:
  1713. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  1714. not supported.
  1715. Args:
  1716. x1 (Tensor): input data.
  1717. x2 (Tensor): input data.
  1718. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1719. output Tensor.
  1720. Returns:
  1721. Tensor or scalar, the lowest common multiple of the absolute value of the inputs.
  1722. This is a scalar if both `x1` and `x2` are scalars.
  1723. Supported Platforms:
  1724. ``Ascend`` ``GPU`` ``CPU``
  1725. Examples:
  1726. >>> import mindspore.numpy as np
  1727. >>> output = np.lcm(np.arange(6), np.array(20))
  1728. >>> print(output)
  1729. [ 0 20 20 60 20 20]
  1730. """
  1731. def _lcm(x1, x2):
  1732. """Calculates lcm without applying keyword arguments"""
  1733. common_divisor = _gcd(x1, x2)
  1734. dtype = _promote(F.dtype(x1), F.dtype(x2))
  1735. x1 = x1.astype(mstype.float32)
  1736. x2 = x2.astype(mstype.float32)
  1737. q1 = F.tensor_div(x1, common_divisor)
  1738. q2 = F.tensor_div(x2, common_divisor)
  1739. res = F.tensor_mul(F.tensor_mul(q1, q2), common_divisor)
  1740. return F.absolute(res).astype(dtype)
  1741. return _apply_tensor_op(_lcm, x1, x2, dtype=dtype)
  1742. def convolve(a, v, mode='full'):
  1743. """
  1744. Returns the discrete, linear convolution of two one-dimensional sequences.
  1745. Note:
  1746. If `v` is longer than `a`, the tensors are swapped before computation.
  1747. Args:
  1748. a (Union[list, tuple, Tensor]): First one-dimensional input tensor.
  1749. v (Union[list, tuple, Tensor]): Second one-dimensional input tensor.
  1750. mode (str, optional): By default, mode is `\'full\'`. This returns the
  1751. convolution at each point of overlap, with an output shape of :math:`(N+M-1,)`.
  1752. At the end-points of the convolution, the signals do not overlap completely,
  1753. and boundary effects may be seen.
  1754. If `mode` is `\'same\'`, it returns output of length :math:`max(M, N)`. Boundary
  1755. effects are still visible.
  1756. If `mode` is `\'valid\'`, it returns output of length :math:`max(M, N) - min(M, N) + 1`.
  1757. The convolution product is only given for points where the signals overlap
  1758. completely. Values outside the signal boundary have no effect.
  1759. Returns:
  1760. Tensor, discrete, linear convolution of a and v.
  1761. Raises:
  1762. TypeError: if the inputs have types not specified above.
  1763. ValueError: if a and v are empty or have wrong dimensions
  1764. Supported Platforms:
  1765. ``GPU``
  1766. Examples:
  1767. >>> import mindspore.numpy as np
  1768. >>> output = np.convolve([1., 2., 3., 4., 5.], [2., 3.], mode="valid")
  1769. >>> print(output)
  1770. [ 3. 6. 9. 12.]
  1771. """
  1772. if not isinstance(a, Tensor):
  1773. a = asarray_const(a)
  1774. if not isinstance(v, Tensor):
  1775. v = asarray_const(v)
  1776. a_size = F.shape_mul(a.shape)
  1777. v_size = F.shape_mul(v.shape)
  1778. if a_size == 0 or v_size == 0:
  1779. _raise_value_error("Inputs cannot be empty.")
  1780. a = _expand(a, 1)
  1781. v = _expand(v, 1)
  1782. final_dtype = _promote(a.dtype, v.dtype)
  1783. a = a.astype("float32")
  1784. v = v.astype("float32")
  1785. if a.ndim != 1 or v.ndim != 1:
  1786. _raise_value_error("a and v must be 1-D tensor.")
  1787. if a_size < v_size:
  1788. a, v = v, a
  1789. a_size, v_size = v_size, a_size
  1790. v = v[::-1]
  1791. return _compute_1D_conv(a, v, mode).astype(final_dtype)
  1792. def _handle_weights(weights, num_samples):
  1793. """Checks fweight and aweight in np.cov."""
  1794. weights = asarray_const(weights)
  1795. if not _check_is_int(weights.dtype):
  1796. _raise_type_error("weights must be integer")
  1797. weights = weights.astype("float32")
  1798. if weights.ndim > 1:
  1799. _raise_runtime_error("cannot handle multidimensional weights")
  1800. if weights.shape[0] != num_samples:
  1801. _raise_runtime_error("incompatible numbers of samples and weights")
  1802. return absolute(weights)
  1803. def _handle_inputs(cov_input, rowvar):
  1804. """Checks input arrays for np.cov."""
  1805. if not isinstance(cov_input, Tensor):
  1806. cov_input = asarray_const(cov_input)
  1807. if cov_input.ndim > 2:
  1808. _raise_value_error("input array has dimension more than 2.")
  1809. cov_input = cov_input.astype("float32")
  1810. cov_input = _expand(cov_input, 2)
  1811. if not isinstance(rowvar, bool):
  1812. _raise_type_error("input rowvar should be boolean.")
  1813. if not rowvar and cov_input.shape[0] != 1:
  1814. cov_input = cov_input.T
  1815. return cov_input
  1816. def _handle_facts(w, m, ddof, aweights):
  1817. """Computes facts for np.cov"""
  1818. fact = None
  1819. if w is None:
  1820. fact = m.shape[1] - ddof
  1821. else:
  1822. w_sum = _reduce_sum_default(w, -1)
  1823. if ddof == 0:
  1824. fact = w_sum
  1825. elif aweights is None:
  1826. fact = w_sum - ddof
  1827. else:
  1828. fact = w_sum - ddof * F.reduce_sum(w * aweights) / w_sum
  1829. return fact
  1830. def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, dtype=None):
  1831. """
  1832. Estimates a covariance matrix, given data and weights.
  1833. Covariance indicates the level to which two variables vary together. If we examine
  1834. N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix
  1835. element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The element
  1836. :math:`C_{ii}` is the variance of :math:`x_i`.
  1837. Note:
  1838. `fweights` and `aweights` must be all positive, in Numpy if negative values
  1839. are detected, a value error will be raised, in MindSpore we converts all values
  1840. to positive instead.
  1841. Args:
  1842. m (Union[Tensor, list, tuple]): A 1-D or 2-D tensor containing multiple variables
  1843. and observations. Each row of `m` represents a variable, and each column
  1844. represents a single observation of all those variables. Also see `rowvar` below.
  1845. y (Union[Tensor, list, tuple], optional): An additional set of variables
  1846. and observations. `y` has the same form as that of `m`.
  1847. rowvar(bool, optional): If `rowvar` is ``True`` (default), then each row represents
  1848. a variable, with observations in the columns. Otherwise, the relationship
  1849. is transposed: each column represents a variable, while the rows contain
  1850. observations.
  1851. bias (bool, optional): Default Normalization (``False``) is by :math:`(N - 1)`, where
  1852. :math:`N` is the number of observations given (unbiased estimate). If bias is
  1853. ``True``, then Normalization is by `N`. These values can be overridden by
  1854. using the keyword `ddof`.
  1855. ddof (int, optional): If not ``None``, the default value implied by `bias` is
  1856. overridden. Note that :math:`ddof=1` will return the unbiased estimate, even
  1857. if both fweights and aweights are specified, and :math:`ddof=0` will return
  1858. the simple average. See the notes for the details. The default value
  1859. is ``None``.
  1860. fweights (Union[Tensor, list, tuple], optional): 1-D tensor of integer
  1861. frequency weights; the number of times each observation vector should
  1862. be repeated.
  1863. aweights (Union[Tensor, list, tuple], optional): 1-D tensor of observation
  1864. vector weights. These relative weights are typically larger for observations
  1865. considered more important and smaller for observations considered less
  1866. important. If :math:`ddof=0` the tensor of weights can be used to assign probabilities
  1867. to observation vectors.
  1868. dtype (Union[:class:`mindspore.dtype`, str], optional): Data-type of the
  1869. result. By default, the return data-type will have mstype.float32 precision.
  1870. Returns:
  1871. Tensor, the covariance matrix of the variables.
  1872. Raises:
  1873. TypeError: if the inputs have types not specified above.
  1874. ValueError: if `m` and `y` have wrong dimensions.
  1875. RuntimeError: if `aweights` and `fweights` have dimensions > 2.
  1876. Supported Platforms:
  1877. ``Ascend`` ``GPU`` ``CPU``
  1878. Examples:
  1879. >>> import mindspore.numpy as np
  1880. >>> output = np.cov([[2., 3., 4., 5.], [0., 2., 3., 4.], [7., 8., 9., 10.]])
  1881. >>> print(output)
  1882. [[1.6666666 2.1666667 1.6666666]
  1883. [2.1666667 2.9166667 2.1666667]
  1884. [1.6666666 2.1666667 1.6666666]]
  1885. """
  1886. # This implementation was inspired by original numpy implementation.
  1887. m = _handle_inputs(m, rowvar)
  1888. if m.shape[0] == 0:
  1889. return empty((0, 0), dtype="float32")
  1890. if y is not None:
  1891. y = _handle_inputs(y, rowvar)
  1892. m = concatenate((m, y), axis=0)
  1893. if ddof is None:
  1894. if not bias:
  1895. ddof = 1
  1896. else:
  1897. ddof = 0
  1898. # Handle fweights and aweights
  1899. w = _handle_weights(fweights, m.shape[1]) if fweights is not None else None
  1900. if aweights is not None:
  1901. aweights = _handle_weights(aweights, m.shape[1])
  1902. w = aweights if w is None else w * aweights
  1903. avg = average(m, axis=1, weights=w)
  1904. # Determine the Normalization
  1905. fact = _handle_facts(w, m, ddof, aweights)
  1906. m = m - F.expand_dims(avg, -1)
  1907. if w is None:
  1908. m_t = m.T
  1909. else:
  1910. m_t = (m * w).T
  1911. res = true_divide(dot(m, m_t), fact).squeeze()
  1912. if dtype is not None:
  1913. return res.astype(dtype)
  1914. return res
  1915. @constexpr
  1916. def _real_axes(ndim_orig, ndim_out, axes_orig):
  1917. """Returns the real axes to be reduced after performing broadcast"""
  1918. _diff = ndim_out - ndim_orig
  1919. axes = F.make_range(_diff)
  1920. axes_orig = map(functools.partial(operator.add, _diff), axes_orig)
  1921. return axes + tuple(axes_orig)
  1922. @constexpr
  1923. def _shape_reduced_keepdims(shape, axes):
  1924. """
  1925. Reduces dimensions corresponding to argument axes while
  1926. keeping the number of dimensions unchanged.
  1927. """
  1928. ndim_out = F.tuple_len(shape)
  1929. shape_out = [1]*ndim_out
  1930. for i in range(ndim_out):
  1931. if not i in axes:
  1932. shape_out[i] = shape[i]
  1933. return tuple(shape_out)
  1934. @constexpr
  1935. def _shape_reduced(shape, axes):
  1936. """Removes dimensions corresponding to argument axes"""
  1937. ndim_orig = F.tuple_len(shape)
  1938. ndim_out = ndim_orig - F.tuple_len(axes)
  1939. shape_out = [0]*ndim_out
  1940. idx_out = 0
  1941. for i in range(ndim_orig):
  1942. if not i in axes:
  1943. shape_out[idx_out] = shape[i]
  1944. idx_out += 1
  1945. return tuple(shape_out)
  1946. def _reduce(a, reduce_fn, cmp_fn=None, axis=None, keepdims=False, initial=None, where=True, dtype=None):
  1947. """
  1948. Applies comparison based on cmp_fn and reduction based on reduce_fn.
  1949. If cmp_fn is None, only reduction is performed.
  1950. """
  1951. a = _to_tensor(a)
  1952. shape = F.shape(a)
  1953. ndim = F.rank(a)
  1954. if dtype is None:
  1955. dtype = F.dtype(a)
  1956. axes = _check_axis_valid(axis, ndim)
  1957. if initial is not None:
  1958. if ((isinstance(initial, Tensor) and F.rank(initial) > 0) or
  1959. not isinstance(initial, (int, float, bool, Tensor))):
  1960. _raise_type_error('initial should be scalar')
  1961. if _is_shape_empty(shape):
  1962. if not axes:
  1963. return a
  1964. if keepdims:
  1965. shape_out = _shape_reduced_keepdims(shape, axes)
  1966. else:
  1967. shape_out = _shape_reduced(shape, axes)
  1968. if _is_shape_empty(shape_out):
  1969. return empty(shape_out, dtype)
  1970. if initial is None:
  1971. if cmp_fn is None:
  1972. initial = nan
  1973. else:
  1974. _raise_value_error('initial value must be provided for zero-size arrays')
  1975. return full(shape_out, initial, dtype)
  1976. if initial is not None:
  1977. initial = full(shape, initial, dtype)
  1978. a = cmp_fn(a, initial)
  1979. if isinstance(where, Tensor):
  1980. if initial is None:
  1981. _raise_value_error('initial value must be provided for where masks')
  1982. ndim_orig = F.rank(a)
  1983. a = where_(where, a, initial)
  1984. axes = _real_axes(ndim_orig, F.rank(a), axes)
  1985. return reduce_fn(a, axes).astype(dtype)
  1986. def nanmax(a, axis=None, dtype=None, keepdims=False):
  1987. """
  1988. Return the maximum of an array or maximum along an axis, ignoring any NaNs.
  1989. Note:
  1990. Numpy arguments `out` is not supported.
  1991. For all NaN slices, a very small negative number is returned instead of NaN.
  1992. Args:
  1993. a (Union[int, float, list, tuple, Tensor]): Array containing numbers whose maximum
  1994. is desired. If `a` is not an array, a conversion is attempted.
  1995. axis (Union[int, tuple of int, None], optional): Axis or axes along which the maximum is
  1996. computed. The default is to compute the maximum of the flattened array.
  1997. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  1998. output Tensor.
  1999. keepdims (boolean, optional): defaults to False. If this is set to True, the axes which
  2000. are reduced are left in the result as dimensions with size one. With this option,
  2001. the result will broadcast correctly against the original `a`.
  2002. Returns:
  2003. Tensor.
  2004. Raises:
  2005. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  2006. if the axes contain duplicates.
  2007. Supported Platforms:
  2008. ``GPU`` ``CPU``
  2009. Examples:
  2010. >>> import mindspore.numpy as np
  2011. >>> a = np.array([[1, 2], [3, np.nan]])
  2012. >>> output = np.nanmax(a)
  2013. >>> print(output)
  2014. 3.0
  2015. >>> output = np.nanmax(a, axis=0)
  2016. >>> print(output)
  2017. [3. 2.]
  2018. """
  2019. a = _to_tensor(a)
  2020. if not isinstance(keepdims, int):
  2021. _raise_type_error("integer argument expected, got", keepdims)
  2022. nan_mask = _isnan(a)
  2023. a = F.select(nan_mask, full(F.shape(a), -sys.maxsize - 1, F.dtype(a)), a)
  2024. reduce_fn = _reduce_max_keepdims if keepdims else _reduce_max_default
  2025. return _reduce(a, reduce_fn, axis=axis, keepdims=keepdims, dtype=dtype)
  2026. def nanmin(a, axis=None, dtype=None, keepdims=False):
  2027. """
  2028. Returns the minimum of array elements over a given axis, ignoring any NaNs.
  2029. Note:
  2030. Numpy arguments `out` is not supported.
  2031. For all-NaN slices, a very large number is returned instead of NaN.
  2032. Args:
  2033. a (Union[int, float, list, tuple, Tensor]): Array containing numbers whose minimum
  2034. is desired. If `a` is not an array, a conversion is attempted.
  2035. axis (Union[int, tuple of int, None], optional): Axis or axes along which the minimum is
  2036. computed. The default is to compute the minimum of the flattened array.
  2037. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2038. output Tensor.
  2039. keepdims (boolean, optional): defaults to False. If this is set to True, the axes which
  2040. are reduced are left in the result as dimensions with size one. With this option,
  2041. the result will broadcast correctly against the original `a`.
  2042. Returns:
  2043. Tensor.
  2044. Raises:
  2045. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  2046. if the axes contain duplicates.
  2047. Supported Platforms:
  2048. ``GPU`` ``CPU``
  2049. Examples:
  2050. >>> import mindspore.numpy as np
  2051. >>> a = np.array([[1, 2], [3, np.nan]])
  2052. >>> output = np.nanmin(a)
  2053. >>> print(output)
  2054. 1.0
  2055. >>> output = np.nanmin(a, axis=0)
  2056. >>> print(output)
  2057. [1. 2.]
  2058. """
  2059. a = _to_tensor(a)
  2060. if not isinstance(keepdims, int):
  2061. _raise_type_error("integer argument expected, got", keepdims)
  2062. nan_mask = _isnan(a)
  2063. a = F.select(nan_mask, full(F.shape(a), sys.maxsize, F.dtype(a)), a)
  2064. reduce_fn = _reduce_min_keepdims if keepdims else _reduce_min_default
  2065. return _reduce(a, reduce_fn, axis=axis, keepdims=keepdims, dtype=dtype)
  2066. def _reduce_nansum(x, axis, keepdims=False):
  2067. """Computes reduce sum treating NaNs as zeros."""
  2068. x = F.select(_isnan(x), zeros(F.shape(x), F.dtype(x)), x)
  2069. if keepdims:
  2070. return _reduce_sum_keepdims(x, axis)
  2071. return _reduce_sum_default(x, axis)
  2072. def nansum(a, axis=None, dtype=None, keepdims=False):
  2073. """
  2074. Returns the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
  2075. Note:
  2076. Numpy arguments `out` is not supported.
  2077. Args:
  2078. a (Union[int, float, list, tuple, Tensor]): Array containing numbers
  2079. whose sum is desired. If `a` is not an array, a conversion is attempted.
  2080. axis (Union[int, tuple of int, None], optional): Axis or axes along which the sum is
  2081. computed. The default is to compute the sum of the flattened array.
  2082. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2083. output Tensor.
  2084. keepdims (boolean, optional): defaults to False. If this is set to True, the axes which
  2085. are reduced are left in the result as dimensions with size one. With this option,
  2086. the result will broadcast correctly against the original `a`.
  2087. Returns:
  2088. Tensor.
  2089. Raises:
  2090. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  2091. if the axes contain duplicates.
  2092. Supported Platforms:
  2093. ``GPU`` ``CPU``
  2094. Examples:
  2095. >>> import mindspore.numpy as np
  2096. >>> a = np.array([[1, 1], [1, np.nan]])
  2097. >>> output = np.nansum(a)
  2098. >>> print(output)
  2099. 3.0
  2100. >>> output = np.nansum(a, axis=0)
  2101. >>> print(output)
  2102. [2. 1.]
  2103. """
  2104. a = _to_tensor(a)
  2105. nan_mask = _isnan(a)
  2106. a = F.select(nan_mask, zeros(F.shape(a), F.dtype(a)), a)
  2107. return _reduce(a, functools.partial(_reduce_nansum, keepdims=keepdims), axis=axis,
  2108. keepdims=keepdims, dtype=dtype)
  2109. def _count_nonnan(a, axis, keepdims=False):
  2110. """Counts the number of elements excluding NaNs."""
  2111. nonnan_mask = F.select(_isnan(a), zeros(F.shape(a), F.dtype(a)), ones(F.shape(a), F.dtype(a)))
  2112. if keepdims:
  2113. return _reduce_sum_keepdims(nonnan_mask, axis)
  2114. return _reduce_sum_default(nonnan_mask, axis)
  2115. def nanmean(a, axis=None, dtype=None, keepdims=False):
  2116. """
  2117. Computes the arithmetic mean along the specified axis, ignoring NaNs.
  2118. Returns the average of the array elements. The average is taken over the flattened
  2119. array by default, otherwise over the specified axis. float32 intermediate and
  2120. return values are used for integer inputs.
  2121. Note:
  2122. Numpy arguments `out` is not supported.
  2123. Args:
  2124. a (Union[int, float, list, tuple, Tensor]): Array containing numbers
  2125. whose mean is desired. If `a` is not an array, a conversion is attempted.
  2126. axis (Union[int, tuple of int, None], optional): Axis or axes along which the mean is
  2127. computed. The default is to compute the mean of the flattened array.
  2128. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2129. output Tensor.
  2130. keepdims (boolean, optional): defaults to False. If this is set to True, the axes which
  2131. are reduced are left in the result as dimensions with size one. With this option,
  2132. the result will broadcast correctly against the original `a`.
  2133. Returns:
  2134. Tensor.
  2135. Raises:
  2136. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  2137. if the axes contain duplicates.
  2138. Supported Platforms:
  2139. ``GPU`` ``CPU``
  2140. Examples:
  2141. >>> import mindspore.numpy as np
  2142. >>> a = np.array([[1, np.nan], [3, 4]])
  2143. >>> output = np.nanmean(a)
  2144. >>> print(output)
  2145. 2.6666667
  2146. >>> output = np.nanmean(a, axis=0)
  2147. >>> print(output)
  2148. [2. 4.]
  2149. >>> output = np.nanmean(a, axis=1)
  2150. >>> print(output)
  2151. [1. 3.5]
  2152. """
  2153. if dtype is None:
  2154. dtype = mstype.float32
  2155. a = _to_tensor(a)
  2156. axis = _check_axis_valid(axis, F.rank(a))
  2157. sum_a = nansum(a, axis=axis, dtype=dtype, keepdims=keepdims)
  2158. return F.tensor_div(sum_a, _count_nonnan(a, axis, keepdims))
  2159. def _nanvar(a, axis, ddof=0, keepdims=False):
  2160. """Computes nanvar without applying keyword arguments."""
  2161. mean_a = nanmean(a, axis=axis, keepdims=True)
  2162. pow_a = F.tensor_pow(F.tensor_sub(a, mean_a), 2)
  2163. sum_a = _reduce_nansum(pow_a, axis, keepdims)
  2164. count = _count_nonnan(a, axis, keepdims)
  2165. return divide(sum_a, F.tensor_sub(count, ddof))
  2166. def nanvar(a, axis=None, dtype=None, ddof=0, keepdims=False):
  2167. """
  2168. Computes the variance along the specified axis, while ignoring NaNs.
  2169. Returns the variance of the array elements, a measure of the spread of a distribution. The
  2170. variance is computed for the flattened array by default, otherwise over the specified axis.
  2171. Note:
  2172. Numpy arguments `out` is not supported.
  2173. On GPU, the supported dtypes are np.float16, and np.float32.
  2174. Args:
  2175. a (Union[int, float, list, tuple, Tensor]): Array containing numbers
  2176. whose variance is desired. If `a` is not an array, a conversion is attempted.
  2177. axis (Union[int, tuple of int, None], optional): Axis or axes along which the variance is
  2178. computed. The default is to compute the variance of the flattened array.
  2179. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2180. output Tensor.
  2181. ddof (int, optional): “Delta Degrees of Freedom”: the divisor used in the calculation is
  2182. ``N - ddof``, where `N` represents the number of non-NaN elements. By default `ddof`
  2183. is zero.
  2184. keepdims (boolean, optional): defaults to False. If this is set to True, the axes which
  2185. are reduced are left in the result as dimensions with size one. With this option,
  2186. the result will broadcast correctly against the original `a`.
  2187. Returns:
  2188. Tensor.
  2189. Raises:
  2190. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  2191. if the axes contain duplicates.
  2192. Supported Platforms:
  2193. ``GPU`` ``CPU``
  2194. Examples:
  2195. >>> import mindspore.numpy as np
  2196. >>> a = np.array([[1, np.nan], [3, 4]])
  2197. >>> output = np.nanvar(a)
  2198. >>> print(output)
  2199. 1.5555557
  2200. >>> output = np.nanvar(a, axis=0)
  2201. >>> print(output)
  2202. [1. 0.]
  2203. >>> output = np.nanvar(a, axis=1)
  2204. >>> print(output)
  2205. [0. 0.25]
  2206. """
  2207. if dtype is None:
  2208. dtype = mstype.float32
  2209. return _reduce(a, functools.partial(_nanvar, ddof=ddof, keepdims=keepdims), axis=axis,
  2210. keepdims=keepdims, dtype=dtype)
  2211. def nanstd(a, axis=None, dtype=None, ddof=0, keepdims=False):
  2212. """
  2213. Computes the standard deviation along the specified axis, while ignoring NaNs.
  2214. Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN
  2215. array elements. The standard deviation is computed for the flattened array by default,
  2216. otherwise over the specified axis.
  2217. Note:
  2218. Numpy arguments `out` is not supported.
  2219. On GPU, the supported dtypes are np.float16, and np.float32.
  2220. Args:
  2221. a (Union[int, float, list, tuple, Tensor]): Calculates the standard deviation of the non-NaN values.
  2222. axis (Union[int, tuple of int, None], optional): Axis or axes along which the standard
  2223. deviation is computed. The default is to compute the standard deviation of the
  2224. flattened array.
  2225. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2226. output Tensor.
  2227. ddof (int, optional): “Delta Degrees of Freedom”: the divisor used in the calculation is
  2228. ``N - ddof``, where `N` represents the number of non-NaN elements. By default `ddof`
  2229. is zero.
  2230. keepdims (boolean, optional): defaults to False. If this is set to True, the axes which
  2231. are reduced are left in the result as dimensions with size one. With this option,
  2232. the result will broadcast correctly against the original `a`.
  2233. Returns:
  2234. Tensor.
  2235. Raises:
  2236. ValueError: if axes are out of the range of ``[-a.ndim, a.ndim)``, or
  2237. if the axes contain duplicates.
  2238. Supported Platforms:
  2239. ``GPU`` ``CPU``
  2240. Examples:
  2241. >>> import mindspore.numpy as np
  2242. >>> a = np.array([[1, np.nan], [3, 4]])
  2243. >>> output = np.nanstd(a)
  2244. >>> print(output)
  2245. 1.2472192
  2246. >>> output = np.nanstd(a, axis=0)
  2247. >>> print(output)
  2248. [1. 0.]
  2249. >>> output = np.nanstd(a, axis=1)
  2250. >>> print(output)
  2251. [0. 0.5]
  2252. """
  2253. if dtype is None:
  2254. dtype = mstype.float32
  2255. return _reduce(a, lambda a, axis: F.sqrt(_nanvar(a, axis, ddof=ddof, keepdims=keepdims)),
  2256. axis=axis, keepdims=keepdims, dtype=dtype)
  2257. def exp2(x, dtype=None):
  2258. """
  2259. Calculates ``2**p`` for all p in the input array.
  2260. Note:
  2261. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2262. not supported.
  2263. On GPU, the supported dtypes are np.float16, and np.float32.
  2264. Args:
  2265. x (Tensor): input values.
  2266. dtype (:class:`mindspore.dtype`, optional): defaults to :class:`None`. Overrides the dtype of the
  2267. output Tensor.
  2268. Returns:
  2269. Tensor or scalar, element-wise 2 to the power `x`.
  2270. Supported Platforms:
  2271. ``Ascend`` ``GPU`` ``CPU``
  2272. Examples:
  2273. >>> import mindspore.numpy as np
  2274. >>> x = np.array([2, 3]).astype(np.float32)
  2275. >>> output = np.exp2(x)
  2276. >>> print(output)
  2277. [4. 8.]
  2278. """
  2279. return _apply_tensor_op(lambda x: F.tensor_pow(2, x), x, dtype=dtype)
  2280. def kron(a, b):
  2281. """
  2282. Kronecker product of two arrays.
  2283. Computes the Kronecker product, a composite array made of blocks of the second
  2284. array scaled by the first.
  2285. Note:
  2286. Booleans are not supported.
  2287. Args:
  2288. a (Union[int, float, list, tuple, Tensor]): input values.
  2289. b (Union[int, float, list, tuple, Tensor]): input values.
  2290. Returns:
  2291. Tensor.
  2292. Supported Platforms:
  2293. ``Ascend`` ``GPU`` ``CPU``
  2294. Examples:
  2295. >>> import mindspore.numpy as np
  2296. >>> output = np.kron([1,10,100], [5,6,7])
  2297. >>> print(output)
  2298. [ 5 6 7 50 60 70 500 600 700]
  2299. >>> output = np.kron([5,6,7], [1,10,100])
  2300. >>> print(output)
  2301. [ 5 50 500 6 60 600 7 70 700]
  2302. >>> output = np.kron(np.eye(2), np.ones((2,2)))
  2303. >>> print(output)
  2304. [[1. 1. 0. 0.]
  2305. [1. 1. 0. 0.]
  2306. [0. 0. 1. 1.]
  2307. [0. 0. 1. 1.]]
  2308. """
  2309. a, b = _to_tensor(a, b)
  2310. ndim = _max(F.rank(a), F.rank(b))
  2311. if ndim == 0:
  2312. return F.tensor_mul(a, b)
  2313. a = _expand(a, ndim)
  2314. b = _expand(b, ndim)
  2315. shape_a = F.shape(a)
  2316. shape_b = F.shape(b)
  2317. # scales a by the shape of b
  2318. kron_shape = _seq_prod(shape_a, shape_b)
  2319. a = F.reshape(a, _add_unit_axes(shape_a, 2*ndim, True))
  2320. a = F.tile(a, _add_unit_axes(shape_b, 2*ndim, False))
  2321. a = moveaxis(a, F.make_range(ndim, 2*ndim), F.make_range(1, 2*ndim, 2))
  2322. a = F.reshape(a, kron_shape)
  2323. # scales b by the shape of a
  2324. b = F.tile(b, shape_a)
  2325. return F.tensor_mul(a, b)
  2326. def cross(a, b, axisa=- 1, axisb=- 1, axisc=- 1, axis=None):
  2327. """
  2328. Returns the cross product of two (arrays of) vectors.
  2329. The cross product of `a` and `b` in :math:`R^3` is a vector perpendicular to both
  2330. `a` and `b`. If `a` and `b` are arrays of vectors, the vectors are defined by the
  2331. last axis of `a` and `b` by default, and these axes can have dimensions 2 or 3.
  2332. Where the dimension of either `a` or `b` is 2, the third component of the input
  2333. vector is assumed to be zero and the cross product calculated accordingly. In cases
  2334. where both input vectors have dimension 2, the z-component of the cross product is
  2335. returned.
  2336. Args:
  2337. a (Union[list, tuple, Tensor]): Components of the first vector(s).
  2338. b (Union[list, tuple, Tensor]): Components of the second vector(s).
  2339. axisa (int, optional): Axis of `a` that defines the vector(s). By default, the last
  2340. axis.
  2341. axisb (int, optional): Axis of `b` that defines the vector(s). By default, the last
  2342. axis.
  2343. axisc (int, optional): Axis of `c` containing the cross product vector(s). Ignored
  2344. if both input vectors have dimension 2, as the return is scalar. By default,
  2345. the last axis.
  2346. axis (int, optional): If defined, the axis of `a`, `b` and `c` that defines the
  2347. vector(s) and cross product(s). Overrides `axisa`, `axisb` and `axisc`.
  2348. Returns:
  2349. Tensor, vector cross product(s).
  2350. Raises:
  2351. ValueError: when the dimensions of the vector(s) in `a` and/or `b` does not equal 2
  2352. or 3.
  2353. Supported Platforms:
  2354. ``Ascend`` ``GPU`` ``CPU``
  2355. Examples:
  2356. >>> import mindspore.numpy as np
  2357. >>> x = np.array([[1,2,3], [4,5,6]])
  2358. >>> y = np.array([[4,5,6], [1,2,3]])
  2359. >>> output = np.cross(x, y)
  2360. >>> print(output)
  2361. [[-3 6 -3]
  2362. [ 3 -6 3]]
  2363. >>> output = np.cross(x, y, axisc=0)
  2364. [[-3 3]
  2365. [ 6 -6]
  2366. [-3 3]]
  2367. """
  2368. a, b = _to_tensor(a, b)
  2369. if axis is not None:
  2370. axisa, axisb, axisc = axis, axis, axis
  2371. _check_axis_in_range(axisa, F.rank(a))
  2372. _check_axis_in_range(axisb, F.rank(b))
  2373. a = moveaxis(a, axisa, -1)
  2374. b = moveaxis(b, axisb, -1)
  2375. shape_a = F.shape(a)
  2376. shape_b = F.shape(b)
  2377. if F.shape(a)[-1] not in (2, 3) or F.shape(b)[-1] not in (2, 3):
  2378. _raise_value_error('incompatible dimensions for cross product (dimension must be 2 or 3)')
  2379. a_has_z = shape_a[-1] == 3
  2380. b_has_z = shape_b[-1] == 3
  2381. shape_out = _infer_out_shape(shape_a[:-1], shape_b[:-1])
  2382. if a_has_z or b_has_z:
  2383. shape_out += (3,)
  2384. _check_axis_in_range(axisc, len(shape_out))
  2385. dtype = _promote(F.dtype(a), F.dtype(b))
  2386. if _get_device() == 'CPU':
  2387. # F.tensor_slice only supports float on CPU
  2388. if not _check_is_float(F.dtype(a)):
  2389. a = F.cast(a, mstype.float32)
  2390. if not _check_is_float(F.dtype(b)):
  2391. b = F.cast(b, mstype.float32)
  2392. a_slice_start = _list_comprehensions(F.rank(a) - 1, 0, True)
  2393. a_slice_size = shape_a[:-1] + (1,)
  2394. b_slice_start = _list_comprehensions(F.rank(b) - 1, 0, True)
  2395. b_slice_size = shape_b[:-1] + (1,)
  2396. def _get_slice_product(idx_a, idx_b):
  2397. return multiply(F.tensor_slice(a, a_slice_start + (idx_a,), a_slice_size),
  2398. F.tensor_slice(b, b_slice_start + (idx_b,), b_slice_size))
  2399. cz = F.tensor_sub(_get_slice_product(0, 1), _get_slice_product(1, 0)) # ax*by - ay*bx
  2400. if not a_has_z and not b_has_z:
  2401. return F.reshape(cz, shape_out).astype(dtype)
  2402. if a_has_z and b_has_z:
  2403. cx = F.tensor_sub(_get_slice_product(1, 2), _get_slice_product(2, 1)) # ay*bz - az*by
  2404. cy = F.tensor_sub(_get_slice_product(2, 0), _get_slice_product(0, 2)) # az*bx - ax*bz
  2405. elif a_has_z:
  2406. cx = F.neg_tensor(_get_slice_product(2, 1)) # -az*by
  2407. cy = _get_slice_product(2, 0) # az*bx
  2408. else: # b_has_z
  2409. cx = _get_slice_product(1, 2) # ay*bz
  2410. cy = F.neg_tensor(_get_slice_product(0, 2)) # -ax*bz
  2411. res = _concat((cx, cy, cz)).reshape(shape_out)
  2412. return moveaxis(res, -1, axisc).astype(dtype)
  2413. def ceil(x, dtype=None):
  2414. """
  2415. Returns the ceiling of the input, element-wise.
  2416. The ceil of the scalar `x` is the smallest integer `i`, such that ``i >= x``.
  2417. Note:
  2418. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2419. not supported.
  2420. On GPU, the supported dtypes are np.float16, and np.float32.
  2421. Args:
  2422. x (Tensor): input values.
  2423. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2424. output Tensor.
  2425. Returns:
  2426. Tensor or scalar, the floor of each element in `x`. This is a scalar if `x` is a scalar.
  2427. Supported Platforms:
  2428. ``Ascend`` ``GPU`` ``CPU``
  2429. Examples:
  2430. >>> import mindspore.numpy as np
  2431. >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
  2432. >>> output = np.ceil(a)
  2433. >>> print(output)
  2434. [-1. -1. -0. 1. 2. 2. 2.]
  2435. """
  2436. return _apply_tensor_op(lambda x: F.neg_tensor(F.floor(F.neg_tensor(x.astype(mstype.float32)))),
  2437. x, dtype=dtype)
  2438. def _infer_shape_rem(shape1, shape2, ndim1, ndim2, transpose_b):
  2439. """Infers the shape of the last two dimensions after performing matmul."""
  2440. shape_rem = ()
  2441. if ndim1 >= 2:
  2442. shape_rem += (shape1[-2],)
  2443. if transpose_b:
  2444. if ndim2 >= 2:
  2445. shape_rem += (shape2[-2],)
  2446. else:
  2447. if ndim1 >= 1:
  2448. shape_rem += (shape2[-1],)
  2449. return shape_rem
  2450. def positive(a, dtype=None):
  2451. """
  2452. Numerical positive, element-wise.
  2453. Note:
  2454. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2455. not supported.
  2456. Args:
  2457. a (Tensor): Input tensor.
  2458. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2459. output Tensor.
  2460. Returns:
  2461. Tensor.
  2462. Supported Platforms:
  2463. ``Ascend`` ``GPU`` ``CPU``
  2464. Examples:
  2465. >>> import mindspore.numpy as np
  2466. >>> a = np.asarray([1, -1]).astype('float32')
  2467. >>> output = np.positive(a)
  2468. >>> print(output)
  2469. [1. -1.]
  2470. """
  2471. _check_input_tensor(a)
  2472. neg_tensor = F.neg_tensor(a)
  2473. return _apply_tensor_op(F.neg_tensor, neg_tensor, dtype=dtype)
  2474. def negative(a, dtype=None):
  2475. """
  2476. Numerical negative, element-wise.
  2477. Note:
  2478. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2479. not supported.
  2480. Args:
  2481. a (Tensor): Input tensor.
  2482. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2483. output Tensor.
  2484. Returns:
  2485. Tensor.
  2486. Supported Platforms:
  2487. ``Ascend`` ``GPU`` ``CPU``
  2488. Examples:
  2489. >>> import mindspore.numpy as np
  2490. >>> a = np.asarray([1, -1]).astype('float32')
  2491. >>> output = np.negative(a)
  2492. >>> print(output)
  2493. [-1. 1.]
  2494. """
  2495. return _apply_tensor_op(F.neg_tensor, a, dtype=dtype)
  2496. def cumsum(a, axis=None, dtype=None):
  2497. """
  2498. Returns the cumulative sum of the elements along a given axis.
  2499. Note:
  2500. If ``a.dtype`` is :class:`int8`, :class:`int16` or :class:`bool`, the result
  2501. `dtype` will be elevated to :class:`int32`.
  2502. Args:
  2503. a (Tensor): Input tensor.
  2504. axis (int, optional): Axis along which the cumulative sum is computed. The
  2505. default (None) is to compute the cumsum over the flattened array.
  2506. dtype (:class:`mindspore.dtype`, optional): If not specified, stay the same as `a`,
  2507. unless `a` has an integer dtype with a precision less than that of the
  2508. default platform integer. In that case, the default platform integer
  2509. is used.
  2510. Returns:
  2511. Tensor.
  2512. Raises:
  2513. TypeError: If input arguments have types not specified above.
  2514. ValueError: If axis is out of range.
  2515. Supported Platforms:
  2516. ``Ascend`` ``GPU`` ``CPU``
  2517. Examples:
  2518. >>> import mindspore.numpy as np
  2519. >>> output = np.cumsum(np.ones((3,3)), axis=0)
  2520. >>> print(output)
  2521. [[1. 1. 1.]
  2522. [2. 2. 2.]
  2523. [3. 3. 3.]]
  2524. """
  2525. _check_input_tensor(a)
  2526. return a.cumsum(axis, dtype)
  2527. def nancumsum(a, axis=None, dtype=None):
  2528. """
  2529. Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs)
  2530. as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are
  2531. replaced by zeros.
  2532. Zeros are returned for slices that are all-NaN or empty.
  2533. Note:
  2534. If ``a.dtype`` is :class:`int8`, :class:`int16` or :class:`bool`, the result
  2535. `dtype` will be elevated to :class:`int32`.
  2536. Args:
  2537. a (Tensor): Input tensor.
  2538. axis (int, optional): Axis along which the cumulative sum is computed. The
  2539. default (None) is to compute the cumsum over the flattened array.
  2540. dtype (:class:`mindspore.dtype`, optional): If not specified, stay the same as `a`,
  2541. unless `a` has an integer dtype with a precision less than that of the
  2542. default platform integer. In that case, the default platform integer
  2543. is used.
  2544. Returns:
  2545. Tensor.
  2546. Raises:
  2547. TypeError: If input arguments have types not specified above.
  2548. ValueError: If axis is out of range.
  2549. Supported Platforms:
  2550. ``GPU`` ``CPU``
  2551. Examples:
  2552. >>> import mindspore.numpy as np
  2553. >>> a = np.array([[1, 2], [3, np.nan]])
  2554. >>> output = np.nancumsum(a)
  2555. >>> print(output)
  2556. [1. 3. 6. 6.]
  2557. >>> output = np.nancumsum(a, axis=0)
  2558. >>> print(output)
  2559. [[1. 2.]
  2560. [4. 2.]]
  2561. >>> output = np.nancumsum(a, axis=1)
  2562. >>> print(output)
  2563. [[1. 3.]
  2564. [3. 3.]]
  2565. """
  2566. a = F.select(_isnan(a), zeros(F.shape(a), F.dtype(a)), a)
  2567. return a.cumsum(axis, dtype)
  2568. def cbrt(x, dtype=None):
  2569. """
  2570. Returns the cube-root of a tensor, element-wise.
  2571. Note:
  2572. Numpy arguments `casting`, `order`, `subok`, `signature`, and `extobj` are
  2573. not supported.
  2574. Args:
  2575. x (Tensor): Input tensor.
  2576. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  2577. output Tensor.
  2578. Returns:
  2579. Tensor.
  2580. Supported Platforms:
  2581. ``Ascend`` ``GPU`` ``CPU``
  2582. Examples:
  2583. >>> import mindspore.numpy as np
  2584. >>> a = np.asarray([1, -1, 3, -8, 64])
  2585. >>> output = np.cbrt(a)
  2586. >>> print(output)
  2587. [ 1. -1. 1.4422495 -2. 4. ]
  2588. """
  2589. def _cbrt(x):
  2590. compute_type = promote_types(x.dtype, "float32")
  2591. x = x.astype(compute_type)
  2592. # TODO: use P.Sign() once gpu support is added
  2593. abs_x = F.absolute(x)
  2594. sign_x = abs_x / x
  2595. return sign_x * F.tensor_pow(abs_x, 1. / 3.)
  2596. return _apply_tensor_op(_cbrt, x, dtype=dtype)
  2597. def log1p(x, dtype=None):
  2598. """
  2599. Returns the natural logarithm of one plus the input array, element-wise.
  2600. Calculates ``log(1 + x)``.
  2601. Note:
  2602. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2603. not supported.
  2604. Args:
  2605. x (Tensor): Input array.
  2606. dtype (:class:`mindspore.dtype`): Default: :class:`None`. Overrides the dtype of the
  2607. output Tensor.
  2608. Returns:
  2609. Tensor or scalar. This is a scalar if `x` is a scalar.
  2610. Supported Platforms:
  2611. ``Ascend`` ``GPU`` ``CPU``
  2612. Examples:
  2613. >>> import mindspore.numpy as np
  2614. >>> x = np.array([1, 2, 3]).astype('float16')
  2615. >>> output = np.log1p(x)
  2616. >>> print(output)
  2617. [0.6934 1.099 1.387 ]
  2618. """
  2619. return _apply_tensor_op(lambda x: F.log(x + 1), x, dtype=dtype)
  2620. def logaddexp(x1, x2, dtype=None):
  2621. """
  2622. Logarithm of the sum of exponentiations of the inputs.
  2623. Calculates ``log(exp(x1) + exp(x2))``. This function is useful in statistics where the
  2624. calculated probabilities of events may be so small as to exceed the range of normal
  2625. floating point numbers. In such cases the logarithm of the calculated probability is
  2626. stored. This function allows adding probabilities stored in such a fashion.
  2627. Note:
  2628. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2629. not supported.
  2630. Args:
  2631. x1 (Tensor): Input array.
  2632. x2 (Tensor): Input array. If ``x1.shape != x2.shape``, they must be broadcastable to
  2633. a common shape (which becomes the shape of the output).
  2634. dtype (:class:`mindspore.dtype`): Default: :class:`None`. Overrides the dtype of the
  2635. output Tensor.
  2636. Returns:
  2637. Tensor or scalar. This is a scalar if both `x1` and `x2` are scalars.
  2638. Supported Platforms:
  2639. ``Ascend`` ``GPU`` ``CPU``
  2640. Examples:
  2641. >>> import mindspore.numpy as np
  2642. >>> x1 = np.array([1, 2, 3]).astype('float16')
  2643. >>> x2 = np.array(2).astype('float16')
  2644. >>> output = np.logaddexp(x1, x2)
  2645. >>> print(output)
  2646. [2.312 2.693 3.312]
  2647. """
  2648. def _logaddexp(x1, x2):
  2649. return F.log(F.tensor_add(F.tensor_exp(x1), F.tensor_exp(x2)))
  2650. return _apply_tensor_op(_logaddexp, x1, x2, dtype=dtype)
  2651. def log2(x, dtype=None):
  2652. """
  2653. Base-2 logarithm of `x`.
  2654. Note:
  2655. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2656. not supported.
  2657. Args:
  2658. x (Tensor): Input tensor.
  2659. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2660. output Tensor.
  2661. Returns:
  2662. Tensor or scalar. This is a scalar if `x` is a scalar.
  2663. Supported Platforms:
  2664. ``Ascend`` ``GPU`` ``CPU``
  2665. Examples:
  2666. >>> import mindspore.numpy as np
  2667. >>> x = np.array([2, 4, 8]).astype('float16')
  2668. >>> output = np.log2(x)
  2669. >>> print(output)
  2670. [1. 2. 3.]
  2671. """
  2672. tensor_2 = _make_tensor(2, x.dtype)
  2673. def _log2(x):
  2674. return F.log(x) / F.log(tensor_2)
  2675. return _apply_tensor_op(_log2, x, dtype=dtype)
  2676. def logaddexp2(x1, x2, dtype=None):
  2677. """
  2678. Logarithm of the sum of exponentiations of the inputs in base of 2.
  2679. Calculates ``log2(2**x1 + 2**x2)``.
  2680. This function is useful in machine learning when the calculated probabilities of events
  2681. may be so small as to exceed the range of normal floating point numbers.
  2682. In such cases the base-2 logarithm of the calculated probability can be used instead.
  2683. This function allows adding probabilities stored in such a fashion.
  2684. Note:
  2685. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2686. not supported.
  2687. Args:
  2688. x1 (Tensor): Input tensor.
  2689. x2 (Tensor): Input tensor. If ``x1.shape != x2.shape``, they must be broadcastable to
  2690. a common shape (which becomes the shape of the output).
  2691. dtype (:class:`mindspore.dtype`): Default: :class:`None`. Overrides the dtype of the
  2692. output Tensor.
  2693. Returns:
  2694. Tensor or scalar. This is a scalar if both `x1` and `x2` are scalars.
  2695. Supported Platforms:
  2696. ``Ascend`` ``GPU`` ``CPU``
  2697. Examples:
  2698. >>> import mindspore.numpy as np
  2699. >>> x1 = np.array([2, 4, 8]).astype('float16')
  2700. >>> x2 = np.array(2).astype('float16')
  2701. >>> output = np.logaddexp2(x1, x2)
  2702. >>> print(output)
  2703. [3. 4.32 8.02]
  2704. """
  2705. _check_input_tensor(x1, x2)
  2706. add_exp = F.tensor_add(F.tensor_pow(2, x1), F.tensor_pow(2, x2))
  2707. return log2(add_exp, dtype=dtype)
  2708. def log10(x, dtype=None):
  2709. """
  2710. Base-10 logarithm of `x`.
  2711. Note:
  2712. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2713. not supported.
  2714. Args:
  2715. x (Tensor): Input tensor.
  2716. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2717. output Tensor.
  2718. Returns:
  2719. Tensor or scalar. This is a scalar if `x` is a scalar.
  2720. Supported Platforms:
  2721. ``Ascend`` ``GPU`` ``CPU``
  2722. Examples:
  2723. >>> import mindspore.numpy as np
  2724. >>> x = np.array([10, 100, 1000]).astype('float16')
  2725. >>> output = np.log10(x)
  2726. >>> print(output)
  2727. [1. 2. 3.]
  2728. """
  2729. tensor_10 = _make_tensor(10, x.dtype)
  2730. def _log10(x):
  2731. return F.log(x) / F.log(tensor_10)
  2732. return _apply_tensor_op(_log10, x, dtype=dtype)
  2733. def _cast_type_for_trigonometric(x):
  2734. _check_input_tensor(x)
  2735. if x.dtype != mstype.float16 or x.dtype != mstype.float32 or x.dtype != mstype.float64:
  2736. dtype = _promote_for_trigonometric(x.dtype)
  2737. x = F.cast(x, dtype)
  2738. return x
  2739. def sin(x, dtype=None):
  2740. """
  2741. Trigonometric sine, element-wise.
  2742. Note:
  2743. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2744. not supported.
  2745. Args:
  2746. x (Tensor): Input tensor.
  2747. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2748. output Tensor.
  2749. Returns:
  2750. Tensor or scalar. This is a scalar if `x` is a scalar.
  2751. Supported Platforms:
  2752. ``Ascend`` ``GPU`` ``CPU``
  2753. Examples:
  2754. >>> import mindspore.numpy as np
  2755. >>> x = np.array([-5, -1, 0, 2, 4, 100]).astype('float32')
  2756. >>> output = np.sin(x)
  2757. >>> print(output)
  2758. [ 0.9589243 -0.84147096 0. 0.9092974 -0.7568025 -0.50636566]
  2759. """
  2760. x = _cast_type_for_trigonometric(x)
  2761. return _apply_tensor_op(F.sin, x, dtype=dtype)
  2762. def cos(x, dtype=None):
  2763. """
  2764. Cosine element-wise.
  2765. Note:
  2766. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2767. not supported.
  2768. Args:
  2769. x (Tensor): Input tensor.
  2770. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2771. output Tensor.
  2772. Returns:
  2773. Tensor or scalar. This is a scalar if `x` is a scalar.
  2774. Supported Platforms:
  2775. ``Ascend`` ``GPU`` ``CPU``
  2776. Examples:
  2777. >>> import mindspore.numpy as np
  2778. >>> x = np.arange(5).astype('float32')
  2779. >>> print(np.cos(x))
  2780. [ 1. 0.5403023 -0.41614684 -0.9899925 -0.6536436 ]
  2781. """
  2782. x = _cast_type_for_trigonometric(x)
  2783. return _apply_tensor_op(F.cos, x, dtype=dtype)
  2784. def tan(x, dtype=None):
  2785. """
  2786. Computes tangent element-wise.
  2787. Equivalent to :math:`np.sin(x)/np.cos(x)` element-wise.
  2788. Note:
  2789. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2790. not supported.
  2791. Args:
  2792. x (Tensor): Input tensor.
  2793. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2794. output Tensor.
  2795. Returns:
  2796. Tensor or scalar. This is a scalar if `x` is a scalar.
  2797. Raises:
  2798. TypeError: If the input is not a tensor or is :class:`tensor.dtype` is :class:`mindsproe.float64`.
  2799. Supported Platforms:
  2800. ``Ascend`` ``CPU``
  2801. Examples:
  2802. >>> import mindspore.numpy as np
  2803. >>> x = np.array([-5, -1, 0, 2, 4, 100]).astype('float32')
  2804. >>> print(np.tan(x))
  2805. [ 3.380515 -1.5574077 0. -2.1850398 1.1578213 -0.58721393]
  2806. """
  2807. x = _cast_type_for_trigonometric(x)
  2808. return _apply_tensor_op(F.tan, x, dtype=dtype)
  2809. def arcsin(x, dtype=None):
  2810. """
  2811. Inverse sine, element-wise.
  2812. Note:
  2813. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2814. not supported.
  2815. Args:
  2816. x (Tensor): Input tensor. y-coordinate on the unit circle.
  2817. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2818. output Tensor.
  2819. Returns:
  2820. Tensor.
  2821. Raises:
  2822. TypeError: If the input is not a tensor.
  2823. Supported Platforms:
  2824. ``Ascend`` ``GPU`` ``CPU``
  2825. Examples:
  2826. >>> import mindspore.numpy as np
  2827. >>> x = np.asarray([1, -1], np.float32)
  2828. >>> output = np.arcsin(x)
  2829. >>> print(output)
  2830. [ 1.5707964 -1.5707964]
  2831. """
  2832. x = _cast_type_for_trigonometric(x)
  2833. return _apply_tensor_op(F.asin, x, dtype=dtype)
  2834. def arccos(x, dtype=None):
  2835. """
  2836. Trigonometric inverse cosine, element-wise.
  2837. Note:
  2838. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2839. not supported.
  2840. Args:
  2841. x (Tensor): Input tensor. x-coordinate on the unit circle.
  2842. For real arguments, the domain is :math:`[-1, 1]`.
  2843. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2844. output Tensor.
  2845. Returns:
  2846. Tensor.
  2847. Raises:
  2848. TypeError: If the input is not a tensor.
  2849. Supported Platforms:
  2850. ``Ascend`` ``GPU`` ``CPU``
  2851. Examples:
  2852. >>> import mindspore.numpy as np
  2853. >>> x = np.asarray([1, -1], np.float32)
  2854. >>> output = np.arccos(x)
  2855. >>> print(output)
  2856. [0. 3.1415927]
  2857. """
  2858. x = _cast_type_for_trigonometric(x)
  2859. return _apply_tensor_op(F.acos, x, dtype=dtype)
  2860. def arctan(x, dtype=None):
  2861. """
  2862. Trigonometric inverse tangent, element-wise.
  2863. The inverse of tan, so that if :math:`y = tan(x)` then :math:`x = arctan(y)`.
  2864. Note:
  2865. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2866. not supported.
  2867. Args:
  2868. x (Tensor): Input tensor.
  2869. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2870. output Tensor.
  2871. Returns:
  2872. Tensor or scalar. This is a scalar if `x` is a scalar.
  2873. Supported Platforms:
  2874. ``Ascend`` ``GPU`` ``CPU``
  2875. Examples:
  2876. >>> import mindspore.numpy as np
  2877. >>> x = np.arange(5).astype('float32')
  2878. >>> print(np.tan(x))
  2879. [ 0. 1.5574077 -2.1850398 -0.14254655 1.1578213 ]
  2880. """
  2881. x = _cast_type_for_trigonometric(x)
  2882. return _apply_tensor_op(F.atan, x, dtype=dtype)
  2883. def sinh(x, dtype=None):
  2884. """
  2885. Hyperbolic sine, element-wise.
  2886. Note:
  2887. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2888. not supported.
  2889. Args:
  2890. x (Tensor): Input tensor.
  2891. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2892. output Tensor.
  2893. Returns:
  2894. Tensor or scalar. This is a scalar if `x` is a scalar.
  2895. Supported Platforms:
  2896. ``Ascend`` ``CPU``
  2897. Examples:
  2898. >>> import mindspore.numpy as np
  2899. >>> x = np.arange(5).astype('float32')
  2900. >>> print(np.sinh(x))
  2901. [ 0. 1.1752012 3.6268604 10.017875 27.289917 ]
  2902. """
  2903. x = _cast_type_for_trigonometric(x)
  2904. return _apply_tensor_op(F.sinh, x, dtype=dtype)
  2905. def cosh(x, dtype=None):
  2906. """
  2907. Hyperbolic cosine, element-wise.
  2908. Note:
  2909. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2910. not supported.
  2911. Args:
  2912. x (Tensor): Input tensor.
  2913. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2914. output Tensor.
  2915. Returns:
  2916. Tensor or scalar. This is a scalar if `x` is a scalar.
  2917. Supported Platforms:
  2918. ``Ascend`` ``CPU``
  2919. Examples:
  2920. >>> import mindspore.numpy as np
  2921. >>> x = np.arange(5).astype('float32')
  2922. >>> print(np.cosh(x))
  2923. [ 1. 1.5430807 3.7621956 10.067662 27.308233 ]
  2924. """
  2925. x = _cast_type_for_trigonometric(x)
  2926. return _apply_tensor_op(F.cosh, x, dtype=dtype)
  2927. def tanh(x, dtype=None):
  2928. """
  2929. Computes hyperbolic tangent element-wise.
  2930. Note:
  2931. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2932. not supported.
  2933. Args:
  2934. x (Tensor): Input tensor.
  2935. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2936. output Tensor.
  2937. Returns:
  2938. Tensor or scalar. This is a scalar if `x` is a scalar.
  2939. Supported Platforms:
  2940. ``Ascend`` ``GPU`` ``CPU``
  2941. Examples:
  2942. >>> import mindspore.numpy as np
  2943. >>> x = np.arange(5).astype('float32')
  2944. >>> print(np.tanh(x))
  2945. [0. 0.7615942 0.9640276 0.9950548 0.9993293]
  2946. """
  2947. x = _cast_type_for_trigonometric(x)
  2948. return _apply_tensor_op(F.tanh, x, dtype=dtype)
  2949. def arcsinh(x, dtype=None):
  2950. """
  2951. Inverse hyperbolic sine element-wise.
  2952. Note:
  2953. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2954. not supported.
  2955. Args:
  2956. x (Tensor): Input tensor.
  2957. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2958. output Tensor.
  2959. Returns:
  2960. Tensor or scalar. This is a scalar if `x` is a scalar.
  2961. Supported Platforms:
  2962. ``Ascend`` ``GPU`` ``CPU``
  2963. Examples:
  2964. >>> import mindspore.numpy as np
  2965. >>> x = np.arange(5).astype('float32')
  2966. >>> print(np.arcsinh(x))
  2967. [0. 0.8813736 1.4436355 1.8184465 2.0947125]
  2968. """
  2969. x = _cast_type_for_trigonometric(x)
  2970. return _apply_tensor_op(F.asinh, x, dtype=dtype)
  2971. def arccosh(x, dtype=None):
  2972. """
  2973. Inverse hyperbolic cosine, element-wise.
  2974. Note:
  2975. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2976. not supported.
  2977. Args:
  2978. x (Tensor): Input tensor.
  2979. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  2980. output Tensor.
  2981. Returns:
  2982. Tensor or scalar. This is a scalar if `x` is a scalar.
  2983. Supported Platforms:
  2984. ``Ascend`` ``GPU`` ``CPU``
  2985. Examples:
  2986. >>> import mindspore.numpy as np
  2987. >>> x = np.arange(1, 5).astype('float32')
  2988. >>> print(np.arccosh(x))
  2989. [0. 1.316958 1.7627472 2.063437 ]
  2990. """
  2991. x = _cast_type_for_trigonometric(x)
  2992. return _apply_tensor_op(F.acosh, x, dtype=dtype)
  2993. def arctanh(x, dtype=None):
  2994. """
  2995. Inverse hyperbolic tangent element-wise.
  2996. Note:
  2997. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  2998. not supported.
  2999. Args:
  3000. x (Tensor): Input tensor.
  3001. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  3002. output Tensor.
  3003. Returns:
  3004. Tensor or scalar. This is a scalar if `x` is a scalar.
  3005. Supported Platforms:
  3006. ``Ascend`` ``CPU``
  3007. Examples:
  3008. >>> import mindspore.numpy as np
  3009. >>> x = np.array([-0.99, -0.75, -0.5, 0, 0.5]).astype('float32')
  3010. >>> print(np.arctanh(x))
  3011. [-2.646653 -0.97295505 -0.54930615 0. 0.54930615]
  3012. """
  3013. x = _cast_type_for_trigonometric(x)
  3014. return _apply_tensor_op(F.atanh, x, dtype=dtype)
  3015. def arctan2(x1, x2, dtype=None):
  3016. """
  3017. Element-wise arc tangent of :math:`x1/x2` choosing the quadrant correctly.
  3018. Note:
  3019. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  3020. not supported.
  3021. Args:
  3022. x1 (Tensor): input tensor.
  3023. x2 (Tensor): input tensor.
  3024. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  3025. output Tensor.
  3026. Returns:
  3027. Tensor or scalar, the sum of `x1` and `x2`, element-wise. This is a scalar
  3028. if both `x1` and `x2` are scalars.
  3029. Supported Platforms:
  3030. ``Ascend`` ``CPU``
  3031. Examples:
  3032. >>> import mindspore.numpy as np
  3033. >>> x1 = np.array([-1, +1, +1, -1])
  3034. >>> x2 = np.array([-1, -1, +1, +1])
  3035. >>> output = np.arctan2(x1, x2)
  3036. >>> print(output)
  3037. [-2.3561945 2.3561945 0.78539819 -0.78539819]
  3038. """
  3039. x1 = _cast_type_for_trigonometric(x1)
  3040. x2 = _cast_type_for_trigonometric(x2)
  3041. return _apply_tensor_op(F.atan2, x1, x2, dtype=dtype)
  3042. def promote_types(type1, type2):
  3043. """
  3044. Returns the data type with the smallest size and smallest scalar kind.
  3045. Note:
  3046. The promotion rule is slightly different from original Numpy, but more like
  3047. jax, due to the preference on ``32-bit`` over ``64-bit`` data types.
  3048. Args:
  3049. type1 (Union[:class:`mindspore.dtype`, str]): First data type.
  3050. type2 (Union[:class:`mindspore.dtype`, str]): Second data type.
  3051. Returns:
  3052. The promoted data type.
  3053. Raises:
  3054. TypeError: if the input are not valid :class:`mindspore.dtype` input.
  3055. Supported Platforms:
  3056. ``Ascend`` ``GPU`` ``CPU``
  3057. Examples:
  3058. >>> import mindspore.numpy as np
  3059. >>> output = np.promote_types(np.float32, np.float64)
  3060. >>> print(output)
  3061. Float64
  3062. """
  3063. type1 = _check_dtype(type1)
  3064. type2 = _check_dtype(type2)
  3065. return _promote(type1, type2)
  3066. def corrcoef(x, y=None, rowvar=True, dtype=None):
  3067. r"""
  3068. Returns Pearson product-moment correlation coefficients.
  3069. Please refer to the documentation for cov for more detail. The relationship
  3070. between the correlation coefficient matrix, R, and the covariance matrix, C, is
  3071. :math:`R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} * C_{jj} } }`
  3072. The values of R are between -1 and 1, inclusive.
  3073. Note:
  3074. Currently, complex numbers are not supported.
  3075. Args:
  3076. x (Union[int, float, bool, tuple, list, Tensor]): A 1-D or 2-D array containing
  3077. multiple variables and observations. Each row of `x` represents a variable,
  3078. and each column a single observation of all those variables. Also see rowvar below.
  3079. y (Union[int, float, bool, tuple, list, Tensor], optional): An additional set
  3080. of variables and observations.
  3081. rowvar (bool, optional): If rowvar is `True` (default), then each row represents
  3082. a variable, with observations in the columns. Otherwise, the relationship
  3083. is transposed: each column represents a variable, while the rows contain observations.
  3084. dtype (:class:`mindspore.dtype`, optional): Data-type of the result. By default,
  3085. the return data-type will have at least float32 precision.
  3086. Returns:
  3087. Tensor, The correlation coefficient matrix of the variables.
  3088. Raises:
  3089. TypeError: if the inputs have types not specified above.
  3090. ValueError: if `x` and `y` have wrong dimensions.
  3091. Supported Platforms:
  3092. ``Ascend`` ``GPU`` ``CPU``
  3093. Examples:
  3094. >>> import mindspore.numpy as np
  3095. >>> output = np.corrcoef([[2., 3., 4., 5.], [0., 2., 3., 4.], [7., 8., 9., 10.]])
  3096. >>> print(output)
  3097. [[1. 0.9827076 1. ]
  3098. [0.9827077 0.99999994 0.9827077 ]
  3099. [1. 0.9827076 1. ]]
  3100. """
  3101. # This implementation was adapted from original Numpy.
  3102. c = cov(x, y, rowvar)
  3103. if not c.shape:
  3104. return F.tensor_div(c, c)
  3105. d = diag(c)
  3106. stddev = sqrt(d)
  3107. c /= F.expand_dims(stddev, -1)
  3108. c /= F.expand_dims(stddev, 0)
  3109. c = clip(c, -1, 1)
  3110. if dtype is not None:
  3111. return c.astype(dtype)
  3112. return c
  3113. def _slice_along_axis(f, axis, slice_start, slice_end):
  3114. """
  3115. Slice a tensor along a given axis, a helper function for gradient
  3116. Args:
  3117. f (Tensor): Input Tensor.
  3118. axis (int): Specified axis.
  3119. slice_start (int): The start of the slice.
  3120. slice_end (int): The end of the int.
  3121. Returns:
  3122. Sliced tensor.
  3123. """
  3124. slice_size = slice_end - slice_start
  3125. index_start = (0,) * f.ndim
  3126. index_end = f.shape
  3127. index_start = _tuple_setitem(index_start, axis, slice_start)
  3128. index_end = _tuple_setitem(index_end, axis, slice_size)
  3129. return F.tensor_slice(f, index_start, index_end)
  3130. def _gradient_along_axis(f, h, axis):
  3131. """compute the gradients of `f` along a given axis, a helper function of gradient."""
  3132. end = f.shape[axis]
  3133. upper_edge = _slice_along_axis(f, axis, 1, 2) - _slice_along_axis(f, axis, 0, 1)
  3134. lower_edge = _slice_along_axis(f, axis, end-1, end) - _slice_along_axis(f, axis, end-2, end-1)
  3135. if end <= 2:
  3136. a_grad = concatenate((upper_edge, lower_edge), axis)
  3137. else:
  3138. middle = (_slice_along_axis(f, axis, 2, end) - _slice_along_axis(f, axis, 0, end-2)) * 0.5
  3139. a_grad = concatenate((upper_edge, middle, lower_edge), axis)
  3140. return a_grad / h
  3141. def gradient(f, *varargs, axis=None, edge_order=1):
  3142. """
  3143. Returns the gradient of a N-dimensional array.
  3144. The gradient is computed using second order accurate central differences
  3145. in the interior points and either first or second order accurate one-sides
  3146. (forward or backwards) differences at the boundaries.
  3147. The returned gradient hence has the same shape as the input array.
  3148. Note:
  3149. Currently we only support `edge_order`=1 and uniform spacing of `varargs`.
  3150. Args:
  3151. f (Union[tuple, list, Tensor]): An N-dimensional array containing samples of
  3152. a scalar function.
  3153. varargs (Union[tuple[number], tuple[tensor scalar]], optional)
  3154. Spacing between f values. Default unitary spacing for all dimensions.
  3155. Spacing can be specified using:
  3156. 1. single scalar to specify a sample distance for all dimensions.
  3157. 2. N scalars to specify a constant sample distance for each dimension.
  3158. edge_order (int): Gradient is calculated using N-th order accurate differences
  3159. at the boundaries. Default: 1.
  3160. axis (Union[None, int, tuple(int), list(int)], optional): Gradient is calculated
  3161. only along the given axis or axes. The default :class:`(axis = None)` is to calculate
  3162. the gradient for all the axes of the input tensor. `axis` may be negative,
  3163. in which case it counts from the last to the first `axis`.
  3164. Returns:
  3165. gradient, a list of tensors (or a single tensor if there is only one dimension
  3166. to be calculated). Each derivative has the same shape as f.
  3167. Raises:
  3168. TypeError: if the inputs have types not specified above.
  3169. ValueError: if `axis` values out of bounds, or shape of `f` has entries < 1.
  3170. NotImplementedError: if `edge_order` != 1, or `varargs` contains non-scalar entries.
  3171. Supported Platforms:
  3172. ``Ascend`` ``GPU`` ``CPU``
  3173. Examples:
  3174. >>> import mindspore.numpy as np
  3175. >>> output = np.gradient([[1, 2, 6], [3, 4, 5]], axis=-1)
  3176. >>> print(output)
  3177. [[1. 2.5 4. ]
  3178. [1. 1. 1. ]]
  3179. """
  3180. # This implementation was adapted from Numpy and jax.numpy
  3181. if edge_order != 1:
  3182. _raise_unimplemented_error("edge_order != 1 not implemented")
  3183. if not isinstance(f, Tensor):
  3184. f = asarray_const(f)
  3185. if f.dtype != mstype.float64:
  3186. f = f.astype(mstype.float32)
  3187. if axis is None:
  3188. axis = F.make_range(f.ndim)
  3189. else:
  3190. _check_axis_type(axis, True, True, True)
  3191. axis = _canonicalize_axis(axis, f.ndim)
  3192. axis = (axis,) if isinstance(axis, int) else axis
  3193. len_axes = len(axis)
  3194. n = len(varargs)
  3195. dx = None
  3196. # check varargs and make varags the same length as axis
  3197. if n == 0 or varargs is None:
  3198. # no spacing
  3199. dx = (1,) * len_axes
  3200. elif n == 1:
  3201. # single value for all axes
  3202. dx = varargs * len_axes
  3203. elif n == len_axes:
  3204. dx = varargs
  3205. else:
  3206. _raise_type_error("Invalid number of arguments")
  3207. a_grad = []
  3208. for idx in F.make_range(len_axes):
  3209. h = dx[idx]
  3210. ax = axis[idx]
  3211. if f.shape[ax] < 2:
  3212. _raise_value_error("Shape of array too small to calculate a numerical gradient, "
  3213. "at least 2 elements are required.")
  3214. # if h is not scalar
  3215. if not (isinstance(h, (int, float, bool)) or (isinstance(h, Tensor) and h.ndim == 0)):
  3216. _raise_unimplemented_error("Non-constant spacing not implemented")
  3217. a_grad.append(_gradient_along_axis(f, h, ax))
  3218. if len(axis) == 1:
  3219. return a_grad[0]
  3220. return a_grad
  3221. def sum_(a, axis=None, dtype=None, keepdims=False, initial=None):
  3222. """
  3223. Returns sum of array elements over a given axis.
  3224. Note:
  3225. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and
  3226. `extobj` are not supported.
  3227. Args:
  3228. x (Union[int, float, bool, list, tuple, Tensor]): Elements to sum.
  3229. axis (Union[None, int, tuple(int)]): Axis or axes along which a sum is performed. Default: None.
  3230. If None, sum all of the elements of the input array.
  3231. If axis is negative it counts from the last to the first axis.
  3232. If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple
  3233. instead of a single axis or all the axes as before.
  3234. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  3235. output Tensor.
  3236. keepdims (bool): If this is set to True, the axes which are reduced are left in the result as
  3237. dimensions with size one. With this option, the result will broadcast correctly against the input array.
  3238. If the default value is passed, then keepdims will not be passed through to the sum method of
  3239. sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not
  3240. implement keepdims any exceptions will be raised.
  3241. initial (scalar): Starting value for the sum.
  3242. Returns:
  3243. Tensor. An array with the same shape as a, with the specified axis removed.
  3244. If a is a 0-d array, or if axis is None, a scalar is returned.
  3245. If an output array is specified, a reference to out is returned.
  3246. Raises:
  3247. TypeError: If input is not array_like or `axis` is not int or tuple of ints or
  3248. `keepdims` is not integer or `initial` is not scalar.
  3249. ValueError: If any axis is out of range or duplicate axes exist.
  3250. Supported Platforms:
  3251. ``Ascend`` ``GPU`` ``CPU``
  3252. Examples:
  3253. >>> import mindspore.numpy as np
  3254. >>> print(np.sum([0.5, 1.5]))
  3255. 2.0
  3256. >>> print(np.sum(np.array([-1, 0, 1], np.int32)))
  3257. 0
  3258. >>> x = np.arange(10).reshape(2, 5).astype('float32')
  3259. >>> print(np.sum(x, axis=1))
  3260. [10. 35.]
  3261. """
  3262. a = _to_tensor(a)
  3263. return a.sum(axis, dtype, keepdims, initial)
  3264. @constexpr
  3265. def _min_cost_chain_matmul(dims):
  3266. """
  3267. Returns indices of splits that has the minimal cost for matmul.
  3268. s[i, j] holds the index of the split with minimal cost for arrays[i, i + 1, ... j]
  3269. """
  3270. dims = tuple(dims)
  3271. n = len(dims) - 1
  3272. m = [[0]*n for _ in range(n)]
  3273. s = [[0]*n for _ in range(n)]
  3274. for pos in range(1, n):
  3275. for i in range(n - pos):
  3276. j = i + pos
  3277. m[i][j] = sys.maxsize
  3278. for k in range(i, j):
  3279. cost = m[i][k] + m[k + 1][j] + dims[i]*dims[k + 1]*dims[j + 1]
  3280. if cost < m[i][j]:
  3281. m[i][j] = cost
  3282. s[i][j] = k
  3283. return s
  3284. @constexpr
  3285. def _get_dims(shapes):
  3286. """
  3287. Returns the chain of the dimensions in arrays.
  3288. dims[i] == arrays[i - 1].shape[1] == arrays[i].shape[0]
  3289. """
  3290. shapes = tuple(shapes)
  3291. if any(len(shape) != 2 for shape in shapes):
  3292. raise ValueError('Array must be 2 dimensional')
  3293. dims = tuple(map(operator.itemgetter(0), shapes))
  3294. if any(shape[1] != dim for shape, dim in zip(shapes[:-1], dims[1:])):
  3295. raise ValueError(f'shapes not aligned')
  3296. return dims + (shapes[-1][1],)
  3297. def _multi_dot(arrays, i, j, order):
  3298. """Computes multi dot recursively using minimal cost."""
  3299. if i == j:
  3300. return arrays[i]
  3301. return dot(_multi_dot(arrays, i, order[i][j], order),
  3302. _multi_dot(arrays, order[i][j] + 1, j, order))
  3303. def multi_dot(arrays):
  3304. """
  3305. Computes the dot product of two or more arrays in a single function call, while automatically
  3306. selecting the fastest evaluation order.
  3307. multi_dot chains numpy.dot and uses optimal parenthesization of the matrices
  3308. `[1] <en.wikipedia.org/wiki/Matrix_chain_multiplication>`. Depending on the shapes of the
  3309. matrices, this can speed up the multiplication a lot.
  3310. If the first argument is 1-D it is treated as a row vector. If the last argument is 1-D it
  3311. is treated as a column vector. The other arguments must be 2-D.
  3312. Note:
  3313. Numpy argument `out` is not supported.
  3314. Args:
  3315. arrays (sequence of array_like): If the first argument is 1-D it is treated as row
  3316. vector. If the last argument is 1-D it is treated as column vector. The other
  3317. arguments must be 2-D.
  3318. Returns:
  3319. Tensor, the dot product of the supplied arrays.
  3320. Raises:
  3321. ValueError: arrays are not 2-D.
  3322. Supported Platforms:
  3323. ``Ascend`` ``GPU`` ``CPU``
  3324. Examples:
  3325. >>> A = np.ones((10000, 100))
  3326. >>> B = np.ones((100, 1000))
  3327. >>> C = np.ones((1000, 5))
  3328. >>> D = np.ones((5, 333))
  3329. >>> output = np.multi_dot([A, B, C, D])
  3330. >>> print(output)
  3331. [[500000. 500000. 500000. ... 500000. 500000. 500000.]
  3332. [500000. 500000. 500000. ... 500000. 500000. 500000.]
  3333. [500000. 500000. 500000. ... 500000. 500000. 500000.]
  3334. ...
  3335. [500000. 500000. 500000. ... 500000. 500000. 500000.]
  3336. [500000. 500000. 500000. ... 500000. 500000. 500000.]
  3337. [500000. 500000. 500000. ... 500000. 500000. 500000.]]
  3338. """
  3339. if len(arrays) < 2:
  3340. _raise_value_error('Expecting at least 2 arrays')
  3341. if isinstance(arrays, (tuple, list)):
  3342. arrays = _to_tensor(*arrays)
  3343. else:
  3344. arrays = _to_tensor(arrays)
  3345. num = len(arrays)
  3346. arrays = F.reshape(arrays, (-1,) + _tuple_slice(F.shape(arrays), 2, None))
  3347. arrays = split(arrays, num)
  3348. if len(arrays) == 2:
  3349. return dot(*arrays)
  3350. shape_out = ()
  3351. arrs = []
  3352. for arr in arrays:
  3353. arrs.append(arr)
  3354. if F.rank(arrs[0]) == 1:
  3355. arrs[0] = F.reshape(arrs[0], (1, arrs[0].size))
  3356. else:
  3357. shape_out += (F.shape(arrs[0])[0],)
  3358. if F.rank(arrs[-1]) == 1:
  3359. arrs[-1] = F.reshape(arrs[-1], (arrs[-1].size, 1))
  3360. else:
  3361. shape_out += (F.shape(arrs[-1])[1],)
  3362. shapes = []
  3363. for arr in arrs:
  3364. shapes.append(F.shape(arr))
  3365. dims = _get_dims(shapes)
  3366. order = _min_cost_chain_matmul(dims)
  3367. res = _multi_dot(arrs, 0, len(arrs) - 1, order)
  3368. return F.reshape(res, shape_out)
  3369. def argmax(a, axis=None):
  3370. """
  3371. Returns the indices of the maximum values along an axis.
  3372. Note:
  3373. Numpy argument `out` is not supported.
  3374. On Ascend, in case of multiple occurrences of the maximum values, the return
  3375. indices may not necessarily correspond to the first occurrence.
  3376. Args:
  3377. a (Union[int, float, bool, list, tuple, Tensor]): Input array.
  3378. axis (int, optional): By default, the index is into
  3379. the flattened array, otherwise along the specified axis.
  3380. Returns:
  3381. Tensor, array of indices into the array. It has the same
  3382. shape as a.shape with the dimension along axis removed.
  3383. Raises:
  3384. ValueError: if axis is out of range.
  3385. Supported Platforms:
  3386. ``Ascend`` ``GPU`` ``CPU``
  3387. Examples:
  3388. >>> import mindspore.numpy as np
  3389. >>> a = np.arange(10, 16).reshape(2, 3)
  3390. >>> print(np.argmax(a))
  3391. 5
  3392. >>> print(np.argmax(a, axis=0))
  3393. [1 1 1]
  3394. >>> print(np.argmax(a, axis=1))
  3395. [2 2]
  3396. """
  3397. a = _to_tensor(a)
  3398. return a.argmax(axis)
  3399. def argmin(a, axis=None):
  3400. """
  3401. Returns the indices of the minimum values along an axis.
  3402. Note:
  3403. Numpy argument `out` is not supported.
  3404. Args:
  3405. a (Union[int, float, bool, list, tuple, Tensor]): Input array.
  3406. axis (int, optional): By default, the index is into
  3407. the flattened array, otherwise along the specified axis.
  3408. Returns:
  3409. Tensor, array of indices into the array. It has the same
  3410. shape as a.shape with the dimension along axis removed.
  3411. Raises:
  3412. ValueError: if axis is out of range.
  3413. Supported Platforms:
  3414. ``Ascend`` ``GPU`` ``CPU``
  3415. Examples:
  3416. >>> import mindspore.numpy as np
  3417. >>> a = np.arange(10, 16).reshape(2, 3)
  3418. >>> print(np.argmin(a))
  3419. 0
  3420. >>> print(np.argmin(a, axis=0))
  3421. [0 0 0]
  3422. >>> print(np.argmin(a, axis=1))
  3423. [0 0]
  3424. """
  3425. a = _to_tensor(a)
  3426. return a.argmin(axis)
  3427. @constexpr
  3428. def _get_sort_range(size):
  3429. """Returns the range for number of searches (log2(size)) on a sorted array with the given size."""
  3430. return tuple(range(ceil(log2(_to_tensor(size + 1).astype(mstype.float32))).astype(mstype.int32)))
  3431. def searchsorted(a, v, side='left', sorter=None):
  3432. """
  3433. Finds indices where elements should be inserted to maintain order.
  3434. Finds the indices into a sorted array a such that, if the corresponding elements
  3435. in v were inserted before the indices, the order of a would be preserved.
  3436. Args:
  3437. a (Union[int, float, bool, list, tuple, Tensor]): 1-D input array. If `sorter` is
  3438. None, then it must be sorted in ascending order, otherwise `sorter` must be
  3439. an array of indices that sort it.
  3440. v (Union[int, float, bool, list, tuple, Tensor]): Values to insert into `a`.
  3441. side ('left', 'right', optional): If ‘left’, the index of the first suitable
  3442. location found is given. If ‘right’, return the last such index. If there is
  3443. no suitable index, return either 0 or N (where N is the length of `a`).
  3444. sorter (Union[int, float, bool, list, tuple, Tensor]): 1-D optional array of
  3445. integer indices that sort array `a` into ascending order. They are typically
  3446. the result of argsort.
  3447. Returns:
  3448. Tensor, array of insertion points with the same shape as `v`.
  3449. Raises:
  3450. ValueError: if argument for `side` or `sorter` is invalid.
  3451. Supported Platforms:
  3452. ``Ascend`` ``GPU`` ``CPU``
  3453. Examples:
  3454. >>> from mindspore import numpy as np
  3455. >>> print(np.searchsorted([1,2,3,4,5], 3))
  3456. 2
  3457. >>> print(np.searchsorted([1,2,3,4,5], 3, side='right'))
  3458. 3
  3459. >>> print(np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3]))
  3460. [0 5 1 2]
  3461. """
  3462. if side not in ('left', 'right'):
  3463. _raise_value_error('invalid value for keyword "side"')
  3464. a = _to_tensor(a).astype(mstype.float32)
  3465. v = _to_tensor(v)
  3466. shape = F.shape(v)
  3467. if sorter is not None:
  3468. if F.rank(sorter) != 1 or sorter.size != a.size:
  3469. _raise_value_error('sorter must be 1-D array with the same size as `a`')
  3470. sorter = _to_tensor(sorter)
  3471. sorter = F.expand_dims(sorter, -1)
  3472. a = F.gather_nd(a, sorter)
  3473. less_op = F.tensor_le if side == 'left' else F.tensor_lt
  3474. i = F.fill(mstype.int32, shape, 0)
  3475. j = F.fill(mstype.int32, shape, a.size)
  3476. two = F.fill(mstype.int32, shape, 2)
  3477. for _ in _get_sort_range(a.size):
  3478. mid = floor_divide(add(i, j), two)
  3479. mask = less_op(v, F.gather_nd(a, F.expand_dims(mid, -1)))
  3480. i = F.select(mask, i, mid)
  3481. j = F.select(mask, mid, j)
  3482. return j
  3483. def interp(x, xp, fp, left=None, right=None):
  3484. """
  3485. One-dimensional linear interpolation for monotonically increasing sample points.
  3486. Returns the one-dimensional piecewise linear interpolant to a function with given
  3487. discrete data points `(xp, fp)`, evaluated at `x`.
  3488. Note:
  3489. Numpy argument `period` is not supported.
  3490. Complex values are not supported.
  3491. Args:
  3492. x (Union[int, float, bool, list, tuple, Tensor]): The x-coordinates at which
  3493. to evaluate the interpolated values.
  3494. xp (Union[int, float, bool, list, tuple, Tensor]): 1-D sequence of floats, the
  3495. x-coordinates of the data points, must be increasing.
  3496. fp (Union[int, float, bool, list, tuple, Tensor]): 1-D sequence of floats, the
  3497. y-coordinates of the data points, same length as `xp`.
  3498. left (float, optional): Value to return for ``x < xp[0]``, default is ``fp[0]``.
  3499. right (float, optional): Value to return for ``x > xp[-1]``, default is ``fp[-1]``.
  3500. Returns:
  3501. Tensor, the interpolated values, same shape as `x`.
  3502. Raises:
  3503. ValueError: if `xp` or `fp` is not one-dimensional, or if `xp` and `fp` do not have
  3504. the same length.
  3505. Supported Platforms:
  3506. ``Ascend`` ``GPU`` ``CPU``
  3507. Examples:
  3508. >>> xp = [1, 2, 3]
  3509. >>> fp = [3, 2, 0]
  3510. >>> print(np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp))
  3511. [3. 3. 2.5 0.55999994 0. ]
  3512. >>> UNDEF = -99.0
  3513. >>> print(np.interp(3.14, xp, fp, right=UNDEF))
  3514. -99.0
  3515. """
  3516. # TODO implement period once sort is supported
  3517. x, xp, fp = _to_tensor(x, xp, fp)
  3518. if F.rank(xp) != 1 or F.rank(fp) != 1:
  3519. _raise_value_error('xp and fp must be 1-d sequences')
  3520. size = xp.size
  3521. if fp.size != size:
  3522. _raise_value_error('the y-coordinates must have the same length as `xp`')
  3523. shape = F.shape(x)
  3524. xp = xp.astype(mstype.float32)
  3525. fp = fp.astype(mstype.float32)
  3526. indices_1 = clip(searchsorted(xp, x), 0, size - 1)
  3527. indices_0 = clip(indices_1 - _to_tensor(1), 0, size - 1)
  3528. indices_0 = F.expand_dims(indices_0, -1)
  3529. indices_1 = F.expand_dims(indices_1, -1)
  3530. x_0 = F.gather_nd(xp, indices_0)
  3531. x_1 = F.gather_nd(xp, indices_1)
  3532. y_0 = F.gather_nd(fp, indices_0)
  3533. y_1 = F.gather_nd(fp, indices_1)
  3534. res = (y_0*(x_1 - x) + y_1*(x - x_0))/(x_1 - x_0)
  3535. res = F.select(F.equal(x_0, x_1), y_0, res)
  3536. # where x < xp[0], y = left or xp[0]
  3537. # where x > xp[-1], y = right or xp[-1]
  3538. idx_0 = _to_tensor([0])
  3539. idx_last = _to_tensor([size - 1])
  3540. if left is None:
  3541. left = F.gather_nd(fp, idx_0)
  3542. left = full(shape, left, mstype.float32)
  3543. if right is None:
  3544. right = F.gather_nd(fp, idx_last)
  3545. right = full(shape, right, mstype.float32)
  3546. choose_left = F.tensor_lt(x, F.gather_nd(xp, idx_0))
  3547. choose_right = F.tensor_gt(x, F.gather_nd(xp, idx_last))
  3548. res = F.select(choose_left, left, res)
  3549. res = F.select(choose_right, right, res)
  3550. return res
  3551. def _apply_tensor_op(fn, *args, dtype=None):
  3552. """Applies tensor operations based on fn"""
  3553. args = _to_tensor(*args)
  3554. if isinstance(args, Tensor):
  3555. res = fn(args)
  3556. else:
  3557. res = fn(*args)
  3558. if dtype is not None and not _check_same_type(F.dtype(res), dtype):
  3559. res = F.cast(res, dtype)
  3560. return res
  3561. def sign(x, dtype=None):
  3562. """
  3563. Returns an element-wise indication of the sign of a number.
  3564. The sign function returns `-1 if x < 0, 0 if x == 0, 1 if x > 0`. nan is returned for nan inputs.
  3565. Note:
  3566. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  3567. not supported.
  3568. Complex inputs are not supported now.
  3569. Args:
  3570. x (Union[int, float, list, tuple, Tensor]): Input values.
  3571. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  3572. output Tensor.
  3573. Returns:
  3574. The sign of x. This is a tensor or a scalar when x is a scalar.
  3575. Raises:
  3576. TypeError: if dtype of the input is not in the given types or
  3577. the input can not be converted to tensor.
  3578. Supported Platforms:
  3579. ``Ascend`` ``GPU`` ``CPU``
  3580. Examples:
  3581. >>> import mindspore.numpy as np
  3582. >>> output = np.sign(np.array([-1., 0., 1., 1.2]))
  3583. >>> print(output)
  3584. [-1. 0. 1. 1.]
  3585. """
  3586. if not isinstance(x, (int, float, list, tuple, Tensor)):
  3587. _raise_type_error('integer, float, list, tuple or Tensor are expected, but got', x)
  3588. x = _to_tensor(x)
  3589. if _check_same_type(F.dtype(x), mstype.bool_):
  3590. _raise_type_error("sign does not accept dtype bool.")
  3591. _non_zero_sign = x / absolute(x)
  3592. _zero = _broadcast_to_shape(_make_tensor(0, x.dtype), x.shape)
  3593. is_zero = F.equal(x, 0)
  3594. res = F.select(is_zero, _zero, _non_zero_sign)
  3595. if dtype is not None and not _check_same_type(F.dtype(res), dtype):
  3596. res = F.cast(res, dtype)
  3597. return res
  3598. def copysign(x1, x2, dtype=None):
  3599. """
  3600. Changes the sign of `x1` to that of `x2`, element-wise.
  3601. If `x2` is a scalar, its sign will be copied to all elements of `x1`.
  3602. Note:
  3603. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  3604. not supported.
  3605. Complex inputs are not supported now.
  3606. Args:
  3607. x1 (Union[int, float, list, tuple, Tensor]): Values to change the sign of.
  3608. x2 (Union[int, float, list, tuple, Tensor]): The sign of x2 is copied to x1. If `x1.shape != x2.shape`,
  3609. they must be broadcastable to a common shape (which becomes the shape of the output).
  3610. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  3611. output Tensor.
  3612. Returns:
  3613. Tensor or scalar. The values of `x1` with the sign of `x2`. This is a scalar if both `x1` and `x2` are scalars.
  3614. Raises:
  3615. TypeError: if dtype of the input is not in the given types or
  3616. the input can not be converted to tensor.
  3617. Supported Platforms:
  3618. ``Ascend`` ``GPU`` ``CPU``
  3619. Examples:
  3620. >>> import mindspore.numpy as np
  3621. >>> output = np.copysign(np.array([1, -1, -1]), np.array([-1, 1, -1]))
  3622. >>> print(output)
  3623. [-1 1 -1]
  3624. """
  3625. if not isinstance(x1, (int, float, list, tuple, Tensor)):
  3626. _raise_type_error('integer, float, list, tuple or Tensor are expected, but got', x1)
  3627. if not isinstance(x2, (int, float, list, tuple, Tensor)):
  3628. _raise_type_error('integer, float, list, tuple or Tensor are expected, but got', x2)
  3629. x1, x2 = _to_tensor(x1, x2)
  3630. x2 = _broadcast_to_shape(x2, x1.shape)
  3631. if _check_same_type(F.dtype(x1), mstype.bool_) or _check_same_type(F.dtype(x2), mstype.bool_):
  3632. _raise_type_error("sign does not accept dtype bool.")
  3633. original_dtype = x1.dtype
  3634. if not _check_is_float(original_dtype):
  3635. pos_tensor = F.absolute(x1.astype('float32')).astype(original_dtype)
  3636. else:
  3637. pos_tensor = F.absolute(x1)
  3638. neg_tensor = F.neg_tensor(pos_tensor)
  3639. less_zero = F.less(x2, 0)
  3640. res = F.select(less_zero, neg_tensor, pos_tensor)
  3641. if dtype is not None and not _check_same_type(F.dtype(res), dtype):
  3642. res = F.cast(res, dtype)
  3643. return res
  3644. def digitize(x, bins, right=False):
  3645. """
  3646. Returns the indices of the bins to which each value in input array belongs.
  3647. If values in `x` are beyond the bounds of `bins`, 0 or ``len(bins)`` is returned
  3648. as appropriate.
  3649. Args:
  3650. x (Union[int, float, bool, list, tuple, Tensor]): Input array to be binned.
  3651. bins (Union[int, float, bool, list, tuple, Tensor]): Array of bins. It has to
  3652. be 1-dimensional and monotonic.
  3653. right (boolean, optional): Indicating whether the intervals include the right
  3654. or the left bin edge. Default behavior is ``(right==False)`` indicating
  3655. that the interval does not include the right edge. The left bin end is
  3656. open in this case, i.e., ``bins[i-1] <= x < bins[i]`` is the default
  3657. behavior for monotonically increasing bins.
  3658. Returns:
  3659. Tensor of ints, output array of indices, of same shape as `x`.
  3660. Supported Platforms:
  3661. ``Ascend`` ``GPU`` ``CPU``
  3662. Examples:
  3663. >>> import mindspore.numpy as np
  3664. >>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.])
  3665. >>> bins = np.array([0, 5, 10, 15, 20])
  3666. >>> inds = np.digitize(x, bins)
  3667. >>> print(inds)
  3668. [1 3 3 4 5]
  3669. """
  3670. x, bins = _to_tensor(x, bins)
  3671. if F.rank(bins) > 1:
  3672. _raise_value_error('bins should be 1-dimensional')
  3673. if x.size == 0:
  3674. return x
  3675. if bins.size == 0:
  3676. return zeros(F.shape(x), mstype.int32)
  3677. side = 'left' if right else 'right'
  3678. first_bin = bins[0]
  3679. last_bin = bins[_type_convert(int, bins.size) - 1]
  3680. cond = first_bin <= last_bin
  3681. incr = searchsorted(bins, x, side)
  3682. decr = _to_tensor(bins.size) - searchsorted(flip(bins), x, side)
  3683. return where_(cond, incr, decr)
  3684. def bincount(x, weights=None, minlength=0, length=None):
  3685. """
  3686. Count number of occurrences of each value in array of non-negative ints.
  3687. The number of bins (of size 1) is one larger than the largest value in `x`.
  3688. If `minlength` is specified, there will be at least this number of bins in the
  3689. output array (though it will be longer if necessary, depending on the contents
  3690. of `x`). Each bin gives the number of occurrences of its index value in `x`. If
  3691. `weights` is specified the input array is weighted by it, i.e. if a value `n`
  3692. is found at position `i`, ``out[n] += weight[i]`` instead of ``out[n] += 1``.
  3693. Note:
  3694. The additional argument `length` specifies the number of bins (overriding
  3695. ``x.max() + 1``), which must be provided in graph mode.
  3696. If `x` contains negative values, no error will be raised, and negative values
  3697. are treated as zeros instead.
  3698. Args:
  3699. x (Union[list, tuple, Tensor]): 1-d input array.
  3700. weights (Union[int, float, bool, list, tuple, Tensor], optional): Weights,
  3701. array of the same shape as `x`.
  3702. minlength (int, optional): A minimum number of bins for the output array.
  3703. length (int, optional): Number of bins.
  3704. Returns:
  3705. Tensor, the result of binning the input array. The length of out is equal to
  3706. ``np.amax(x)+1``.
  3707. Raises:
  3708. ValueError: if `x` is not one-dimensional, or if `x` and `weights` do not have
  3709. the same shape.
  3710. Supported Platforms:
  3711. ``Ascend`` ``GPU`` ``CPU``
  3712. Examples:
  3713. >>> import mindspore.numpy as np
  3714. >>> print(np.bincount(np.arange(5)))
  3715. [1 1 1 1 1]
  3716. >>> print(np.bincount(np.array([0, 1, 1, 3, 2, 1, 7])))
  3717. [1 3 1 1 0 0 0 1]
  3718. >>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
  3719. >>> x = np.array([0, 1, 1, 2, 2, 2])
  3720. >>> print(np.bincount(x, weights=w))
  3721. [0.3 0.7 1.1]
  3722. """
  3723. x = _to_tensor(x)
  3724. if F.rank(x) != 1:
  3725. _raise_value_error('`x` should be one-dimensional')
  3726. if not _check_is_int(F.dtype(x)):
  3727. _raise_type_error('`x` should be an array of ints')
  3728. x = clip(x, 0, None)
  3729. if length is None:
  3730. if F.isconstant(x):
  3731. length = int(maximum(F.reduce_max(x.astype(mstype.float32)), minlength - 1).asnumpy()) + 1
  3732. else:
  3733. _raise_value_error('argument `length` must be provided in graph mode')
  3734. idx = arange(length).reshape(length, 1)
  3735. idx_mapping = F.equal(x, idx)
  3736. if weights is not None:
  3737. weights = _to_tensor(weights)
  3738. if F.shape(x) != F.shape(weights):
  3739. _raise_value_error('`x` and `weights` must have the same length')
  3740. idx_mapping *= weights
  3741. return F.reduce_sum(idx_mapping.astype(mstype.float32), 1).ravel()
  3742. def histogram(a, bins=10, range=None, weights=None, density=False): # pylint: disable=redefined-builtin
  3743. """
  3744. Computes the histogram of a dataset.
  3745. Note:
  3746. String values for `bins` is not supported.
  3747. Deprecated numpy argument `normed` is not supported.
  3748. Args:
  3749. a (Union[int, float, bool, list, tuple, Tensor]): Input data. The histogram
  3750. is computed over the flattened array.
  3751. bins (Union[int, tuple, list, Tensor], optional): If `bins` is an int, it
  3752. defines the number of equal-width bins in the given range (10, by
  3753. default). If `bins` is a sequence, it defines the bin edges, including
  3754. the rightmost edge, allowing for non-uniform bin widths.
  3755. range((float, float), optional): The lower and upper range of the bins. If
  3756. not provided, `range` is simply ``(a.min(), a.max())``. Values outside
  3757. the range are ignored. The first element of the range must be less than
  3758. or equal to the second.
  3759. weights (Union[int, float, bool, list, tuple, Tensor], optional): An array
  3760. of weights, of the same shape as `a`. Each value in a only contributes
  3761. its associated weight towards the bin count (instead of 1). If density
  3762. is True, the weights are normalized, so that the integral of the density
  3763. over the range remains 1.
  3764. density (boolean, optional): If False, the result will contain the number of
  3765. samples in each bin. If True, the result is the value of the probability
  3766. density function at the bin, normalized such that the integral over the
  3767. range is 1. Note that the sum of the histogram values will not be equal
  3768. to 1 unless bins of unity width are chosen; it is not a probability mass
  3769. function.
  3770. Returns:
  3771. (Tensor, Tensor), the values of the histogram and the bin edges.
  3772. Raises:
  3773. ValueError: if `x` and `weights` do not have the same size.
  3774. Supported Platforms:
  3775. ``Ascend`` ``GPU`` ``CPU``
  3776. Examples:
  3777. >>> from mindspore import numpy as np
  3778. >>> print(np.histogram([1, 2, 1], bins=[0, 1, 2, 3]))
  3779. (Tensor(shape=[3], dtype=Float32, value= [0, 2, 1]),
  3780. Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 3]))
  3781. >>> print(np.histogram(np.arange(4), bins=np.arange(5), density=True))
  3782. (Tensor(shape=[4], dtype=Float32, value=
  3783. [ 2.50000000e-01, 2.50000000e-01, 2.50000000e-01, 2.50000000e-01]),
  3784. Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]))
  3785. >>> print(np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]))
  3786. (Tensor(shape=[3], dtype=Float32, value= [1, 4, 1]),
  3787. Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 3]))
  3788. """
  3789. a = _to_tensor(a).ravel()
  3790. bin_edges = histogram_bin_edges(a, bins, range, weights)
  3791. data_to_bins = searchsorted(bin_edges, a, 'right')
  3792. bin_size = _type_convert(int, bin_edges.size)
  3793. data_to_bins = where_(a == bin_edges[-1], _to_tensor(bin_size - 1), data_to_bins)
  3794. if weights is not None:
  3795. weights = _to_tensor(weights).ravel()
  3796. count = bincount(data_to_bins, weights, length=bin_size)[1:]
  3797. if count.size == 0:
  3798. return count, bin_edges
  3799. if density:
  3800. count = F.cast(count, mstype.float32)
  3801. count = count/diff(bin_edges)/F.reduce_sum(count)
  3802. return count, bin_edges
  3803. @constexpr
  3804. def _factor_flattened_hist(nbin):
  3805. """Returns the factor that will be applied to the histogram to be flattened."""
  3806. factor = list((itertools.accumulate(nbin[1:][::-1], operator.mul)))[::-1]
  3807. factor.append(1)
  3808. return factor
  3809. def histogramdd(sample, bins=10, range=None, weights=None, density=False): # pylint: disable=redefined-builtin
  3810. """
  3811. Computes the multidimensional histogram of some data.
  3812. Note:
  3813. Deprecated numpy argument `normed` is not supported.
  3814. Args:
  3815. sample (Union[list, tuple, Tensor]): The data to be histogrammed, either `(N, D)`
  3816. array, or `(D, N)` array_like. Note the unusual interpretation of sample
  3817. when an array_like:
  3818. When an array, each row is a coordinate in a `D-dimensional` space - such as
  3819. ``histogramdd(np.array([p1, p2, p3]))``.
  3820. When an array_like, each element is the list of values for single coordinate
  3821. - such as ``histogramdd((X, Y, Z))``.
  3822. The first form should be preferred.
  3823. bins (Union[int, tuple, list], optional): The bin specification:
  3824. A sequence of arrays describing the monotonically increasing bin edges along
  3825. each dimension.
  3826. The number of bins for each dimension ``(nx, ny, … =bins)``
  3827. The number of bins for all dimensions ``(nx=ny=…=bins)``.
  3828. range(Union[list, tuple], optional): A sequence of length `D`, each an optional
  3829. ``(lower, upper)`` tuple giving the outer bin edges to be used if the edges
  3830. are not given explicitly in bins. An entry of None in the sequence results in
  3831. the minimum and maximum values being used for the corresponding dimension.
  3832. The default, None, is equivalent to passing a tuple of `D` None values.
  3833. weights (Union[list, tuple, Tensor], optional): An array with shape `(N,)` of values
  3834. `w_i` weighing each sample ``(x_i, y_i, z_i, …)``.
  3835. density (boolean, optional): If False, the default, returns the number of samples
  3836. in each bin. If True, returns the probability density function at the bin,
  3837. ``bin_count / sample_count / bin_volume``.
  3838. Returns:
  3839. (Tensor, list of Tensor), the values of the histogram and the bin edges.
  3840. Raises:
  3841. ValueError: if `range` does not have the same size as the number of samples.
  3842. Supported Platforms:
  3843. ``Ascend`` ``GPU`` ``CPU``
  3844. Examples:
  3845. >>> from mindspore import numpy as np
  3846. >>> sample = np.arange(15).reshape(5, 3)
  3847. >>> print(sample)
  3848. [[ 0 1 2]
  3849. [ 3 4 5]
  3850. [ 6 7 8]
  3851. [ 9 10 11]
  3852. [12 13 14]]
  3853. >>> print(np.histogramdd(sample, bins=(2, 3, 4)))
  3854. (Tensor(shape=[2, 3, 4], dtype=Float32, value=
  3855. [[[1, 1, 0, 0],
  3856. [0, 0, 0, 0],
  3857. [0, 0, 0, 0]],
  3858. [[0, 0, 0, 0],
  3859. [0, 0, 1, 0],
  3860. [0, 0, 0, 2]]]),
  3861. [Tensor(shape=[3], dtype=Float32, value=
  3862. [ 0.00000000e+00, 6.00000000e+00, 1.20000000e+01]),
  3863. Tensor(shape=[4], dtype=Float32, value=
  3864. [ 1.00000000e+00, 5.00000000e+00, 9.00000000e+00, 1.30000000e+01]),
  3865. Tensor(shape=[5], dtype=Float32, value=
  3866. [ 2.00000000e+00, 5.00000000e+00, 8.00000000e+00, 1.10000000e+01, 1.40000000e+01])])
  3867. """
  3868. if isinstance(sample, (tuple, list)):
  3869. sample = _to_tensor(*sample)
  3870. sample = stack(sample, -1)
  3871. elif not isinstance(sample, Tensor):
  3872. _raise_type_error('sample should be (N, D) array, or (D, N) array_like')
  3873. if F.rank(sample) != 2:
  3874. _raise_value_error('when an array, sample should be 2-dimensional')
  3875. ndim = F.shape(sample)[1]
  3876. if isinstance(bins, int):
  3877. bins = _list_comprehensions(ndim, bins)
  3878. if isinstance(bins, (tuple, list, Tensor)):
  3879. if len(bins) != ndim:
  3880. _raise_value_error('The dimension of bins must be equal to the dimension of the sample')
  3881. else:
  3882. _raise_type_error('bins should be int or sequence')
  3883. if range is None:
  3884. range = _list_comprehensions(ndim, None, False, True)
  3885. else:
  3886. if len(range) != ndim:
  3887. _raise_value_error('range argument must have one entry per dimension')
  3888. bin_edges = []
  3889. dedges = []
  3890. for i in F.make_range(ndim):
  3891. edges = histogram_bin_edges(sample[:, i], bins[i], range[i], weights)
  3892. bin_edges.append(edges)
  3893. dedges.append(diff(edges))
  3894. data_indices = []
  3895. nbin = ()
  3896. flattened_bin_size = 1
  3897. for i in F.make_range(ndim):
  3898. data_to_bins = searchsorted(bin_edges[i], sample[:, i], 'right')
  3899. bin_size = _type_convert(int, bin_edges[i].size)
  3900. data_to_bins = where_(sample[:, i] == bin_edges[i][-1], _to_tensor(bin_size - 1), data_to_bins)
  3901. data_indices.append(data_to_bins)
  3902. nbin += (bin_size + 1,)
  3903. flattened_bin_size *= (bin_size + 1)
  3904. factor = F.reshape(_to_tensor(_factor_flattened_hist(nbin)), (ndim, 1))
  3905. stacked_indices = stack(data_indices) * factor
  3906. if _get_device() == 'Ascend':
  3907. stacked_indices = F.cast(stacked_indices, mstype.float32)
  3908. flattened_hist = F.reduce_sum(stacked_indices.astype(mstype.float32), 0)
  3909. count = bincount(flattened_hist.astype(mstype.int32), weights, length=flattened_bin_size)
  3910. count = F.reshape(count, nbin)
  3911. slices = _list_comprehensions(ndim, F.make_slice(1, -1, 1), True)
  3912. count = count[slices]
  3913. if density:
  3914. s = F.reduce_sum(count.astype(mstype.float32))
  3915. for i in F.make_range(ndim):
  3916. shape = _expanded_shape(ndim, dedges[i].size, i)
  3917. count /= _to_tensor(dedges[i]).reshape(shape)
  3918. count /= s
  3919. return count, bin_edges
  3920. def histogram2d(x, y, bins=10, range=None, weights=None, density=False): # pylint: disable=redefined-builtin
  3921. """
  3922. Computes the multidimensional histogram of some data.
  3923. Note:
  3924. Deprecated numpy argument `normed` is not supported.
  3925. Args:
  3926. x (Union[list, tuple, Tensor]): An array with shape `(N,)` containing the x
  3927. coordinates of the points to be histogrammed.
  3928. y (Union[list, tuple, Tensor]): An array with shape `(N,)` containing the y
  3929. coordinates of the points to be histogrammed.
  3930. bins (Union[int, tuple, list], optional): The bin specification:
  3931. If int, the number of bins for the two dimensions ``(nx=ny=bins)``.
  3932. If array_like, the bin edges for the two dimensions ``(x_edges=y_edges=bins)``.
  3933. If [int, int], the number of bins in each dimension ``(nx, ny = bins)``.
  3934. If [array, array], the bin edges in each dimension ``(x_edges, y_edges = bins)``.
  3935. A combination [int, array] or [array, int], where int is the number of bins and
  3936. array is the bin edges.
  3937. range(Union[list, tuple], optional): has shape (2, 2), the leftmost and rightmost
  3938. edges of the bins along each dimension (if not specified explicitly in the bins
  3939. parameters): ``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range
  3940. will be considered outliers and not tallied in the histogram.
  3941. weights (Union[list, tuple, Tensor], optional): An array with shape `(N,)` of values
  3942. `w_i` weighing each sample `(x_i, y_i)`.
  3943. density (boolean, optional): If False, the default, returns the number of samples
  3944. in each bin. If True, returns the probability density function at the bin,
  3945. ``bin_count / sample_count / bin_volume``.
  3946. Returns:
  3947. (Tensor, Tensor, Tensor), the values of the bi-directional histogram and the bin edges
  3948. along the first and second dimensions.
  3949. Raises:
  3950. ValueError: if `range` does not have the same size as the number of samples.
  3951. Supported Platforms:
  3952. ``Ascend`` ``GPU`` ``CPU``
  3953. Examples:
  3954. >>> from mindspore import numpy as np
  3955. >>> x = np.arange(5)
  3956. >>> y = np.arange(2, 7)
  3957. >>> print(np.histogram2d(x, y, bins=(4, 6)))
  3958. (Tensor(shape=[4, 6], dtype=Float32, value=
  3959. [[1, 0, 0, 0, 0, 0],
  3960. [0, 1, 0, 0, 0, 0],
  3961. [0, 0, 0, 1, 0, 0]
  3962. [0, 0, 0, 0, 1, 1]]),
  3963. Tensor(shape=[5], dtype=Float32, value=
  3964. [ 0.00000000e+00, 1.00000000e+00, 2.00000000e+00, 3.00000000e+00, 4.00000000e+00]),
  3965. Tensor(shape=[7], dtype=Float32, value=
  3966. [ 2.00000000e+00, 2.66666675e+00, 3.33333349e+00, 4.00000000e+00, 4.66666698e+00,
  3967. 5.33333349e+00, 6.00000000e+00]))
  3968. """
  3969. count, bin_edges = histogramdd((x, y), bins=bins, range=range, weights=weights, density=density)
  3970. return count, bin_edges[0], bin_edges[1]
  3971. def matrix_power(a, n):
  3972. """
  3973. Raises a square matrix to the (integer) power `n`.
  3974. For positive integers `n`, the power is computed by repeated matrix squarings and
  3975. matrix multiplications.
  3976. If :math:`n == 0`, the identity matrix of the same shape as `M` is returned.
  3977. Note:
  3978. Stacks of object matrices are not currently supported and
  3979. :math:`n < 0` is not supported.
  3980. Args:
  3981. a (Union[int, float, bool, list, tuple, Tensor]): Input matrix.
  3982. n (int): The exponent can be any integer or long integer, positive or zero.
  3983. Returns:
  3984. Tensor.
  3985. Raises:
  3986. TypeError: if the input can not be converted to a tensor or
  3987. the exponent is not integer.
  3988. ValueError: if the input includes less than 2 dimensions or
  3989. the last 2 dimensions are not square.
  3990. Supported Platforms:
  3991. ``Ascend`` ``GPU`` ``CPU``
  3992. Examples:
  3993. >>> from mindspore import numpy as np
  3994. >>> a = np.arange(16).reshape(4, 4).astype('float32')
  3995. >>> print(np.matrix_power(a, 2))
  3996. [[ 56. 62. 68. 74.]
  3997. [152. 174. 196. 218.]
  3998. [248. 286. 324. 362.]
  3999. [344. 398. 452. 506.]]
  4000. """
  4001. a = _to_tensor(a)
  4002. if not isinstance(n, int):
  4003. _raise_type_error("exponent must be an integer")
  4004. if a.ndim < 2:
  4005. _raise_value_error("Array must be at least two-dimensional")
  4006. if a.shape[-2] != a.shape[-1]:
  4007. _raise_value_error("Last 2 dimensions of the array must be square")
  4008. if n < 0:
  4009. _raise_value_error("n < 0 is not supported now.")
  4010. if n == 0:
  4011. return _broadcast_to_shape(eye(a.shape[-1], a.shape[-1], dtype=a.dtype), a.shape)
  4012. if n == 1:
  4013. return a
  4014. res = a
  4015. while n > 1:
  4016. res = C.matmul(res, a)
  4017. n = n - 1
  4018. return res
  4019. def around(a, decimals=0):
  4020. """
  4021. Evenly round to the given number of decimals.
  4022. Note:
  4023. Numpy argument `out` is not supported.
  4024. Complex numbers are not supported.
  4025. Args:
  4026. a (Union[int, float, list, tuple, Tensor]): Input data.
  4027. decimals (int): Number of decimal places to round to. Default: 0.
  4028. Returns:
  4029. Tensor. A tensor of the same type as a, containing the rounded values.
  4030. The result of rounding a float is a float.
  4031. Raises:
  4032. TypeError: if the input can not be converted to a tensor or
  4033. the `decimals` argument is not integer.
  4034. Supported Platforms:
  4035. ``Ascend`` ``GPU`` ``CPU``
  4036. Examples:
  4037. >>> import mindspore.numpy as np
  4038. >>> a = np.array([-1.3, 0.0, 0.5, 1.5, 2.5])
  4039. >>> print(np.around(a))
  4040. [-1. 0. 0. 2. 2.]
  4041. """
  4042. a = _to_tensor_origin_dtype(a)
  4043. if not isinstance(decimals, int):
  4044. _raise_type_error("decimals must be an integer")
  4045. if decimals < 0:
  4046. _raise_value_error("decimals < 0 is not supported now.")
  4047. if decimals == 0:
  4048. return _round(a)
  4049. return F.tensor_div(_round(a * 10**decimals), 10**decimals)
  4050. def _to_poly1d(x):
  4051. x = atleast_1d(_to_tensor(x))
  4052. if F.rank(x) > 1:
  4053. _raise_value_error('input array must be scalar or 1-d sequence')
  4054. return x
  4055. def polyadd(a1, a2):
  4056. """
  4057. Finds the sum of two polynomials.
  4058. Returns the polynomial resulting from the sum of two input polynomials.
  4059. Note:
  4060. Numpy object poly1d is currently not supported.
  4061. Args:
  4062. a1 (Union[int, float, bool, list, tuple, Tensor): Input polynomial.
  4063. a2 (Union[int, float, bool, list, tuple, Tensor): Input polynomial.
  4064. Returns:
  4065. Tensor, the sum of the inputs.
  4066. Raises:
  4067. ValueError: if the input array has more than 1 dimensions.
  4068. Supported Platforms:
  4069. ``Ascend`` ``GPU`` ``CPU``
  4070. Examples:
  4071. >>> import mindspore.numpy as np
  4072. >>> print(np.polyadd([1, 2], [9, 5, 4]))
  4073. [9 6 6]
  4074. """
  4075. a1 = _to_poly1d(a1)
  4076. a2 = _to_poly1d(a2)
  4077. diff_size = a1.size - a2.size
  4078. if diff_size == 0:
  4079. return add(a1, a2)
  4080. if diff_size > 0:
  4081. return concatenate((a1[:diff_size], add(a1[diff_size:], a2)))
  4082. return concatenate((a2[:-diff_size], add(a1, a2[-diff_size:])))
  4083. def polysub(a1, a2):
  4084. """
  4085. Difference (subtraction) of two polynomials.
  4086. Given two polynomials `a1` and `a2`, returns ``a1 - a2``.
  4087. Note:
  4088. Numpy object poly1d is currently not supported.
  4089. Args:
  4090. a1 (Union[int, float, bool, list, tuple, Tensor): Minuend polynomial.
  4091. a2 (Union[int, float, bool, list, tuple, Tensor): Subtrahend polynomial.
  4092. Returns:
  4093. Tensor, the difference of the inputs.
  4094. Raises:
  4095. ValueError: if the input array has more than 1 dimensions.
  4096. Supported Platforms:
  4097. ``Ascend`` ``GPU`` ``CPU``
  4098. Examples:
  4099. >>> import mindspore.numpy as np
  4100. >>> print(np.polysub([2, 10, -2], [3, 10, -4]))
  4101. [-1 0 2]
  4102. """
  4103. return polyadd(a1, -_to_tensor(a2))
  4104. def polyval(p, x):
  4105. """
  4106. Evaluates a polynomial at specific values.
  4107. If `p` is of length `N`, this function returns the value:
  4108. ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]``
  4109. If `x` is a sequence, then ``p(x)`` is returned for each element of `x`. If `x`
  4110. is another polynomial then the composite polynomial ``p(x(t))`` is returned.
  4111. Note:
  4112. Numpy object poly1d is currently not supported.
  4113. Args:
  4114. p (Union[int, float, bool, list, tuple, Tensor): 1D array of polynomial
  4115. coefficients (including coefficients equal to zero) from highest
  4116. degree to the constant term.
  4117. x (Union[int, float, bool, list, tuple, Tensor): A number, an array of
  4118. numbers, at which to evaluate `p`.
  4119. Returns:
  4120. Tensor.
  4121. Raises:
  4122. ValueError: if `p` has more than 1 dimensions.
  4123. Supported Platforms:
  4124. ``Ascend`` ``GPU`` ``CPU``
  4125. Examples:
  4126. >>> import mindspore.numpy as np
  4127. >>> print(np.polyval([3,0,1], 5))
  4128. 76
  4129. """
  4130. p = _to_poly1d(p)
  4131. x = _to_tensor(x)
  4132. shape = F.shape(x)
  4133. exp_p = arange(_type_convert(int, p.size) - 1, -1, -1)
  4134. var_p = (x.reshape(shape + (1,)))**exp_p
  4135. return F.reduce_sum(p*var_p, -1)
  4136. def polyder(p, m=1):
  4137. """
  4138. Returns the derivative of the specified order of a polynomial.
  4139. Note:
  4140. Numpy object poly1d is currently not supported.
  4141. Args:
  4142. p (Union[int, float, bool, list, tuple, Tensor): Polynomial to differentiate.
  4143. A sequence is interpreted as polynomial coefficients.
  4144. m (int, optional): Defaults to 1, order of differentiation.
  4145. Returns:
  4146. Tensor, a new polynomial representing the derivative.
  4147. Raises:
  4148. ValueError: if `p` has more than 1 dimensions.
  4149. Supported Platforms:
  4150. ``Ascend`` ``GPU`` ``CPU``
  4151. Examples:
  4152. >>> import mindspore.numpy as np
  4153. >>> print(np.polyder([1, 1, 1, 1]))
  4154. [3 2 1]
  4155. """
  4156. p = _to_poly1d(p)
  4157. if m < 0:
  4158. _raise_value_error('Order of derivative must be positive')
  4159. if m >= p.size:
  4160. return _to_tensor([])
  4161. for _ in range(m):
  4162. coeff = _to_tensor(F.make_range(_type_convert(int, p.size) - 1, 0, -1))
  4163. p = p[:-1]*coeff
  4164. return p
  4165. def polymul(a1, a2):
  4166. """
  4167. Finds the product of two polynomials.
  4168. Note:
  4169. Numpy object poly1d is currently not supported.
  4170. Args:
  4171. a1 (Union[int, float, bool, list, tuple, Tensor): Input polynomial.
  4172. a2 (Union[int, float, bool, list, tuple, Tensor): Input polynomial.
  4173. Returns:
  4174. Tensor, a new polynomial representing the derivative.
  4175. Raises:
  4176. ValueError: if the input array has more than 1 dimensions.
  4177. Supported Platforms:
  4178. ``Ascend`` ``GPU`` ``CPU``
  4179. Examples:
  4180. >>> import mindspore.numpy as np
  4181. >>> print(np.polymul([3, 1, 2], [2, 5]))
  4182. [ 6 17 9 10]
  4183. """
  4184. a1 = _to_poly1d(a1)
  4185. a2 = _to_poly1d(a2)
  4186. return convolve(a1, a2)
  4187. def polyint(p, m=1, k=None):
  4188. """
  4189. Returns an antiderivative (indefinite integral) of a polynomial.
  4190. Note:
  4191. Numpy object poly1d is currently not supported.
  4192. Args:
  4193. p (Union[int, float, bool, list, tuple, Tensor): Polynomial to integrate. A
  4194. sequence is interpreted as polynomial coefficients.
  4195. m (int, optional): Defaults to 1, Order of the antiderivative.
  4196. k (Union[int, list of int]y, optinoal): Integration constants. They are given
  4197. in the order of integration: those corresponding to highest-order terms
  4198. come first. If None (default), all constants are assumed to be zero. If
  4199. ``m = 1``, a single scalar can be given instead of a list.
  4200. Returns:
  4201. Tensor, a new polynomial representing the antiderivative.
  4202. Raises:
  4203. ValueError: if `p` has more than 1 dimensions.
  4204. Supported Platforms:
  4205. ``Ascend`` ``GPU`` ``CPU``
  4206. Examples:
  4207. >>> import mindspore.numpy as np
  4208. >>> print(np.polyint([1, 1, 1]))
  4209. [0.33333334 0.5 1. 0. ]
  4210. """
  4211. p = _to_poly1d(p)
  4212. if m < 0:
  4213. _raise_value_error('Order of derivative must be positive')
  4214. if m == 0:
  4215. return p
  4216. if k is None:
  4217. k = zeros(m, F.dtype(p))
  4218. k = atleast_1d(_to_tensor(k))
  4219. if k.size == 1:
  4220. k = F.tile(k, (m,))
  4221. k = F.expand_dims(k, -1)
  4222. for i in range(m):
  4223. coeff = _to_tensor(F.make_range(_type_convert(int, p.size), 0, -1))
  4224. p = concatenate((true_divide(p, coeff), k[i]))
  4225. return p
  4226. @constexpr
  4227. def _get_dtype(x):
  4228. """Returns the dtype of x."""
  4229. if isinstance(x, bool):
  4230. return mstype.bool_
  4231. if isinstance(x, int):
  4232. return mstype.int32
  4233. if isinstance(x, float):
  4234. return mstype.float32
  4235. if isinstance(x, typing.Number):
  4236. return x
  4237. if isinstance(x, str):
  4238. t = dtype_map.get(x, None)
  4239. if t is None:
  4240. t = dtype_map.get(str(nptype(x)))
  4241. return t
  4242. raise TypeError('data type not understood')
  4243. def result_type(*arrays_and_dtypes):
  4244. """
  4245. Returns the type that results from applying the type promotion rules to the arguments.
  4246. Note:
  4247. The promotion rule is slightly different from original Numpy, but more like
  4248. jax, due to the preference on ``32-bit`` over ``64-bit`` data types.
  4249. Complex dtypes are not supported.
  4250. Args:
  4251. *arrays_and_dtypes (Union[int, float, bool, list, tuple, Tensor, :class:`mindspore.dtype`, str]):
  4252. The operands of some operation whose result type is needed.
  4253. Returns:
  4254. :class:`mindspore.dtype`, the result type.
  4255. Raises:
  4256. TypeError: if the input is not a valid data type.
  4257. Supported Platforms:
  4258. ``Ascend`` ``GPU`` ``CPU``
  4259. Examples:
  4260. >>> import mindspore.numpy as np
  4261. >>> print(np.result_type('i2', np.float32, True))
  4262. Float32
  4263. """
  4264. def get_dtype(x):
  4265. if isinstance(x, Tensor):
  4266. return F.dtype(_to_tensor(x))
  4267. return _get_dtype(x)
  4268. dtype_out = get_dtype(arrays_and_dtypes[0])
  4269. for i in arrays_and_dtypes[1:]:
  4270. dtype_out = _promote(dtype_out, get_dtype(i))
  4271. return dtype_out
  4272. def unwrap(p, discont=3.141592653589793, axis=-1):
  4273. """
  4274. Unwraps by changing deltas between values to ``2*pi`` complement.
  4275. Unwraps radian phase `p` by changing absolute jumps greater than `discont` to their
  4276. `2*pi` complement along the given axis.
  4277. Note:
  4278. For absolute jumps that are within a very close range to pi, unwrapping may be done
  4279. differently than numpy due to differences in round-off.
  4280. Args:
  4281. p (Union[int, float, bool, list, tuple, Tensor): Input array.
  4282. discont (float, optional): Maximum discontinuity between values, default is pi.
  4283. axis (int, optional): Axis along which unwrap will operate, default is the last axis.
  4284. Returns:
  4285. Tensor.
  4286. Raises:
  4287. ValueError: if the axis is out of range.
  4288. Supported Platforms:
  4289. ``Ascend`` ``GPU`` ``CPU``
  4290. Examples:
  4291. >>> import mindspore.numpy as np
  4292. >>> phase = np.add(np.linspace(0, np.pi, num=5), [0, 0, 0, np.pi, np.pi])
  4293. >>> print(phase)
  4294. [0. 0.7853982 1.5707964 5.4977875 6.2831855]
  4295. >>> print(np.unwrap(phase))
  4296. [ 0.0000000e+00 7.8539819e-01 1.5707964e+00 -7.8539848e-01 -4.7683716e-07]
  4297. """
  4298. if not isinstance(discont, (int, float)):
  4299. _raise_type_error('discont should be a float')
  4300. p = _to_tensor(p)
  4301. ndim = F.rank(p)
  4302. axis = _check_axis_in_range(axis, ndim)
  4303. dd = diff(p, axis=axis)
  4304. ddmod = remainder(add(dd, pi), 2*pi) - pi
  4305. ddmod = where_(F.logical_and(ddmod == -pi, dd > 0), pi, ddmod)
  4306. ph_correct = ddmod - dd
  4307. ph_correct = where_(absolute(dd) < discont, 0, ph_correct)
  4308. slice_all = _list_comprehensions(F.rank(p), F.make_slice(None, None, None), True)
  4309. slice0 = _tuple_setitem(slice_all, axis, F.make_slice(0, 1, None))
  4310. slice1 = _tuple_setitem(slice_all, axis, F.make_slice(1, None, None))
  4311. head = p[slice0]
  4312. tail = add(p[slice1], cumsum(ph_correct, axis))
  4313. return concatenate((head, tail), axis=axis)
  4314. def cumprod(a, axis=None, dtype=None):
  4315. """
  4316. Returns the cumulative product of elements along a given axis.
  4317. Note:
  4318. Numpy argument `out` is not supported.
  4319. Args:
  4320. a (Union[int, float, bool, list, tuple, Tensor]): Input tensor.
  4321. axis (int, optional): Axis along which the cumulative product is computed.
  4322. By default the input is flattened.
  4323. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Overrides the dtype of the
  4324. output Tensor.
  4325. Returns:
  4326. Tensor.
  4327. Raises:
  4328. TypeError: If the input can not be converted to tensor or `axis` is not integer.
  4329. ValueError: If axis is out of range.
  4330. Supported Platforms:
  4331. ``Ascend``
  4332. Examples:
  4333. >>> import mindspore.numpy as np
  4334. >>> x = np.array([1, 2, 3])
  4335. >>> print(np.cumprod(x))
  4336. [1 2 6]
  4337. """
  4338. a = _to_tensor_origin_dtype(a)
  4339. original_dtype = F.dtype(a)
  4340. if axis is not None and not isinstance(axis, int):
  4341. _raise_type_error("integer axis is expected, but got", axis)
  4342. if axis is None:
  4343. a = a.ravel()
  4344. axis = 0
  4345. _check_axis_in_range(axis, a.ndim)
  4346. a = a.astype('float32') if original_dtype != mstype.float64 else a
  4347. if dtype is None:
  4348. if original_dtype in [mstype.int8, mstype.int16, mstype.bool_]:
  4349. dtype = mstype.int32
  4350. elif original_dtype in [mstype.uint8, mstype.uint16]:
  4351. dtype = mstype.uint32
  4352. else:
  4353. dtype = original_dtype
  4354. return _cumprod_default(a, axis).astype(dtype, copy=False)
  4355. def _process_index(index, dims, mode='raise'):
  4356. """Generates index (Tensor) according to different modes."""
  4357. if mode == "raise":
  4358. _raise_unimplemented_error("'raise' mode is not implemented")
  4359. if mode not in ['clip', 'wrap']:
  4360. _raise_value_error("invalid mode. Expected 'wrap' or 'clip'")
  4361. ori_shape = index.shape
  4362. tup = ()
  4363. for i, idx in enumerate(index):
  4364. d = dims[i]
  4365. if mode == "clip":
  4366. idx = clip(idx, 0, d - 1)
  4367. elif mode == "wrap":
  4368. idx = remainder(idx, d)
  4369. idx = F.expand_dims(idx, 0) if idx.ndim < 1 else idx
  4370. tup += (idx,)
  4371. return P.Concat(0)(tup).reshape(ori_shape)
  4372. def _get_strides(dims, order='C'):
  4373. """Generates strides (1-D tensor) according to `dims` (1-D tensor)."""
  4374. if order not in ['C', 'F']:
  4375. _raise_value_error("invalid order. Expected 'C' or 'F'")
  4376. tup = (_to_tensor([1]),)
  4377. dims = dims[1:][::-1] if order == 'C' else dims[:-1]
  4378. for d in dims:
  4379. tensor = tup[-1] * d
  4380. if tensor.ndim < 1:
  4381. tensor = F.expand_dims(tensor, 0)
  4382. tup += (tensor,)
  4383. tup = tup[::-1] if order == 'C' else tup
  4384. return P.Concat(0)(tup)
  4385. def ravel_multi_index(multi_index, dims, mode='clip', order='C'):
  4386. """
  4387. Converts a tuple of index arrays into an array of flat indices,
  4388. applying boundary modes to the multi-index.
  4389. Note:
  4390. `raise` mode is not supported. Default mode is `clip`.
  4391. Args:
  4392. multi_index (tuple of array_like):
  4393. A tuple of integer arrays, one array for each dimension.
  4394. dims (Union[int, tuple of ints]): The shape of array into which the indices from multi_index apply.
  4395. mode ({`wrap`, `clip`}): Specifies how out-of-bounds indices are handled. Default: `clip`.
  4396. - `wrap`: wrap around
  4397. - `clip`: clip to the range
  4398. In `clip` mode, a negative index which would normally wrap will clip to 0 instead.
  4399. order ({`C`, `F`}): Determines whether the multi-index should be viewed as indexing in
  4400. row-major (C-style) or column-major (Fortran-style) order.
  4401. Returns:
  4402. Raveled_indices array. An array of indices into the flattened version of an array of dimensions dims.
  4403. Raises:
  4404. TypeError: If `multi_index` or `dims` can not be converted to tensor or
  4405. `dims` is not a sequence of integer values.
  4406. ValueError: If the length of `multi_index` and that of `dims` are not equal.
  4407. Supported Platforms:
  4408. ``GPU``
  4409. Examples:
  4410. >>> import mindspore.numpy as np
  4411. >>> arr = np.array([[3, 6, 6], [4, 5, 1]])
  4412. >>> output = np.ravel_multi_index(arr, (7, 6))
  4413. >>> print(output)
  4414. [22. 41. 37.]
  4415. """
  4416. if isinstance(dims, int):
  4417. dims = (dims,)
  4418. dims = _to_tensor(dims)
  4419. if dims.ndim > 1 or dims.dtype in (mstype.float16, mstype.float32, mstype.float64, mstype.bool_):
  4420. _raise_type_error("only 1-D integer arrays are accepted.")
  4421. multi_index = _to_tensor(multi_index)
  4422. if len(multi_index) != len(dims):
  4423. _raise_value_error("parameter multi_index must be a sequence of length ", len(dims))
  4424. if multi_index.dtype in (mstype.float16, mstype.float32, mstype.float64):
  4425. _raise_type_error("only int indices permitted")
  4426. multi_index = _process_index(multi_index, dims, mode)
  4427. strides = _get_strides(dims, order)
  4428. s_shape = strides.shape + _list_comprehensions(multi_index.ndim - 1, 1, True)
  4429. strides = _broadcast_to_shape(strides.reshape(s_shape), multi_index.shape)
  4430. return sum_((multi_index * strides).astype('float32'), axis=0)
  4431. def _vector_norm(x, ord, axis, keepdims): # pylint: disable=redefined-builtin
  4432. """Returns norm of a vector."""
  4433. if _in(ord, ('fro', 'nuc')):
  4434. _raise_value_error('Frobenius norm and nuclear norm are only defined for vectors')
  4435. if ord is None:
  4436. ord = 2
  4437. if ord == inf:
  4438. res = P.ReduceMax(keepdims)(absolute(x), axis)
  4439. elif ord == -inf:
  4440. res = P.ReduceMin(keepdims)(absolute(x), axis)
  4441. elif ord == 0:
  4442. res = P.ReduceSum(keepdims)(F.not_equal(x, 0).astype(mstype.float32), axis)
  4443. else:
  4444. res = power(P.ReduceSum(keepdims)(power(absolute(x), ord), axis), 1./ord)
  4445. return res
  4446. def _matrix_norm(x, ord, axis, keepdims): # pylint: disable=redefined-builtin
  4447. """Returns norm of a matrix."""
  4448. if ord == 0:
  4449. _raise_value_error('for 0 axis, norm is defined only for 2-D matrices')
  4450. if ord == 'nuc':
  4451. _raise_unimplemented_error('nuclear norm is not implemented')
  4452. if _in(ord, (2, -2)):
  4453. _raise_unimplemented_error('2-norm is not implemented for matrices')
  4454. if _in(ord, (None, 'fro')):
  4455. res = F.sqrt(P.ReduceSum(keepdims)(F.square(x), axis))
  4456. else:
  4457. axis0, axis1 = axis
  4458. if not keepdims:
  4459. if _abs(ord) == inf and axis0 > axis1:
  4460. axis0 -= 1
  4461. elif _abs(ord) == 1 and axis1 > axis0:
  4462. axis1 -= 1
  4463. if ord == inf:
  4464. res = P.ReduceMax(keepdims)(P.ReduceSum(keepdims)(absolute(x), axis1), axis0)
  4465. elif ord == -inf:
  4466. res = P.ReduceMin(keepdims)(P.ReduceSum(keepdims)(absolute(x), axis1), axis0)
  4467. elif ord == 1:
  4468. res = P.ReduceMax(keepdims)(P.ReduceSum(keepdims)(absolute(x), axis0), axis1)
  4469. elif ord == -1:
  4470. res = P.ReduceMin(keepdims)(P.ReduceSum(keepdims)(absolute(x), axis0), axis1)
  4471. else:
  4472. return _raise_value_error('invalid norm order for matrices')
  4473. return res
  4474. def norm(x, ord=None, axis=None, keepdims=False): # pylint: disable=redefined-builtin
  4475. """
  4476. Matrix or vector norm.
  4477. This function is able to return one of eight different matrix norms, or one of an
  4478. infinite number of vector norms (described below), depending on the value of the
  4479. ord parameter.
  4480. Note:
  4481. Nuclear norm and 2-norm are not supported for matrices.
  4482. Args:
  4483. x (Union[int, float, bool, list, tuple, Tensor]): Input array. If `axis` is None,
  4484. `x` must be 1-D or 2-D, unless `ord` is None. If both `axis` and `ord` are None,
  4485. the 2-norm of ``x.ravel`` will be returned.
  4486. ord (Union[None, 'fro', 'nuc', inf, -inf, int, float], optional): Order of the norm.
  4487. inf means numpy’s inf object. The default is None.
  4488. axis (Union[None, int, 2-tuple of ints], optional): If `axis` is an integer, it
  4489. specifies the axis of `x` along which to compute the vector norms. If `axis` is
  4490. a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of
  4491. these matrices are computed. If `axis` is None then either a vector norm (when x
  4492. is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default is None.
  4493. keepdims (boolean, optional): If this is set to True, the axes which are normed over
  4494. are left in the result as dimensions with size one. With this option the result
  4495. will broadcast correctly against the original `x`.
  4496. Returns:
  4497. Tensor, norm of the matrix or vector(s).
  4498. Raises:
  4499. ValueError: If the norm order is not defined.
  4500. Supported Platforms:
  4501. ``Ascend`` ``GPU`` ``CPU``
  4502. Examples:
  4503. >>> import mindspore.numpy as np
  4504. >>> print(np.norm(np.arange(9)))
  4505. 14.282857
  4506. """
  4507. if not isinstance(ord, (int, float)) and not _in(ord, (None, 'fro', 'nuc', inf, -inf)):
  4508. _raise_value_error('invalid value for `ord`')
  4509. x = _to_tensor(x)
  4510. ndim = F.rank(x)
  4511. if axis is None:
  4512. if ord is None:
  4513. x = x.ravel()
  4514. if F.rank(x) not in (1, 2):
  4515. _raise_value_error('for None axis, array must a vector or a 2-D matrix')
  4516. axis = F.make_range(F.rank(x))
  4517. axis = _check_axis_valid(axis, F.rank(x))
  4518. if len(axis) == 1:
  4519. res = _vector_norm(x, ord, axis, keepdims)
  4520. elif len(axis) == 2:
  4521. res = _matrix_norm(x, ord, axis, keepdims)
  4522. else:
  4523. return _raise_value_error('invalid number of dimensions to norm')
  4524. if keepdims and ndim > F.rank(res):
  4525. res = _expand(res, ndim)
  4526. return res
  4527. def bitwise_and(x1, x2, dtype=None):
  4528. """
  4529. Computes the bit-wise AND of two arrays element-wise.
  4530. Computes the bit-wise AND of the underlying binary representation of the integers in
  4531. the input arrays. This ufunc implements the C/Python operator &.
  4532. Note:
  4533. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  4534. not supported.
  4535. Args:
  4536. x1 (Tensor): Input array.
  4537. x2 (Tensor): Input array. Only integer and boolean types are handled. If
  4538. ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes
  4539. the shape of the output).
  4540. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  4541. output Tensor.
  4542. Returns:
  4543. Tensor or scalar, this is a scalar if both x1 and x2 are scalars.
  4544. Supported Platforms:
  4545. ``Ascend``
  4546. Examples:
  4547. >>> import mindspore.numpy as np
  4548. >>> print(np.bitwise_and(13, 17))
  4549. 1
  4550. """
  4551. return _apply_tensor_op(F.bitwise_and, x1, x2, dtype=dtype)
  4552. def bitwise_or(x1, x2, dtype=None):
  4553. r"""
  4554. Computes the bit-wise OR of two arrays element-wise.
  4555. Computes the bit-wise OR of the underlying binary representation of the integers in
  4556. the input arrays. This ufunc implements the C/Python operator \|.
  4557. Note:
  4558. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  4559. not supported.
  4560. Args:
  4561. x1 (Tensor): Input array.
  4562. x2 (Tensor): Input array. Only integer and boolean types are handled. If
  4563. ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes
  4564. the shape of the output).
  4565. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  4566. output Tensor.
  4567. Returns:
  4568. Tensor or scalar, this is a scalar if both x1 and x2 are scalars.
  4569. Supported Platforms:
  4570. ``Ascend``
  4571. Examples:
  4572. >>> import mindspore.numpy as np
  4573. >>> print(np.bitwise_or(13, 16))
  4574. 29
  4575. """
  4576. return _apply_tensor_op(F.bitwise_or, x1, x2, dtype=dtype)
  4577. def bitwise_xor(x1, x2, dtype=None):
  4578. """
  4579. Computes the bit-wise XOR of two arrays element-wise.
  4580. Computes the bit-wise XOR of the underlying binary representation of the integers in
  4581. the input arrays. This ufunc implements the C/Python operator ^.
  4582. Note:
  4583. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  4584. not supported.
  4585. Args:
  4586. x1 (Tensor): Input array.
  4587. x2 (Tensor): Input array. Only integer and boolean types are handled. If
  4588. ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes
  4589. the shape of the output).
  4590. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  4591. output Tensor.
  4592. Returns:
  4593. Tensor or scalar, this is a scalar if both x1 and x2 are scalars.
  4594. Supported Platforms:
  4595. ``Ascend``
  4596. Examples:
  4597. >>> import mindspore.numpy as np
  4598. >>> print(np.bitwise_xor(13, 17))
  4599. 28
  4600. """
  4601. return _apply_tensor_op(F.bitwise_xor, x1, x2, dtype=dtype)
  4602. def invert(x, dtype=None):
  4603. """
  4604. Computes bit-wise inversion, or bit-wise NOT, element-wise.
  4605. Computes the bit-wise NOT of the underlying binary representation of the integers in
  4606. the input arrays. This ufunc implements the C/Python operator ~.
  4607. For signed integer inputs, the two’s complement is returned. In a two’s-complement system
  4608. negative numbers are represented by the two’s complement of the absolute value. This is
  4609. the most common method of representing signed integers on computers
  4610. `[1] <https://en.wikipedia.org/wiki/Two’s_complement>`_. A N-bit two’s-complement system
  4611. can represent every integer in the range ``-2^{N-1}`` to ``+2^{N-1}-1``.
  4612. Note:
  4613. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  4614. not supported.
  4615. Supported dtypes on Ascend: np.int16, np.uint16.
  4616. Args:
  4617. x (Tensor): Only integer and boolean types are handled.
  4618. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  4619. output Tensor.
  4620. Returns:
  4621. Tensor or scalar.
  4622. Supported Platforms:
  4623. ``Ascend``
  4624. Examples:
  4625. >>> import mindspore.numpy as np
  4626. >>> print(np.invert(np.array(13, dtype=np.uint16)))
  4627. 65522
  4628. """
  4629. return _apply_tensor_op(F.invert, x, dtype=dtype)
  4630. def rint(x, dtype=None):
  4631. """
  4632. Rounds elements of the array to the nearest integer.
  4633. Note:
  4634. Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are
  4635. not supported.
  4636. Args:
  4637. x (Union[float, list, tuple, Tensor]): Input tensor.
  4638. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  4639. output Tensor.
  4640. Returns:
  4641. Output tensor is same shape and type as x. This is a scalar if x is a scalar.
  4642. Raises:
  4643. TypeError: If `x` can not be converted to tensor.
  4644. Supported Platforms:
  4645. ``Ascend`` ``GPU`` ``CPU``
  4646. Examples:
  4647. >>> import mindspore.numpy as np
  4648. >>> x = np.array([-1.7, -1.5, 0.2, 1.5, 1.7, 2.0])
  4649. >>> print(np.rint(x))
  4650. [-2. -2. 0. 2. 2. 2.]
  4651. """
  4652. x = _to_tensor_origin_dtype(x)
  4653. res = _rint(x)
  4654. if dtype is not None and not _check_same_type(F.dtype(res), dtype):
  4655. res = F.cast(res, dtype)
  4656. return res
  4657. def correlate(a, v, mode='valid'):
  4658. """
  4659. Cross-correlation of two 1-dimensional sequences.
  4660. This function computes the correlation as generally defined in signal processing texts:
  4661. :math:`c_{av}[k] = sum_n a[n+k] * conj(v[n])`
  4662. with `a` and `v` sequences being zero-padded where necessary and conj being the conjugate.
  4663. Note:
  4664. Currently, complex numbers are not supported.
  4665. Args:
  4666. a (Union[list, tuple, Tensor]): First input sequence.
  4667. v (Union[list, tuple, Tensor]): Second input sequence.
  4668. mode (str, optional): By default, mode is `\'valid\'`.
  4669. If `mode` is `\'valid\'`, it returns output of length :math:`max(M, N) - min(M, N) + 1`.
  4670. The convolution product is only given for points where the signals overlap
  4671. completely. Values outside the signal boundary have no effect.
  4672. If `mode` is `\'full\'`, it returns the convolution at each point of overlap, with
  4673. an output shape of :math:`(N + M - 1,)`.
  4674. At the end-points of the convolution, the signals do not overlap completely,
  4675. and boundary effects may be seen.
  4676. If `mode` is `\'same\'`, it returns output of length :math:`max(M, N)`. Boundary
  4677. effects are still visible.
  4678. Returns:
  4679. Tensor. Discrete cross-correlation of `a` and `v`.
  4680. Raises:
  4681. TypeError: if the inputs can not be converted to tensor.
  4682. ValueError: if `a` and `v` are empty or have wrong dimensions
  4683. Supported Platforms:
  4684. ``GPU``
  4685. Examples:
  4686. >>> import mindspore.numpy as np
  4687. >>> output = np.correlate([1, 2, 3], [0, 1, 0.5])
  4688. >>> print(output)
  4689. [3.5]
  4690. >>> output = np.correlate([1, 2, 3], [0, 1, 0.5], mode="same")
  4691. >>> print(output)
  4692. [2. 3.5 3. ]
  4693. """
  4694. a, v = _to_tensor(a, v)
  4695. if a.ndim != 1 or v.ndim != 1:
  4696. _raise_value_error("only support 1-dimensional inputs.")
  4697. if a.size == 0 or v.size == 0:
  4698. _raise_value_error("Inputs cannot be empty.")
  4699. promote_dtype = _promote(a.dtype, v.dtype)
  4700. # P.Conv2D requires that the two tensors have the same data type.
  4701. # If the promote data type is not supported, it will be converted to float32.
  4702. # The supported dtype list may vary in the future.
  4703. if promote_dtype not in [mstype.float32, mstype.float16]:
  4704. promote_dtype = mstype.float32
  4705. a = a.astype(promote_dtype)
  4706. v = v.astype(promote_dtype)
  4707. if a.size < v.size:
  4708. a, v = v, a
  4709. return _compute_1D_conv(a, v, mode)[::-1]
  4710. return _compute_1D_conv(a, v, mode)
  4711. def _compute_1D_conv(a, v, mode):
  4712. """Returns a 1-D sequence which is the cross-correlate of two 1-D sequences (`a` and `v`)."""
  4713. v_size = F.shape_mul(v.shape)
  4714. if mode not in ('same', 'full', 'valid'):
  4715. _raise_value_error("mode must be one of ['full', 'same', 'valid']")
  4716. if v_size > 1:
  4717. if mode == 'same':
  4718. pad_left = _to_tensor(_list_comprehensions(v_size // 2, 0.0, True))
  4719. pad_right = _to_tensor(_list_comprehensions(v_size - v_size // 2 - 1, 0.0, True))
  4720. a = P.Concat(0)((pad_left, a, pad_right))
  4721. elif mode == 'full':
  4722. pad = _to_tensor(_list_comprehensions(v_size - 1, 0.0, True))
  4723. a = P.Concat(0)((pad, a, pad))
  4724. a = a.reshape(1, 1, 1, a.size)
  4725. v = v.reshape(1, 1, 1, v.size)
  4726. _conv = P.Conv2D(1, (1, v.size))
  4727. return _conv(a, v).reshape(-1)
  4728. def radians(x, dtype=None):
  4729. """
  4730. Converts angles from degrees to radians.
  4731. Args:
  4732. x (Tensor): Angles in degrees.
  4733. dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
  4734. output Tensor.
  4735. Returns:
  4736. Tensor, the corresponding radian values. This is a tensor scalar if `x`
  4737. is a tensor scalar.
  4738. Raises:
  4739. TypeError: if `x` is not a tensor.
  4740. Supported Platforms:
  4741. ``Ascend`` ``GPU`` ``CPU``
  4742. Examples:
  4743. >>> import mindspore.numpy as np
  4744. >>> x = np.asarray([1, 2, 3, -4, -5])
  4745. >>> output = np.radians(x)
  4746. >>> print(output)
  4747. [ 0.01745329 0.03490658 0.05235988 -0.06981317 -0.08726647]
  4748. """
  4749. return deg2rad(x, dtype=dtype)