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 207 kB

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