2.4K Star 8.1K Fork 4.4K

GVPMindSpore / mindspore

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
tensor.py 208.98 KB
Copy Edit Raw Blame History
zhangyi authored 2022-08-22 17:27 . modify the supported platforms
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355
# Copyright 2020-2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Tensor implementation."""
from __future__ import absolute_import
import numbers
import numpy as np
from mindspore.communication.management import get_rank, get_group_size
from mindspore.common._utils import is_shape_unknown
from mindspore import context
from mindspore import log as logger
from . import dtype as mstype
from ._register_for_tensor import tensor_operator_registry
from .._c_expression import COOTensor as COOTensor_
from .._c_expression import CSRTensor as CSRTensor_
from .._c_expression import RowTensor as RowTensor_
from .._c_expression import Tensor as Tensor_
from .._checkparam import Rel
from .._checkparam import Validator as validator
__all__ = ['Tensor', 'RowTensor', 'SparseTensor', 'COOTensor', 'CSRTensor']
np_types = (np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64, np.float16,
np.float32, np.float64, np.bool_, np.complex64, np.complex128)
class Tensor(Tensor_):
"""
Tensor is a data structure that stores an n-dimensional array.
Args:
input_data (Union[Tensor, float, int, bool, tuple, list, numpy.ndarray]): The data to be stored. It can be
another Tensor, Python number or NumPy ndarray. Default: None.
dtype (:class:`mindspore.dtype`): Used to indicate the data type of the output Tensor. The argument should
be defined in `mindspore.dtype`. If it is None, the data type of the output Tensor will be the same
as the `input_data`. Default: None.
shape (Union[tuple, list, int]): Used to indicate the shape of the output Tensor. The argument should be
a list of integers, a tuple of integers or an integer. If `input_data` is available,
`shape` doesn't need to be set. Default: None.
init (Initializer): The information of init data.
'init' is used for delayed initialization in parallel mode. Usually, it is not recommended to use
'init' interface to initialize Tensor in the other conditions. If 'init' interface is used to initialize
Tensor, the `Tensor.init_data` API needs to be called to convert `Tensor` to the actual data.
Default: None.
internal (bool): Whether it is created by the framework.
'True' means that the tensor is created by framework.
'False' means that the tensor is created by user.
Default: False
Outputs:
Tensor.
Examples:
>>> import numpy as np
>>> import mindspore as ms
>>> from mindspore import Tensor
>>> from mindspore.common.initializer import One
>>> # initialize a tensor with numpy.ndarray
>>> t1 = Tensor(np.zeros([1, 2, 3]), ms.float32)
>>> print(t1)
[[[0. 0. 0.]
[0. 0. 0.]]]
>>> print(type(t1))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t1.shape)
(1, 2, 3)
>>> print(t1.dtype)
Float32
>>>
>>> # initialize a tensor with a float scalar
>>> t2 = Tensor(0.1)
>>> print(t2)
0.1
>>> print(type(t2))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t2.shape)
()
>>> print(t2.dtype)
Float32
>>>
>>> # initialize a tensor with a tuple
>>> t3 = Tensor((1, 2))
>>> print(t3)
[1 2]
>>> print(type(t3))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t3.shape)
(2,)
>>> print(t3.dtype)
Int64
...
>>> # initialize a tensor with init
>>> t4 = Tensor(shape = (1, 3), dtype=ms.float32, init=One())
>>> print(t4)
[[1. 1. 1.]]
>>> print(type(t4))
<class 'mindspore.common.tensor.Tensor'>
>>> print(t4.shape)
(1, 3)
>>> print(t4.dtype)
Float32
"""
delta_seed = 0
def __init__(self, input_data=None, dtype=None, shape=None, init=None, internal=False):
self.init_finished = False
if internal:
Tensor_.__init__(self, input_data)
else:
# If input data is numpy number, convert it to np array
if isinstance(input_data, np_types):
input_data = np.array(input_data)
if isinstance(shape, numbers.Number):
shape = (shape,)
_check_tensor_input(input_data, dtype, shape, init)
# If input_data is tuple/list/numpy.ndarray, it's support in check_type method.
if (isinstance(shape, (list, tuple)) and None in shape) or init is not None:
shape = _check_tensor_dynamic_shape(dtype, shape, init)
Tensor_.__init__(self, dtype, shape)
else:
validator.check_value_type('input_data', input_data,
(Tensor_, np.ndarray, np.str_, list, tuple, float, int, bool, complex),
'Tensor')
valid_dtypes = (np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64,
np.float16, np.float32, np.float64, np.bool_, np.str_, np.complex64, np.complex128)
if isinstance(input_data, np.ndarray) and input_data.dtype not in valid_dtypes and \
input_data.dtype.kind != 'U' and input_data.dtype.kind != 'S': # Support dtype np.str_
raise TypeError(f"For Tensor, the input_data is a numpy array, "
f"but it's data type: {input_data.dtype} is not in supported list: "
f"{list(i.__name__ for i in valid_dtypes)}.")
if isinstance(input_data, np.ndarray) and input_data.dtype.kind == "S" and \
input_data.shape and context.get_context("enable_ge"):
raise TypeError("For binary string input in GE mode, the shape of the data must be ()")
if isinstance(input_data, (tuple, list)) and np.array(input_data).dtype not in valid_dtypes:
raise TypeError(
f"For Tensor, the input_data is {input_data} that contain unsupported element.")
if dtype is not None:
validator.check_type_name(
'dtype', dtype, mstype.number_type + (mstype.bool_, mstype.string), "Tensor")
else:
dtype = self._set_default_dtype(input_data, dtype)
if isinstance(input_data, np.ndarray) and (not input_data.flags['FORC']):
input_data = np.ascontiguousarray(input_data)
if dtype is not None:
Tensor_.__init__(self, input_data, dtype)
else:
Tensor_.__init__(self, input_data)
self.virtual_flag = False
self.init = init
self.init_finished = True
# if cur Tensor is a index value of another Tensor,
# parent_tensor_ set to another Tensor
# index_of_parent_ will set to the index
self.parent_tensor_ = None
self.index_of_parent_ = None
@staticmethod
def _set_default_dtype(input_data, dtype):
if isinstance(input_data, (float, list, tuple)):
if np.array(input_data).dtype == np.float64:
return mstype.float32
return dtype
def __deepcopy__(self, memodict):
new_obj = Tensor(self)
new_obj.init = self.init
new_obj.virtual_flag = self.virtual_flag
return new_obj
def __repr__(self):
if self.init_finished:
Tensor_.data_sync(self, True)
return Tensor_.__repr__(self)
return ''
def __eq__(self, other):
if not isinstance(other, (int, float, Tensor)):
return False
# bool type is not supported for `Equal` operator in backend.
if self.dtype == mstype.bool_ or (isinstance(other, Tensor) and other.dtype == mstype.bool_):
if isinstance(other, Tensor):
return Tensor(np.array(self.asnumpy() == other.asnumpy()))
return Tensor(np.array(self.asnumpy() == other))
return tensor_operator_registry.get('__eq__')(self, other)
def __ne__(self, other):
if not isinstance(other, (int, float, Tensor)):
return True
# bool type is not supported for `NotEqual` operator in backend.
if self.dtype == mstype.bool_ or (isinstance(other, Tensor) and other.dtype == mstype.bool_):
return Tensor(np.array(self.asnumpy() != other.asnumpy()))
return tensor_operator_registry.get('__ne__')(self, other)
def __hash__(self):
return hash(id(self))
def __neg__(self):
out = tensor_operator_registry.get('__neg__')(self)
return out
def __invert__(self):
out = tensor_operator_registry.get('__logical_not__')(self)
return out
def __bool__(self):
data = self.asnumpy()
if data.shape == ():
return bool(data)
if data.shape == (1,):
return bool(data[0])
raise ValueError("The truth value of an array with several elements is ambiguous.")
@staticmethod
def _convert_scalar_(data, func, message):
if data.shape == ():
return func(data)
if data.shape == (1,):
return func(data[0])
raise ValueError(message)
def __int__(self):
data = self.asnumpy()
return self._convert_scalar_(data, int, "Only one element tensors can be converted to Python scalars")
def __float__(self):
data = self.asnumpy()
return self._convert_scalar_(data, float, "Only one element tensors can be converted to Python scalars")
def __index__(self):
data = self.asnumpy()
if not (data.dtype == "int8"
or data.dtype == "int16"
or data.dtype == "int32"
or data.dtype == "int64"
or data.dtype == "bool"):
raise ValueError("Only integer tensors of a single element can be converted to an index.")
return self._convert_scalar_(data, int,
"Only integer tensors of a single element can be converted to an index.")
def __pos__(self):
return self
def __abs__(self):
data = abs(self.asnumpy())
if isinstance(data, np.number):
data = np.array(data)
return Tensor(data)
def __add__(self, other):
return tensor_operator_registry.get('__add__')(self, other)
def __radd__(self, other):
return self.__add__(other)
def __iadd__(self, other):
return self.__add__(other)
def __sub__(self, other):
return tensor_operator_registry.get('__sub__')(self, other)
def __rsub__(self, other):
return tensor_operator_registry.get('__sub__')(other, self)
def __isub__(self, other):
return self.__sub__(other)
def __mul__(self, other):
return tensor_operator_registry.get('__mul__')(self, other)
def __rmul__(self, other):
return self.__mul__(other)
def __imul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
return tensor_operator_registry.get('__truediv__')(self, other)
def __rtruediv__(self, other):
return tensor_operator_registry.get('__truediv__')(other, self)
def __mod__(self, other):
return tensor_operator_registry.get('__mod__')(self, other)
def __rmod__(self, other):
return tensor_operator_registry.get('__mod__')(other, self)
def __imod__(self, other):
return self.__mod__(other)
def __pow__(self, other):
return tensor_operator_registry.get('__pow__')(self, other)
def __rpow__(self, other):
return tensor_operator_registry.get('__rpow__')(self, other)
def __floordiv__(self, other):
return tensor_operator_registry.get('__floordiv__')(self, other)
def __rfloordiv__(self, other):
return tensor_operator_registry.get('__floordiv__')(other, self)
def __ifloordiv__(self, other):
return self.__floordiv__(other)
def __lt__(self, other):
out = tensor_operator_registry.get('__lt__')(self, other)
return out
def __le__(self, other):
out = tensor_operator_registry.get('__le__')(self, other)
return out
def __getitem__(self, index):
out = tensor_operator_registry.get('__getitem__')(self, index)
if out is not self:
out.parent_tensor_ = self
out.index_of_parent_ = index
return out
def __setitem__(self, index, value):
out = tensor_operator_registry.get('__setitem__')(self, index, value)
self.assign_value(out)
if self.parent_tensor_ is not None and self.index_of_parent_ is not None:
self.parent_tensor_.__setitem__(self.index_of_parent_, self)
return self
def __gt__(self, other):
out = tensor_operator_registry.get('__gt__')(self, other)
return out
def __ge__(self, other):
out = tensor_operator_registry.get('__ge__')(self, other)
return out
def __len__(self):
out = tensor_operator_registry.get('shape')(self)
if out:
return out[0]
raise TypeError("Not support len of a 0-D tensor")
def __str__(self):
if self.dtype == mstype.type_none:
return "Unknown Tensor type!"
return str(self.asnumpy())
@property
def shape(self):
"""Returns the shape of the tensor as a tuple."""
return self._shape
@property
def dtype(self):
"""Return the dtype of the tensor (:class:`mindspore.dtype`)."""
return self._dtype
@property
def size(self):
"""Returns the total number of elements in tensor."""
return self._size
@property
def ndim(self):
"""Return the number of tensor dimensions."""
return len(self._shape)
@property
def has_init(self):
"""Whether tensor is initialized."""
return self.init is not None
@property
def itemsize(self):
"""Return the length of one tensor element in bytes."""
return self._itemsize
@property
def strides(self):
"""Return the tuple of bytes to step in each dimension when traversing a tensor."""
return self._strides
@property
def nbytes(self):
"""Return the total number of bytes taken by the tensor."""
return self._nbytes
@property
def T(self):
"""Return the transposed tensor."""
return self.transpose()
@staticmethod
def from_numpy(array):
"""
Convert numpy array to Tensor without copy data.
Args:
array (numpy.array): The input array.
Returns:
Tensor, has the same data type as input array.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = np.array([1, 2])
>>> output = Tensor.from_numpy(x)
>>> print(output)
[1 2]
"""
return Tensor(Tensor_.from_numpy(array))
def assign_value(self, value):
"""
Assign another tensor value to this tensor.
Args:
value (Tensor): Tensor for assignment.
Returns:
Tensor, Tensor that's been assigned.
"""
self.assign_value_cpp(value)
return self
def item(self, index=None):
"""
Get the item at the specified index of the tensor.
Note:
Tensor.item returns a Tensor scalar instead of a Python scalar.
Args:
index (Union[None, int, tuple(int)]): The index in Tensor. Default: None.
Returns:
A Tensor scalar, dtype is the same with the original Tensor.
Raises:
ValueError: If the length of the `index` is not equal to self.ndim.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,2,3],[4,5,6]], dtype=np.float32))
>>> x = x.item((0,1))
>>> print(x)
2.0
"""
output = tensor_operator_registry.get('item')(self, index)
return output
def itemset(self, *args):
r"""
Insert scalar into a tensor (scalar is cast to tensor's dtype, if possible).
There must be at least 1 argument, and define the last argument as item.
Then, tensor.itemset(\*args) is equivalent to :math:`tensor[args] = item`.
Args:
args (Union[(numbers.Number), (int/tuple(int), numbers.Number)]): The arguments that
specify the index and value. If `args` contain one argument (a scalar),
it is only used in case tensor is of size 1. If `args` contain two
arguments, the last argument is the value to be set and must be a
scalar, the first argument specifies a single tensor element location.
It is either an int or a tuple.
Returns:
A new tensor that doesn't affect the original tensor, with value set by :math:`tensor[args] = item`.
Raises:
ValueError: If the length of the first argument is not equal to self.ndim.
IndexError: If only one argument is provided, and the original Tensor is not scalar.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1,2,3],[4,5,6]], dtype=np.float32))
>>> print(x.itemset((0,1), 4))
[[1. 4. 3.]
[4. 5. 6.]]
>>> print(x)
[[1. 2. 3.]
[4. 5. 6.]]
"""
output = tensor_operator_registry.get('itemset')(self, *args)
return output
def asnumpy(self):
"""
Convert tensor to numpy array. Returns self tensor as a NumPy ndarray. This tensor and the returned ndarray
share the same underlying storage. Changes to self tensor will be reflected in the ndarray.
Returns:
A numpy ndarray which shares the same underlying storage with the tensor.
Examples:
>>> from mindspore import Tensor
>>> import numpy as np
>>> x = Tensor(np.array([1, 2], dtype=np.float32))
>>> y = x.asnumpy()
>>> y[0] = 11
>>> print(x)
[11. 2.]
>>> print(y)
[11. 2.]
"""
self._init_check()
return Tensor_.asnumpy(self)
def flush_from_cache(self):
"""
Flush cache data to host if tensor is cache enable.
Examples:
>>> from mindspore import Tensor
>>> import numpy as np
>>> x = Tensor(np.array([1, 2], dtype=np.float32))
>>> y = x.flush_from_cache()
>>> print(y)
None
"""
self._init_check()
Tensor_._flush_from_cache(self)
def all(self, axis=(), keep_dims=False):
"""
Check all tensor elements along a given axis evaluate to True.
Args:
axis (Union[None, int, tuple(int)]): Dimensions of reduction.
When the axis is None or empty tuple, reduce all dimensions. When the axis is int or
tuple(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().
keep_dims (bool): Whether to keep the reduced dimensions. Default: False.
Returns:
Tensor, if all tensor elements along the given axis evaluate to True, its value is True,
otherwise its value is False. If the axis is None or empty tuple, reduce all dimensions.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.any`: Check any tensor element along a given axis evaluate to True.
Examples:
>>> from mindspore import Tensor
>>> a = Tensor([True, True, False])
>>> output = a.all()
>>> print(output)
False
"""
self._init_check()
if axis is None:
axis = ()
return tensor_operator_registry.get('all')(keep_dims)(self, axis)
def any(self, axis=(), keep_dims=False):
"""
Check any tensor element along a given axis evaluate to True.
Args:
axis (Union[None, int, tuple(int)]): Dimensions of reduction.
When the axis is None or empty tuple, reduce all dimensions. When the axis is int or
tuple(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().
keep_dims (bool): Whether to keep the reduced dimensions. Default: False.
Returns:
Tensor, if any tensor element along the given axis evaluates to True, its value is True,
otherwise its value is False. If the axis is None or empty tuple, reduce all dimensions.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.all`: Check all tensor elements along a given axis evaluate to True.
Examples:
>>> from mindspore import Tensor
>>> a = Tensor([True, True, False])
>>> output = a.any()
>>> print(output)
True
"""
self._init_check()
if axis is None:
axis = ()
return tensor_operator_registry.get('any')(keep_dims)(self, axis)
def atan2(self, y):
r"""
Returns arctangent of x/y element-wise.
`x` refer to self tensor.
It returns :math:`\theta\ \in\ [-\pi, \pi]`
such that :math:`x = r*\sin(\theta), y = r*\cos(\theta)`, where :math:`r = \sqrt{x^2 + y^2}`.
Args of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
If they have different data types, the lower precision data type will be converted to
the relatively highest precision data type.
Args:
y (Tensor): The input tensor. It has the same shape with `x`.
Returns:
Tensor, the shape is the same as the one after broadcasting,and the data type is same as `x`.
Raises:
TypeError: If `x` or `y` is not a Tensor.
RuntimeError: If the data type of `x` and `y` conversion of Parameter is required
when data type conversion of Parameter is not supported.
Supported Platforms:
``Ascend`` ``CPU`` ``GPU``
Examples:
>>> x = Tensor(np.array([0, 1]), mindspore.float32)
>>> y = Tensor(np.array([1, 1]), mindspore.float32)
>>> output = x.atan2(y)
>>> print(output)
[0. 0.7853982]
"""
self._init_check()
return tensor_operator_registry.get('atan2')(self, y)
def view(self, *shape):
"""
Reshape the tensor according to the input shape. It's the same as :func:`mindspore.Tensor.reshape`,
implemented by the underlying reshape operator.
Args:
shape (Union[tuple(int), int]): Dimension of the output tensor.
Returns:
Tensor, which dimension is the input shape's value.
Examples:
>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([[1, 2, 3], [2, 3, 4]], dtype=np.float32))
>>> output = a.view((3, 2))
>>> print(output)
[[1. 2.]
[3. 2.]
[3. 4.]]
"""
self._init_check()
if not shape:
raise ValueError("The shape variable should not be empty")
if isinstance(shape[0], tuple):
if len(shape) != 1:
raise ValueError(f"Only one tuple is needed, but got {shape}")
shape = shape[0]
return tensor_operator_registry.get('reshape')()(self, shape)
def bitwise_and(self, x):
"""
Returns bitwise `and` of two tensors element-wise.
Refer to :func:`mindspore.ops.bitwise_and` for more detail.
Args:
x (Tensor): The input tensor with int16, int32 or uint16 data type.
Returns:
Tensor, has the same type as the `x`.
Supported Platforms:
``Ascend`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
>>> b = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
>>> output = a.bitwise_and(b)
>>> print(output)
[ 0 0 1 -1 1 0 1]
"""
self._init_check()
return tensor_operator_registry.get('bitwise_and')(self, x)
def bitwise_or(self, x):
"""
Returns bitwise `or` of two tensors element-wise.
Refer to :func:`mindspore.ops.bitwise_or` for more detail.
Args:
x (Tensor): The input tensor with int16, int32 or uint16 data type.
Returns:
Tensor, has the same type as the `x`.
Supported Platforms:
``Ascend`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
>>> b = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
>>> output = a.bitwise_or(b)
>>> print(output)
[ 0 1 1 -1 -1 3 3]
"""
self._init_check()
return tensor_operator_registry.get('bitwise_or')(self, x)
def bitwise_xor(self, x):
"""
Returns bitwise `xor` of two tensors element-wise.
Refer to :func:`mindspore.ops.bitwise_xor` for more detail.
Args:
x (Tensor): The input tensor with int16, int32 or uint16 data type.
Returns:
Tensor, has the same type as the `x`.
Supported Platforms:
``Ascend`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> import numpy as np
>>> a = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
>>> b = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
>>> output = a.bitwise_xor(b)
>>> print(output)
[ 0 1 0 0 -2 3 2]
"""
self._init_check()
return tensor_operator_registry.get('bitwise_xor')(self, x)
def scatter_mul(self, indices, updates):
"""
Creates a new tensor by multiplying the values from the positions in self tensor indicated by
`indices`, with values from `updates`. When divided values are provided for the same
index, the result of the update will be to divided these values respectively. Except that
the updates are applied on output `Tensor` instead of input `Parameter`.
The variable `input_x` refers to self tensor.
The last axis of `indices` is the depth of each index vectors. For each index vector,
there must be a corresponding value in `updates`. The shape of `updates` should be
equal to the shape of `input_x[indices]`. For more details, see use cases.
Note:
- If some values of the `indices` are out of bound, instead of raising an index error,
the corresponding `updates` will not be updated to `input_x`.
Args:
indices (Tensor): The index of input tensor whose data type is int32 or int64. The rank must be at least 2.
updates (Tensor): The tensor to update the input tensor, has the same type as input,
and updates shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:].
Returns:
Tensor, has the same shape and type as self tensor.
Raises:
TypeError: If dtype of `indices` is neither int32 nor int64.
ValueError: If length of shape of self tensor is less than the last dimension of shape of `indices`.
Supported Platforms:
``GPU`` ``CPU``
Examples:
>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32)
>>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32)
>>> # Next, demonstrate the approximate operation process of this operator:
>>> # 1, indices[0] = [0, 0], indices[1] = [0, 0]
>>> # 2, And input_x[0, 0] = -0.1
>>> # 3, So input_x[indices] = [-0.1, -0.1]
>>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2)
>>> # 5, Perform the multiply operation for the first time:
>>> # first_input_x = input_x[0][0] * updates[0] = [[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]
>>> # 6, Perform the multiply operation for the second time:
>>> # second_input_x = input_x[0][0] * updates[1] = [[-0.22, 0.3, 3.6], [0.4, 0.5, -3.2]]
>>> output = input_x.scatter_mul(indices, updates)
>>> print(output)
[[-0.22 0.3 3.6 ]
[ 0.4 0.5 -3.2 ]]
"""
self._init_check()
return tensor_operator_registry.get('tensor_scatter_mul')(self, indices, updates)
def scatter_div(self, indices, updates):
"""
Creates a new tensor by dividing the values from the positions in self tensor indicated by
`indices`, with values from `updates`. When divided values are provided for the same
index, the result of the update will be to divided these values respectively. Except that
the updates are applied on output `Tensor` instead of input `Parameter`.
The last axis of `indices` is the depth of each index vectors. For each index vector,
there must be a corresponding value in `updates`. The shape of `updates` should be
equal to the shape of `input_x[indices]`, the variable `input_x` refers to self tensor.
For more details, see use cases.
Note:
- If some values of the `indices` are out of bound, instead of raising an index error,
the corresponding `updates` will not be updated to `input_x`.
- The operator can't handle division by 0 exceptions, so the user needs to make sure
there is no 0 value in `updates`.
Args:
indices (Tensor): The index of input tensor whose data type is int32 or int64.
The rank must be at least 2.
updates (Tensor): The tensor to update the input tensor, has the same type as input,
and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:].
Returns:
Tensor, has the same shape and type as self tensor.
Raises:
TypeError: If dtype of `indices` is neither int32 nor int64.
ValueError: If length of shape of self tensor is less than the last dimension of shape of `indices`.
Supported Platforms:
``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.0]).astype('float32'))
>>> output = input_x.scatter_div(indices, updates)
>>> print(output)
[[-0.05 0.3 3.6 ]
[ 0.4 0.5 -3.2 ]]
"""
self._init_check()
return tensor_operator_registry.get('tensor_scatter_div')(self, indices, updates)
def ger(self, x):
"""
Ger product of `self` and `x`. Calculate the outer product of two arrays. If `self` is a 1D
Tensor of shape :math:`(m,)` and `x` is a 1D Tensor of shape :math:`(n,)`, then `output` must be a Tensor of
shape :math:`(m, n)`.
Note:
Currently Ascend does not support float64 data input.
Refer to :func:`mindspore.ops.ger` for more detail.
Args:
x (Tensor): input Tensor, with dtype of float16, float32 or float64.
Returns:
Tensor, output matrix with the same dtype as inputs.With `self` shape :math:`(m,)` and
`x` shape of :math:`(n,)`, the `output` has shape :math:`(m, n)`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x1 = Tensor([1., 2., 3., 4.], mindspore.float32)
>>> x2 = Tensor([1., 2., 3.], mindspore.float32)
>>> output = x1.ger(x2)
>>> print(output)
[[ 1. 2. 3.]
[ 2. 4. 6.]
[ 3. 6. 9.]
[ 4. 8. 12.]]
"""
self._init_check()
return tensor_operator_registry.get('ger')(self, x)
def broadcast_to(self, shape):
"""
Broadcasts input tensor to a given shape.
Refer to :func:`mindspore.ops.broadcast_to` for more detail.
Args:
shape (tuple): The target shape to broadcast. Can be fully specified, or have -1 in one position
where it will be substituted by the input tensor's shape in that position, see example.
Returns:
Tensor, with the given `shape` and the same data type as `self`.
Raises:
TypeError: If `shape` is not a tuple.
ValueError: If the target and input shapes are incompatible, or if a - 1
in the target shape is in an invalid location.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> shape = (2, 3)
>>> x = Tensor(np.array([1, 2, 3]).astype(np.float32))
>>> output = x.broadcast_to(shape)
>>> print(output)
[[1. 2. 3.]
[1. 2. 3.]]
>>> shape = (-1, 2)
>>> x = Tensor(np.array([[1], [2]]).astype(np.float32))
>>> output = x.broadcast_to(shape)
>>> print(output)
[[1. 1.]
[2. 2.]]
"""
self._init_check()
return tensor_operator_registry.get('broadcast_to')(shape)(self)
def expand_as(self, x):
"""
Expand the dimension of target tensor to the dimension of input tensor.
Args:
x (Tensor): The input tensor. The shape of the input tensor must obey
the broadcasting rule.
Returns:
Tensor, has the same dimension as input tensor.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor([1, 2, 3], dtype=mstype.float32)
>>> y = Tensor(np.ones((2, 3)), dtype=mstype.float32)
>>> output = x.expand_as(y)
>>> print(output)
[[1. 2. 3.]
[1. 2. 3.]]
"""
self._init_check()
return tensor_operator_registry.get('broadcast_to')(x.shape)(self)
def tan(self):
"""
Computes tangent of `x` element-wise.
.. math::
out_i = tan(x_i)
Returns:
Tensor, has the same shape as self.
Raises:
TypeError: If self is not a Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> a = Tensor([-1.0, 0.0, 1.0]).astype("float32")
>>> output = a.tan()
>>> print(output)
[-1.5574081 0. 1.5574081]
"""
self._init_check()
return tensor_operator_registry.get('tan')()(self)
def cosh(self):
r"""
Computes hyperbolic cosine of `x` element-wise.
.. math::
out_i = \cosh(x_i)
Returns:
Tensor, has the same shape as `x`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> a = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
>>> output = a.cosh()
>>> print(output)
[1.0289385 1.364684 1.048436 1.0040528]
"""
self._init_check()
return tensor_operator_registry.get('cosh')()(self)
def abs(self):
"""
Return absolute value element-wisely.
Returns:
Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> a = Tensor([1.1, -2.1]).astype("float32")
>>> output = a.abs()
>>> print(output)
[1.1 2.1]
"""
self._init_check()
return tensor_operator_registry.get('abs')()(self)
def ceil(self):
"""
Rounds a tensor up to the closest integer element-wise.
Returns:
Tensor.
Raises:
TypeError: If dtype of self tensor is not float16 or float32.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> a = Tensor([1.1, 2.5, -1.5]).astype("float32")
>>> output = a.ceil()
>>> print(output)
[ 2. 3. -1.]
"""
self._init_check()
return tensor_operator_registry.get('ceil')()(self)
def lerp(self, end, weight):
"""
Does a linear interpolation of two tensors start and end based on a float or tensor weight.
If `weight` is a tensor, the shapes of two inputs need to be broadcast;
If `weight` is a float, the shapes of `end` need to be broadcast.
Args:
end (Tensor): The tensor with the ending points. Data type must be float16 or float32.
weight (Union[float, Tensor]): The weight for the interpolation formula. Must be a float
or a scalar tensor with float16 or float32 data type.
Returns:
Tensor, has the same type and shape as self tensor.
Raises:
TypeError: If `end` is not a tensor.
TypeError: If `weight` is neither scalar(float) nor tensor.
TypeError: If dtype of `end` is neither float16 nor float32.
TypeError: If dtype of `weight` is neither float16 nor float32 when it is a tensor.
TypeError: If self tensor and `end` have different data types.
TypeError: If self tensor, `end` and `weight` have different data types when `weight` is a tensor.
ValueError: If `end` could not be broadcast to tensor with shape of self tensor.
ValueError: If `weight` could not be broadcast to tensor with shapes of `end` when it is a tensor.
Supported Platforms:
``Ascend`` ``CPU``
Examples:
>>> start = Tensor(np.array([1., 2., 3., 4.]), mindspore.float32)
>>> end = Tensor(np.array([10., 10., 10., 10.]), mindspore.float32)
>>> output = start.lerp( end, 0.5)
>>> print(output)
[5.5 6. 6.5 7. ]
"""
self._init_check()
return tensor_operator_registry.get('lerp')(self, end, weight)
def norm(self, axis, p=2, keep_dims=False, epsilon=1e-12):
"""
Returns the matrix norm or vector norm of a given tensor.
Args:
axis (Union[int,list,tuple]): Specifies which dimension or dimensions of input to calculate the norm across.
p (int): The order of norm. Default: 2. `p` is greater than or equal to 0.
keep_dims (bool): Whether the output tensors have dim retained or not. Default: False.
epsilon (float): A value added to the denominator for numerical stability. Default: 1e-12.
Returns:
Tensor, has the same dtype as self tensor, which shape depends on the args axis.
For example, if the size of input is (2, 3, 4), axis is [0, 1], Outputs' shape will be (4,).
Raises:
TypeError: If dtype of self tensor is not one of: float16, float32.
TypeError: If `p` is not an int.
TypeError: If `axis` is not an int, a tuple or a list.
TypeError: If `axis` is a tuple or a list, but the element of `axis` is not an int.
TypeError: If `keep_dims` is not a bool.
TypeError: If `epsilon` is not a float.
ValueError: If the element of `axis` is out of the range [-len(input_x.shape), len(input_x.shape)).
input_x refers to self tensor.
ValueError: If the length of shape of `axis` is bigger than the length of shape of self tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> input_x = Tensor(np.array([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]).astype(np.float32))
>>> output = input_x.norm([0, 1], p=2)
>>> print(output)
[ 9.165152 10.954452]
"""
self._init_check()
return tensor_operator_registry.get('norm')(self, axis, p, keep_dims, epsilon)
def renorm(self, p, dim, maxnorm):
"""
Renormalizes the sub-tensors along dimension `dim`, and each sub-tensor's p-norm should not exceed the
'maxnorm'. The values of current sub-tensor don't need change if the p-norm of the sub-tensor is less than
`maxnorm`. Otherwise the sub-tensor needs to be modified to the original value of the corresponding position
divided by the p-norm of the substensor and then multiplied by `maxnorm`.
Args:
p (float): Power of norm calculation.
dim (int): The dimension that expected to get the slice-tensor.
maxnorm (float): Max norm.
Returns:
Tensor, has the same dtype and shape as itself.
Raises:
TypeError: If dtype of `p` is not int.
TypeError: If dtype of `dim` is not int.
TypeError: If dtype of `maxnorm` is not float32.
ValueError: If the value of `p` less than 1.
Supported Platforms:
``Ascend`` ``CPU`` ``GPU``
Examples:
>>> x = Tensor(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), mindspore.float32)
>>> y = x.renorm(p=1, dim=0, maxnorm=5.)
>>> print(y)
[[1. 1. 1. ]
[1.6666666 1.6666666 1.6666666 ]
[1.6666667 1.6666667 1.6666667 ]]
"""
self._init_check()
return tensor_operator_registry.get("renorm")(self, p, dim, maxnorm)
def approximate_equal(self, other, tolerance=1e-5):
r"""
Returns True if abs(x-y) is smaller than tolerance element-wise, otherwise False.
.. math::
out_i = \begin{cases}
& \text{ if } \left | x_{i} - y_{i} \right | < \text{tolerance},\ \ True \\
& \text{ if } \left | x_{i} - y_{i} \right | \ge \text{tolerance},\ \ False
\end{cases}
where `tolerance` indicates Acceptable maximum tolerance.
Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
If they have different data types, the lower precision data type will be converted to
the relatively highest precision data type.
Args:
other (Tensor): Second tensor to compare, with data type belongs to float32, float16.
tolerance (float): The maximum deviation that two elements can be considered equal. Default: 1e-05.
Returns:
Tensor, has the same shape as self tensor, and the data type is bool.
Raises:
TypeError: If `tolerance` is not a float.
RuntimeError: If the data type of `x`, `y` conversion of Parameter is given
but data type conversion of Parameter is not supported.
Supported Platforms:
``Ascend`` ``CPU``
Examples:
>>> from mindspore.common import dtype as mstype
>>> tol = 2.
>>> x = Tensor(np.array([1, 2, 3]), mstype.float32)
>>> y = Tensor(np.array([2, 4, 6]), mstype.float32)
>>> output = Tensor(x).approximate_equal(Tensor(y), tol)
>>> print(output)
[ True False False]
"""
validator.check_isinstance("x", self, Tensor)
validator.check_isinstance("y", other, Tensor)
validator.check_isinstance("tolerance", tolerance, float)
self._init_check()
input_x = self.copy() if self.dtype == mstype.float32 else self.astype(mstype.float16)
input_y = other.copy() if other.dtype == mstype.float32 else other.astype(mstype.float16)
return tensor_operator_registry.get('__lt__')(tensor_operator_registry.get('abs')()(
tensor_operator_registry.get('__sub__')(input_x, input_y)
), tolerance)
def log1p(self):
r"""
Returns the natural logarithm of one plus the input tensor element-wise.
`x` refer to self tensor.
.. math::
out_i = {log_e}(x_i + 1)
Returns:
Tensor, has the same shape as the `x`.
Raises:
TypeError: If `x` is not a Tensor.
TypeError: If dtype of `x` is neither float16 nor float32.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> output = x.log1p()
>>> print(output)
[0.6931472 1.0986123 1.609438 ]
"""
self._init_check()
return tensor_operator_registry.get('log1p')(self)
def isclose(self, x2, rtol=1e-05, atol=1e-08, equal_nan=False):
"""
Returns a boolean Tensor where two Tensors are element-wise equal within a tolerance.
Args:
x2 (Tensor): Second Tensor to compare, with data type belongs to float32, float16, int32.
rtol (float, optional): Relative tolerance. Default: 1e-05.
atol (float, optional): Absolute tolerance. Default: 1e-08.
equal_nan (bool, optional): If True, then two NaNs will be considered equal. Default: False.
Returns:
A bool Tensor, with the shape as broadcasted result of the input Tensor and `x2`.
Raises:
TypeError: If either of self Tensor and `x2` is not Tensor.
TypeError: If either of self Tensor and `x2` is not float16, float32 or int32.
TypeError: If either of `atol` and `rtol` is not float.
TypeError: If `equal_nan` is not bool.
TypeError: If the dtype of self Tensor is not same as the `x2`.
ValueError: If self Tensor and `x2` can not be broadcast.
ValueError: If either of `atol` and `rtol` is less than zero.
Supported Platforms:
``CPU``
Examples:
>>> input = Tensor(np.array([1.3, 2.1, 3.2, 4.1, 5.1]), mindspore.float16)
>>> other = Tensor(np.array([1.3, 3.3, 2.3, 3.1, 5.1]), mindspore.float16)
>>> output = input.isclose(other)
>>> print(output)
[ True False False False True]
"""
self._init_check()
return tensor_operator_registry.get('isclose')(self, x2, rtol, atol, equal_nan)
def isfinite(self):
r"""
Determines which elements are finite for each position.
Returns:
Tensor, has the same shape of input, and the dtype is bool.
Raises:
TypeError: If self Tensor is not Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> a = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
>>> output = a.isfinite()
>>> print(output)
[False True False]
"""
self._init_check()
return tensor_operator_registry.get('isfinite')()(self)
def inv(self):
r"""
Computes Reciprocal of this Tensor element-wise.
.. math::
out_i = \frac{1}{x_{i} }
Returns:
Tensor, has the same type and shape as self Tensor.
Raises:
TypeError: If dtype of this Tensor is not one of float16, float32, int32.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.array([0.25, 0.4, 0.31, 0.52]), mindspore.float32)
>>> output = x.inv()
>>> print(output)
[4. 2.5 3.2258065 1.923077 ]
"""
self._init_check()
return tensor_operator_registry.get('inv')(self)
def invert(self):
r"""
Flips all bits of this Tensor element-wise.
.. math::
out_i = \sim x_{i}
Returns:
Tensor, has the same shape as as self Tensor.
Raises:
TypeError: If dtype of this Tensor is neither int16 nor uint16.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.array([25, 4, 13, 9]), mindspore.int16)
>>> output = x.invert()
>>> print(output)
[-26 -5 -14 -10]
"""
self._init_check()
return tensor_operator_registry.get('invert')(self)
def pow(self, power):
r"""
Calculate the power of Tensor.
.. math::
out_{i} = x_{i} ^{ y_{i}}
Note:
- The current Tensor and `power` comply with the implicit type conversion rules to make the data
types consistent.
- Dtypes of the current Tensor and power cannot be bool at the same time, and the shapes of them
can be broadcast.
Args:
power (Union[Tensor, number.Number, bool]): The power value, should be a number.Number or bool value,
or a Tensor whose data type is number or bool\_.
Returns:
Tensor, the shape is the same as the one after broadcasting,
and the data type is the one with higher precision or higher digits among `Tensor` and `power`.
Raises:
TypeError: If `power` is not one of the following: Tensor, number.Number or bool.
ValueError: If the shape of the current Tensor and `power` are different.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> y = 3.0
>>> output = x.pow(y)
>>> print(output)
[ 1. 8. 64.]
>>>
>>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
>>> y = Tensor(np.array([2.0, 4.0, 3.0]), mindspore.float32)
>>> output = x.pow(y)
>>> print(output)
[ 1. 16. 64.]
"""
self._init_check()
return tensor_operator_registry.get('pow')()(self, power)
def mean(self, axis=(), keep_dims=False):
"""
Reduce a dimension of a tensor by averaging all elements in the dimension.
Args:
axis (Union[None, int, tuple(int), list(int)]): Dimensions of reduction.
When the axis is None or empty tuple, reduce all dimensions. When the axis is int, tuple(int) or
list(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().
keep_dims (bool): Whether to keep the reduced dimensions. Default: False.
Returns:
Tensor, has the same data type as input tensor.
- If `axis` is () and `keep_dims` is False, output a 0-dimensional Tensor representing the average of
all elements in the input Tensor.
- If `axis` is int, takes the value 1, and `keep_dims` is False, the shape of the output
is :math:`(x_0, x_2, ..., x_R)` .
- If `axis` is tuple(int) or list(int), the value is (1, 2), and `keep_dims` is False, the shape of
the output Tensor is: math:`(x_0, x_3, ... , x_R)` .
Raises:
TypeError: If `axis` is not one of the following: int, tuple or list.
TypeError: If `keep_dims` is not a bool.
ValueError: If `axis` is out of range.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.std`: Compute the standard deviation along the specified axis.
:func:`mindspore.Tensor.var`: Compute the variance along the specified axis.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.mean()
>>> print(output)
2.0
"""
self._init_check()
if axis is None:
axis = ()
return tensor_operator_registry.get('mean')(keep_dims)(self, axis)
def amin(self, axis=(), keep_dims=False):
"""
Reduces a dimension of a tensor by the minimum value in the dimension, by default. And also can
reduce a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the
same by controlling `keep_dims`.
Args:
axis (Union[None, int, tuple(int), list(int)]): Dimensions of reduction.
When the axis is None or empty tuple, reduce all dimensions. When the axis is int, tuple(int) or
list(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().
keep_dims (bool): Whether to keep the reduced dimensions. Default: False.
Returns:
Tensor, has the same data type as input tensor.
- If `axis` is () and `keep_dims` is False, output a 0-dimensional Tensor representing the minimum value of
all elements in the input Tensor.
- If `axis` is int, takes the value 1, and `keep_dims` is False, the shape of the output
is :math:`(x_0, x_2, ..., x_R)` .
- If `axis` is tuple(int) or list(int), the value is (1, 2), and `keep_dims` is False, the shape of
the output Tensor is: math:`(x_0, x_3, ... , x_R)` .
Raises:
TypeError: If `axis` is not one of the following: int, tuple or list.
TypeError: If `keep_dims` is not a bool.
ValueError: If `axis` is out of range.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.amin()
>>> print(output)
1.0
"""
self._init_check()
return tensor_operator_registry.get('amin')(self, axis, keep_dims)
def amax(self, axis=(), keep_dims=False):
"""
Reduces a dimension of a tensor by the maximum value in the dimension, by default. And also can
reduce a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the
same by controlling `keep_dims`.
Args:
axis (Union[None, int, tuple(int), list(int)]): Dimensions of reduction.
When the axis is None or empty tuple, reduce all dimensions. When the axis is int, tuple(int) or
list(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().
keep_dims (bool): Whether to keep the reduced dimensions. Default: False.
Returns:
Tensor, has the same data type as input tensor.
- If `axis` is () and `keep_dims` is False, output a 0-dimensional Tensor representing the maximum value of
all elements in the input Tensor.
- If `axis` is int, takes the value 1, and `keep_dims` is False, the shape of the output
is :math:`(x_0, x_2, ..., x_R)` .
- If `axis` is tuple(int) or list(int), the value is (1, 2), and `keep_dims` is False, the shape of
the output Tensor is: math:`(x_0, x_3, ... , x_R)` .
Raises:
TypeError: If `axis` is not one of the following: int, tuple or list.
TypeError: If `keep_dims` is not a bool.
ValueError: If `axis` is out of range.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.amax()
>>> print(output)
3.0
"""
self._init_check()
return tensor_operator_registry.get('amax')(self, axis, keep_dims)
def prod(self, axis=(), keep_dims=False):
"""
Reduces a dimension of a tensor by multiplying all elements in the dimension, by default. And also can
reduce a dimension of `x` along the axis. Determine whether the dimensions of the output and input are
the same by controlling `keep_dims`.
Args:
axis (Union[None, int, tuple(int), list(int)]): Dimensions of reduction.
When the axis is None or empty tuple, reduce all dimensions. When the axis is int, tuple(int) or
list(int), if the dimension of Tensor is dim, the value range is [-dim, dim). Default: ().
keep_dims (bool): Whether to keep the reduced dimensions. Default: False.
Returns:
Tensor, has the same data type as input tensor.
- If `axis` is () and `keep_dims` is False, output a 0-dimensional Tensor representing the product of
all elements in the input Tensor.
- If `axis` is int, takes the value 1, and `keep_dims` is False, the shape of the output
is :math:`(x_0, x_2, ..., x_R)` .
- If `axis` is tuple(int) or list(int), the value is (1, 2), and `keep_dims` is False, the shape of
the output Tensor is: math:`(x_0, x_3, ... , x_R)` .
Raises:
TypeError: If `axis` is not one of the following: int, tuple or list.
TypeError: If `keep_dims` is not a bool.
ValueError: If `axis` is out of range.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
>>> output = input_x.prod()
>>> print(output)
6.0
"""
self._init_check()
return tensor_operator_registry.get('prod')(self, axis, keep_dims)
def select(self, condition, y):
r"""
The conditional tensor determines whether the corresponding element in the output must be
selected from the current Tensor (if true) or :math:`y` (if false) based on the value of each element.
It can be defined as:
.. math::
out_i = \begin{cases}
tensor_i, & \text{if } condition_i \\
y_i, & \text{otherwise}
\end{cases}
Args:
condition (Tensor[bool]): The condition tensor, decides which element is chosen.
The shape is the same as the current Tensor.
y (Union[Tensor, int, float]): If y is Tensor, the shape is the same as the current Tensor.
If y is an int or a float, it will be cast to the type of int32 or float32, and broadcast to the same
shape as the Tensor.
Returns:
Tensor, has the same shape as the current Tensor.
Raises:
TypeError: If `y` is not a Tensor, an int or a float.
ValueError: The shapes of inputs are different.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> # 1) y is Tensor
>>>
>>> cond = Tensor([True, False])
>>> x = Tensor([2,3], mindspore.float32)
>>> y = Tensor([1,2], mindspore.float32)
>>> output = x.select(cond, y)
>>> print(output)
[2. 2.]
>>> # 2) y is a float
>>> cond = Tensor([True, False])
>>> x = Tensor([2,3], mindspore.float32)
>>> y = 2.0
>>> output = x.select(cond, y)
>>> print(output)
[2. 2.]
"""
self._init_check()
if not isinstance(condition, Tensor):
raise TypeError(f"For 'Tensor.select', the argument 'condition' should be Tensor,"
f" but got {type(condition)}.")
if not isinstance(y, (Tensor, int, float)):
raise TypeError(f"For 'Tensor.select', the argument 'y' should be Tensor, int or float,"
f" but got {type(y)}.")
if isinstance(y, int) and self.dtype != mstype.int32:
raise TypeError(f"For 'Tensor.select', if the argument 'y' is int,"
f" then the tensor type should be int32 but got {self.dtype}")
if isinstance(y, float) and self.dtype != mstype.float32:
raise TypeError(f"For 'Tensor.select', if the argument 'y' is float,"
f" then the tensor type should be float32 but got {self.dtype}")
input_y = y
if isinstance(y, (int, float)):
input_y = tensor_operator_registry.get('zeros_like')()(self) + y
if isinstance(y, int):
input_y = tensor_operator_registry.get('cast')(input_y, mstype.int32)
else:
input_y = tensor_operator_registry.get('cast')(input_y, mstype.float32)
return tensor_operator_registry.get('select')(condition, self, input_y)
def transpose(self, *axes):
r"""
Return a tensor with axes transposed.
- For a 1-D tensor, this has no effect, as a transposed vector is simply the same vector.
- For a 2-D tensor, this is a standard matrix transpose.
- For an n-D tensor, if axes are given, their order indicates how the axes are permuted.
If axes are not provided and ``tensor.shape = (i[0], i[1],...i[n-2], i[n-1])``,
then ``tensor.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0])``.
Args:
axes(Union[None, tuple(int), list(int), int], optional): If axes is None or
blank, the method will reverse the order of the axes. If axes is tuple(int)
or list(int), tensor.transpose() will transpose the tensor to the new axes order.
If axes is int, this form is simply intended as a convenience alternative to the
tuple/list form.
Returns:
Tensor, has the same dimension as input tensor, with axes suitably permuted.
Raises:
TypeError: If input arguments have types not specified above.
ValueError: If the number of `axes` is not equal to Tensor's ndim.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,3), dtype=np.float32))
>>> x = x.transpose()
>>> print(x.shape)
(3, 2, 1)
"""
self._init_check()
perm = validator.check_transpose_axis(axes, self.ndim)
return tensor_operator_registry.get('transpose')()(self, perm)
def col2im(self, output_size, kernel_size, dilation, padding_value, stride):
"""
Combines an array of sliding local blocks into a large containing tensor.
Args:
output_size (Tensor): 1D tensor with 2 elements of data type int.
kernel_size (Union[int, tuple[int], list[int]]): The size of the kernel, should be two int
for height and width. If type is int, it means that height equal with width. Must be specified.
dilation (Union[int, tuple[int], list[int]]): The size of the dilation, should be two int
for height and width. If type is int, it means that height equal with width. Default: 1.
padding_value (Union[int, tuple[int], list[int]]): The size of the padding, should be two int
for height and width. If type is int, it means that height equal with width. Default: 1.
stride (Union[int, tuple[int], list[int]]): The size of the stride, should be two int
for height and width. If type is int, it means that height equal with width. Default: 0.
Returns:
A 4D Tensor, with same type as input 'x'.
Raises:
TypeError: If :attr:`kernel_size`, `dilation`, `padding_value`, `stride` data type is not in
Union[int, tuple[int], list[int]].
ValueError: If :attr:`kernel_size`, `dilation`, `stride` value is less than zero or elements
number more than 2.
ValueError: If :attr:`padding_value` value is not greater than zero or elements number more than 2.
Supported Platforms:
``GPU``
Examples:
>>> x = Tensor(input_data=np.random.rand(16, 16, 4, 25), dtype=mstype.float32)
>>> output_size = Tensor(input_data=[8, 8], dtype=mstype.int32)
>>> y = x.col2im(output_size, kernel_size=[2, 2], dilation=[2, 2], padding_value=[2, 2], stride=[2, 2])
>>> print(y.shape)
(16, 16, 8, 8)
"""
self._init_check()
return tensor_operator_registry.get('col2im')(self, output_size, kernel_size, dilation, padding_value, stride)
def reshape(self, *shape):
"""
Give a new shape to a tensor without changing its data.
Args:
shape(Union[int, tuple(int), list(int)]): The new shape should be compatible
with the original shape. If an integer, then the result will be a 1-D
tensor of that length. One shape dimension can be -1. In this case, the
value is inferred from the length of the tensor and remaining dimensions.
Returns:
Tensor, with new specified shape.
Raises:
TypeError: If new shape is not integer, list or tuple.
ValueError: If new shape is not compatible with the original shape.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> from mindspore import dtype as mstype
>>> x = Tensor([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]], dtype=mstype.float32)
>>> output = x.reshape((3, 2))
>>> print(output)
[[-0.1 0.3]
[ 3.6 0.4]
[ 0.5 -3.2]]
"""
self._init_check()
new_shape = validator.check_reshape_shp(shape)
return tensor_operator_registry.get('reshape')()(self, new_shape)
def reverse_sequence(self, seq_lengths, seq_dim, batch_dim=0):
"""
Reverses variable length slices.
Args:
seq_lengths (Tensor): Must be a 1-D vector with int32 or int64 types.
seq_dim (int): The dimension where reversal is performed. Required.
batch_dim (int): The input is sliced in this dimension. Default: 0.
Returns:
Reversed tensor with the same shape and data type as input.
Raises:
TypeError: If `seq_dim` or `batch_dim` is not an int.
ValueError: If value of `batch_dim` is equal to or greater than length of shape of input.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
>>> seq_lengths = Tensor(np.array([1, 2, 3]))
>>> output = x.reverse_sequence(seq_lengths, seq_dim=1)
>>> print(output)
[[1. 2. 3.]
[5. 4. 6.]
[9. 8. 7.]]
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
>>> seq_lengths = Tensor(np.array([1, 2, 3]))
>>> output = x.reverse_sequence(seq_lengths, seq_dim=0, batch_dim=1)
>>> print(output)
[[1. 5. 9.]
[4. 2. 6.]
[7. 8. 3.]]
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
>>> seq_lengths = Tensor(np.array([2, 2, 3]))
>>> output = x.reverse_sequence(seq_lengths, seq_dim=1)
>>> print(output)
[[2. 1. 3.]
[5. 4. 6.]
[9. 8. 7.]]
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
>>> seq_lengths = Tensor(np.array([3, 2, 3]))
>>> output = x.reverse_sequence(seq_lengths, seq_dim=1)
>>> print(output)
[[3. 2. 1.]
[5. 4. 6.]
[9. 8. 7.]]
>>> x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.float32)
>>> seq_lengths = Tensor(np.array([4, 4]))
>>> output = x.reverse_sequence(seq_lengths, seq_dim=1)
>>> print(output)
[[4. 3. 2. 1.]
[8. 7. 6. 5.]]
"""
self._init_check()
return tensor_operator_registry.get('reverse_sequence')(seq_dim, batch_dim)(self, seq_lengths)
def ravel(self):
"""
Return a contiguous flattened tensor.
Returns:
Tensor, a 1-D tensor, containing the same elements of the input.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.reshape`: Give a new shape to a tensor without changing its data.
:func:`mindspore.Tensor.flatten`: Return a copy of the tensor collapsed into one dimension.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.ravel()
>>> print(output.shape)
(24,)
"""
self._init_check()
reshape_op = tensor_operator_registry.get('reshape')()
return reshape_op(self, (-1,))
def round(self):
"""
Returns half to even of the tensor element-wise.
Returns:
Tensor, has the same shape and type as the Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.array([0.8, 1.5, 2.3, 2.5, -4.5]), mindspore.float32)
>>> output = x.round()
>>> print(output)
[ 1. 2. 2. 2. -4.]
"""
self._init_check()
return tensor_operator_registry.get('round')()(self)
def flatten(self, order='C'):
r"""
Return a copy of the tensor collapsed into one dimension.
Args:
order (str, optional): Can choose between 'C' and 'F'. 'C' means to
flatten in row-major (C-style) order. 'F' means to flatten in column-major
(Fortran-style) order. Default: 'C'.
Returns:
Tensor, has the same data type as input.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Raises:
TypeError: If `order` is not string type.
ValueError: If `order` is string type, but not 'C' or 'F'.
See also:
:func:`mindspore.Tensor.reshape`: Give a new shape to a tensor without changing its data.
:func:`mindspore.Tensor.ravel`: Return a contiguous flattened tensor.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.flatten()
>>> print(output.shape)
(24,)
"""
self._init_check()
reshape_op = tensor_operator_registry.get('reshape')()
trans_op = tensor_operator_registry.get('transpose')()
order = validator.check_flatten_order(order)
if order == 'C':
return reshape_op(self, (-1,))
perm = tuple(range(self.ndim - 1, -1, -1))
return reshape_op(trans_op(self, perm), (-1,))
def narrow(self, axis, start, length):
"""
Returns a narrowed tensor from input tensor.
The dimension axis is input from start to start + length.
Args:
axis (int): the axis along which to narrow.
start (int): the starting dimension.
length (int): the distance to the ending dimension.
Returns:
Tensor.
- output (Tensors) - The narrowed tensor.
Raises:
TypeError: axis is not integer.
TypeError: start is not integer.
TypeError: length is not integer.
ValueError: axis is not in the range of [0, ndim-1].
ValueError: start is not in the range of [0, shape[axis]-1].
ValueError: start+length is greater than shape[axis]-1.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore
>>> from mindspore import Tensor
>>> x = Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], mindspore.int32)
>>> output = x.narrow(0, 0, 2)
>>> print(output)
[[ 1 2 3]
[ 4 5 6]]
>>> output = x.narrow(1, 1, 2)
>>> print(output)
[[ 2 3]
[ 5 6]
[ 8 9]]
"""
self._init_check()
return tensor_operator_registry.get('narrow')(self, axis, start, length)
def swapaxes(self, axis1, axis2):
"""
Interchange two axes of a tensor.
Args:
axis1 (int): First axis.
axis2 (int): Second axis.
Returns:
Transposed tensor, has the same data type as the input.
Raises:
TypeError: If `axis1` or `axis2` is not integer.
ValueError: If `axis1` or `axis2` is not in the range of :math:`[-ndim, ndim-1]`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
>>> output = x.swapaxes(0, 2)
>>> print(output.shape)
(4,3,2)
"""
self._init_check()
axis1, axis2 = validator.check_swapaxes_axis((axis1, axis2), self.ndim)
if axis1 == axis2:
return self
if axis1 > axis2:
axis1, axis2 = axis2, axis1
perm = tuple(range(0, self.ndim))
if axis2 + 1 < self.ndim:
new_perm = perm[0:axis1] + perm[axis2:axis2 + 1] + \
perm[axis1 + 1:axis2] + perm[axis1:axis1 + 1] + perm[axis2 + 1:]
else:
new_perm = perm[0:axis1] + perm[axis2:axis2 + 1] + \
perm[axis1 + 1:axis2] + perm[axis1:axis1 + 1]
return tensor_operator_registry.get('transpose')()(self, new_perm)
def squeeze(self, axis=None):
"""
Remove the dimension of shape 1 from the Tensor
Args:
axis (Union[None, int, list(int), tuple(int)], optional): Selects a subset of the entries of
length one in the shape. If an axis is selected with shape entry greater than one,
an error is raised. Default is None.
Returns:
Tensor, with all or a subset of the dimensions of length 1 removed.
Raises:
TypeError: If input arguments have types not specified above.
ValueError: If axis is greater than one.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.expand_as`: Expand the dimension of target tensor to the dimension of input tensor.
:func:`mindspore.Tensor.reshape`: Give a new shape to a tensor without changing its data.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,2), dtype=np.float32))
>>> print(x)
[[[1. 1.]
[1. 1.]]]
>>> print(x.shape)
(1, 2, 2)
>>> y = x.squeeze()
>>> print(y)
[[1. 1.]
[1. 1.]]
>>> print(y.shape)
(2, 2)
>>> y = x.squeeze(axis=0)
>>> print(y)
[[1. 1.]
[1. 1.]]
>>> print(y.shape)
(2, 2)
"""
self._init_check()
if axis is None:
return tensor_operator_registry.get('squeeze')(self)
new_shape = validator.prepare_shape_for_squeeze(self.shape, axis)
return tensor_operator_registry.get('reshape')()(self, new_shape)
def expand_dims(self, axis):
"""
Insert a dimension of shape 1 at the specified axis of Tensor
Args:
axis (int): the axis at which to insert the singleton dimension.
Returns:
Tensor, with inserted dimension of length 1.
Raises:
TypeError: If axis is not an int.
ValueError: If axis is not in range [-self.ndim - 1, self.ndim + 1).
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((2,2), dtype=np.float32))
>>> print(x)
[[1. 1.]
[1. 1.]]
>>> print(x.shape)
(2, 2)
>>> y = x.expand_dims(axis=0)
>>> print(y)
[[[1. 1.]
[1. 1.]]]
>>> print(y.shape)
(1, 2, 2)
"""
self._init_check()
validator.check_is_int(axis, 'axis')
validator.check_int_range(axis, -self.ndim - 1, self.ndim + 1, Rel.INC_LEFT, 'axis')
return tensor_operator_registry.get('expand_dims')(self, axis)
def astype(self, dtype, copy=True):
"""
Return a copy of the tensor, cast to a specified type.
Args:
dtype (Union[:class:`mindspore.dtype`, numpy.dtype, str]): Designated tensor dtype, can be in
format of :class:`mindspore.dtype.float32` or :class:`numpy.float32` or `float32`.
copy (bool, optional): By default, astype always returns a newly allocated
tensor. If this is set to false, the input tensor is returned instead
of a copy. Default: True.
Returns:
Tensor, with the designated dtype.
Raises:
TypeError: If the specified dtype cannot be understood.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.ones((1,2,2,1), dtype=np.float32))
>>> x = x.astype("int32")
>>> print(x.dtype)
Int32
"""
self._init_check()
dtype = validator.check_astype_dtype(dtype)
if not copy and dtype == self.dtype:
return self
return tensor_operator_registry.get('cast')(self, dtype)
def argmax(self, axis=None):
"""
Return the indices of the maximum values along an axis.
Args:
axis (int, optional): By default, the index is into
the flattened tensor, otherwise along the specified axis. Default: None.
Returns:
Tensor, indices into the input tensor. It has the same
shape as self.shape with the dimension along axis removed.
Raises:
ValueError: If the axis is out of range.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.argmin`: Return the indices of the minimum values along an axis.
:func:`mindspore.Tensor.min`: Return the minimum of a tensor or minimum along an axis.
:func:`mindspore.Tensor.max`: Return the maximum of a tensor or maximum along an axis.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
>>> print(a.argmax())
5
"""
# P.Argmax only supports float
a = self.astype(mstype.float32)
if axis is None:
a = a.ravel()
axis = 0
else:
axis = validator.check_axis_in_range(axis, a.ndim)
return tensor_operator_registry.get('argmax')(axis)(a)
def argmin(self, axis=None):
"""
Return the indices of the minimum values along an axis.
Args:
axis (int, optional): By default, the index is into
the flattened tensor, otherwise along the specified axis. Default: None.
Returns:
Tensor, indices into the input tensor. It has the same
shape as self.shape with the dimension along axis removed.
Raises:
ValueError: If the axis is out of range.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.argmax`: Return the indices of the maximum values along an axis.
:func:`mindspore.Tensor.min`: Return the minimum of a tensor or minimum along an axis.
:func:`mindspore.Tensor.max`: Return the maximum of a tensor or maximum along an axis.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
>>> print(a.argmin())
0
"""
# P.Argmin only supports float
a = self.astype(mstype.float32)
if axis is None:
a = a.ravel()
axis = 0
else:
axis = validator.check_axis_in_range(axis, a.ndim)
# P.Argmin is currently not supported
return tensor_operator_registry.get('argmax')(axis)(tensor_operator_registry.get('__neg__')(a))
def argmin_with_value(self, axis=0, keep_dims=False):
"""
Returns the minimum value with corresponding index.
Note:
In auto_parallel and semi_auto_parallel mode, the first output index can not be used.
.. warning::
- If there are multiple minimum values, the index of the first minimum value is used.
- The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of this tensor.
Args:
axis (int): The dimension to reduce. Default: 0.
keep_dims (bool): Whether to reduce dimension, if true the output will keep the same dimension as the input,
the output will reduce dimension if false. Default: False.
Outputs:
tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the minimum value of the input
tensor.
- **index** (Tensor) - The index for the minimum value of the input tensor.
If `keep_dims` is true, the shape of
output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is
:math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)` .
- **value** (Tensor) - The minimum value of input tensor, with the same shape as index.
Raises:
TypeError: If `keep_dims` is not a bool.
TypeError: If `axis` is not an int.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32)
>>> index, output = x.argmin_with_value()
>>> print(index, output)
0 0.0
>>> index, output = x.argmin_with_value(keep_dims=True)
>>> print(index, output)
[0] [0.0]
"""
self._init_check()
return tensor_operator_registry.get('argmin_with_value')(self, axis, keep_dims)
def cumsum(self, axis=None, dtype=None):
"""
Return the cumulative sum of the elements along a given axis.
Note:
If ``self.dtype`` is :class:`int8`, :class:`int16` or :class:`bool`, the result
`dtype` will be elevated to :class:`int32`, :class:`int64` is not supported.
Args:
axis (int, optional): Axis along which the cumulative sum is computed. The
default (None) is to compute the cumsum over the flattened array.
dtype (:class:`mindspore.dtype`, optional): If not specified, stay the same as original
tensor, unless it has an integer dtype with a precision less than :class:`float32`.
In that case, :class:`float32` is used. Default: None.
Raises:
ValueError: If the axis is out of range.
Returns:
Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.sum`: Return sum of tensor elements over a given axis.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.ones((3,3)).astype("float32"))
>>> output = a.cumsum(axis=0)
>>> print(output)
[[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]]
"""
x = self
original_dtype = x.dtype
# If original tensor is int, and has precision less then int32, convert to int32
if x.dtype in (mstype.bool_, mstype.int8, mstype.int16, mstype.uint8, mstype.int16):
x = x.astype(mstype.int32)
if axis is None:
x = x.ravel()
axis = 0
validator.check_axis_in_range(axis, x.ndim)
if dtype is not None and original_dtype != dtype:
return tensor_operator_registry.get('cumsum')()(x, axis).astype(dtype, copy=False)
return tensor_operator_registry.get('cumsum')()(x, axis)
def cummin(self, axis):
r"""
Returns a tuple (values,indices) where 'values' is the cumulative minimum value of self Tensor
along the dimension `axis`, and `indices` is the index location of each minimum value.
.. math::
\begin{array}{ll} \\
y{i} = min(x{1}, x{2}, ... , x{i})
\end{array}
Args:
axis (int): The dimension to do the operation over. The value of `axis` must be in the range
`[-x.ndim, x.ndim - 1]`.
Returns:
tuple [Tensor], tuple of 2 Tensors, containing the cumulative minimum of elements and the index,
The shape of each output tensor is the same as self Tensor.
Raises:
TypeError: If `axis` is not an int.
ValueError: If `axis` is out the range of `[-x.ndim, x.ndim - 1]`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor, ops
>>> import mindspore
>>> a = Tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220], mindspore.float32)
>>> output = a.cummin(axis=0)
>>> print(output[0])
[-0.2284 -0.6628 -0.6628 -0.6628 -1.3298 -1.3298]
>>> print(output[1])
[0 1 1 1 4 4]
"""
return tensor_operator_registry.get('cummin')(self, axis)
def cummax(self, axis):
r"""
Returns a tuple (values,indices) where 'values' is the cumulative maximum value of self Tensor
along the dimension `axis`, and `indices` is the index location of each maximum value.
.. math::
\begin{array}{ll} \\
y{i} = max(x{1}, x{2}, ... , x{i})
\end{array}
Args:
axis (int): The dimension to do the operation over. The value of `axis` must be in the range
`[-x.ndim, x.ndim - 1]`.
Returns:
tuple [Tensor], tuple of 2 Tensors, containing the cumulative maximum of elements and the index,
The shape of each output tensor is the same as self Tensor.
Raises:
TypeError: If `axis` is not an int.
ValueError: If `axis` is out the range of `[-x.ndim, x.ndim - 1]`.
Supported Platforms:
``GPU`` ``CPU``
Examples:
>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor
>>> import mindspore.ops as ops
>>> x = Tensor(np.array([[3, 4, 6, 10], [1, 6, 7, 9], [4, 3, 8, 7], [1, 3, 7, 9]]).astype(np.float32))
>>> output = x.cummax(axis=0)
>>> print(output[0])
[[ 3. 4. 6. 10.]
[ 3. 6. 7. 10.]
[ 4. 6. 8. 10.]
[ 4. 6. 8. 10.]]
>>> print(output[1])
[[0 0 0 0]
[0 1 1 0]
[2 1 2 0]
[2 1 2 0]]
"""
return tensor_operator_registry.get('cummax')(self, axis)
def index_fill(self, dim, index, value):
"""
Fills the elements under the `dim` dimension of the self Tensor with the input `value`
by selecting the indices in the order given in `index`.
Args:
dim (Union[int, Tensor]): Dimension along which to fill the input Tensor. Only supports
an int number or a 0-dimensional Tensor, whose data type is int32 or int64.
index (Tensor): Indices of the input Tensor to fill in. The dtype must be int32.
value (Union[bool, int, float, Tensor]): Value to fill the returned Tensor. If `value` is
a Tensor, it must be a 0-dimensional Tensor and has the same dtype as self Tensor. Otherwise,
the `value` will be cast to a 0-dimensional Tensor with the same data type as self Tensor.
Outputs:
Tensor, has the same dtype and shape as self Tensor.
Raises:
TypeError: If `dim` is neither int number nor Tensor.
TypeError: When `dim` is a Tensor and its dtype is not int32 or int64.
TypeError: If `index` is not a Tensor.
TypeError: If dtype of `index` is not int32.
TypeError: If `value` is not a bool, int, float, or Tensor.
TypeError: If dtype of self Tensor and `value` are not the same.
ValueError: When `dim` is a Tensor and its rank is not equal to 0.
ValueError: If the rank of `index` is greater than 1D.
ValueError: When `value` is a Tensor and its rank is not equal to 0.
RuntimeError: If the value of `dim` is out the range of `[-self.ndim, self.ndim - 1]`.
RuntimeError: If the values of `index` are out the range of `[-self.shape[dim], self.shape[dim] - 1]`.
Supported Platforms:
``GPU``
Examples:
>>> import mindspore
>>> import mindspore.ops as ops
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).astype(np.float32))
>>> index = Tensor([0, 2], mindspore.int32)
>>> value = Tensor(-2.0, mindspore.float32)
>>> y = x.index_fill(1, index, value)
>>> print(y)
[[-2. 2. -2.]
[-2. 5. -2.]
[-2. 8. -2.]]
"""
return tensor_operator_registry.get('index_fill')(self, dim, index, value)
def inplace_update(self, v, indices):
"""
Update some rows of a tensor with values of v according to the specified indices.
Note:
`indices` refers to the left-most dimension.
Args:
v (Tensor): A tensor with the same type and same dimension size except the first dimension, which must be
the same as the size of indices.
indices (Union[int, tuple]): Indices into the left-most dimension determining which rows to be updated.
Returns:
Tensor, with updated values.
Raises:
TypeError: if indices is not int or tuple.
TypeError: if indices is tuple but any of its element is not int.
ValueError: the Tensor shape is different from that of v.
Supported Platforms:
``Ascend`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> import mindspore
>>> x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
>>> v = Tensor(np.array([[0.1, 0.2], [0.3, 0.4]]), mindspore.float32)
>>> indices = (0, 1)
>>> output = x.inplace_update(v, indices)
>>> print(output)
[[0.1 0.2]
[0.3 0.4]
[5. 6. ]]
"""
self._init_check()
return tensor_operator_registry.get('inplace_update')(indices)(self, v)
def copy(self):
"""
Return a copy of the tensor.
Note:
The current implementation does not support `order` argument.
Returns:
Copied tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.ones((3,3)).astype("float32"))
>>> output = a.copy()
>>> print(output)
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
"""
if self.size == 0:
return self
origin_dtype = self.dtype
x = self
logical_not_op = tensor_operator_registry.get('logical_not')()
if origin_dtype == mstype.bool_:
return logical_not_op(logical_not_op(x))
if origin_dtype != mstype.float64:
x = x.astype("float32")
x = x / 1.0
x = x.astype(origin_dtype)
return x
def max(self, axis=None, keepdims=False, initial=None, where=True):
"""
Return the maximum of a tensor or maximum along an axis.
Args:
axis (Union[None, int, list, tuple of ints], optional): Axis or
axes along which to operate. By default, flattened input is used. If
this is a tuple of ints, the maximum is selected over multiple axes,
instead of a single axis or all the axes as before. Default: None.
keepdims (bool, optional):
If this is set to True, the axes which are reduced are left in the
result as dimensions with size one. With this option, the result will
broadcast correctly against the input array. Default: False.
initial (scalar, optional):
The minimum value of an output element. Must be present to allow
computation on empty slice. Default: None.
where (bool Tensor, optional):
A boolean tensor which is broadcasted to match the dimensions of array,
and selects elements to include in the reduction. If non-default value
is passed, initial must also be provided. Default: True.
Returns:
Tensor or scalar, maximum of input tensor. If `axis` is None, the result is a scalar
value. If `axis` is given, the result is a tensor of dimension ``self.ndim - 1``.
Raises:
TypeError: If arguments have types not specified above.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.argmin`: Return the indices of the minimum values along an axis.
:func:`mindspore.Tensor.argmax`: Return the indices of the maximum values along an axis.
:func:`mindspore.Tensor.min`: Return the minimum of a tensor or minimum along an axis.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape((2, 2)).astype('float32'))
>>> output = a.max()
>>> print(output)
3.0
"""
reduce_ = tensor_operator_registry.get("reduce")
reduce_max = tensor_operator_registry.get("reduce_max")
maximum = tensor_operator_registry.get("maximum")
return reduce_(self, reduce_max(keepdims), cmp_fn=maximum(), axis=axis, keepdims=keepdims,
initial=initial, where=where)
def min(self, axis=None, keepdims=False, initial=None, where=True):
"""
Return the minimum of a tensor or minimum along an axis.
Args:
axis (Union[None, int, list, tuple of ints], optional): Axis or
axes along which to operate. By default, flattened input is used. If
this is a tuple of ints, the minimum is selected over multiple axes,
instead of a single axis or all the axes as before. Default: None.
keepdims (bool, optional):
If this is set to True, the axes which are reduced are left in the
result as dimensions with size one. With this option, the result will
broadcast correctly against the input tensor. Default: False.
initial (scalar, optional):
The maximum value of an output element. Must be present to allow
computation on empty slice. Default: None.
where (bool Tensor, optional):
A boolean tensor which is broadcasted to match the dimensions of tensor,
and selects elements to include in the reduction. If non-default value
is passed, initial must also be provided. Default: True.
Returns:
Tensor or scalar, minimum of input tensor. If the axis is None, the result is a scalar
value. If `axis` is given, the result is a tensor of dimension ``self.ndim - 1``.
Raises:
TypeError: If arguments have types not specified above.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.argmin`: Return the indices of the minimum values along an axis.
:func:`mindspore.Tensor.argmax`: Return the indices of the maximum values along an axis.
:func:`mindspore.Tensor.max`: Return the maximum of a tensor or maximum along an axis.
Examples:
>>> from mindspore import Tensor
>>> import mindspore.numpy as np
>>> a = Tensor(np.arange(4).reshape((2,2)).astype('float32'))
>>> output = a.min()
>>> print(output)
0.0
"""
reduce_ = tensor_operator_registry.get("reduce")
reduce_min = tensor_operator_registry.get("reduce_min")
minimum = tensor_operator_registry.get("minimum")
return reduce_(self, reduce_min(keepdims), cmp_fn=minimum(), axis=axis, keepdims=keepdims,
initial=initial, where=where)
def scatter_add(self, indices, updates):
"""
Creates a new tensor by adding the values from the positions in self tensor indicated by
`indices`, with values from `updates`. When multiple values are given for the same
index, the updated result will be the sum of all values. This operation is almost
equivalent to using ScatterNdAdd, except that the updates are applied on output `Tensor`
instead of input `Parameter`.
The last axis of `indices` is the depth of each index vectors. For each index vector,
there must be a corresponding value in `updates`. The shape of `updates` should be
equal to the shape of `self[indices]`. For more details, see use cases.
Note:
On GPU, if some values of the `indices` are out of bound, instead of raising an index error,
the corresponding `updates` will not be updated to self tensor. On CPU, if some values of
the `indices` are out of bound, raising an index error. On Ascend, out of bound checking is
not supported, if some values of the `indices` are out of bound, unknown errors may be caused.
Args:
indices (Tensor): The index of input tensor whose data type is int32 or int64.
The rank must be at least 2.
updates (Tensor): The tensor to update the input tensor, has the same type as self tensor,
and updates. Shape should be equal to indices.shape[:-1] + self.shape[indices.shape[-1]:].
Returns:
Tensor, has the same shape and type as self tensor.
Raises:
TypeError: If dtype of `indices` is neither int32 nor int64.
ValueError: If length of shape of self tensor is less than the last dimension of shape of `indices`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.2]).astype('float32'))
>>> output = x.scatter_add(indices, updates)
>>> print(output)
[[ 3.1 0.3 3.6]
[ 0.4 0.5 -3.2]]
"""
self._init_check()
return tensor_operator_registry.get("tensor_scatter_add")()(self, indices, updates)
def scatter_sub(self, indices, updates):
"""
Creates a new tensor by subtracting the values from the positions in self tensor indicated by
`indices`, with values from `updates`. When multiple values are provided for the same
index, the result of the update will be to subtract these values respectively. This operation is almost
equivalent to using :class:`mindspore.ops.ScatterNdSub` , except that the updates are applied on output `Tensor`
instead of input `Parameter`.
The last axis of `indices` is the depth of each index vectors. For each index vector,
there must be a corresponding value in `updates`. The shape of `updates` should be
equal to the shape of `self[indices]`. For more details, see use cases.
Note:
On GPU, if some values of the `indices` are out of bound, instead of raising an index error,
the corresponding `updates` will not be updated to self tensor. On CPU, if some values of
the `indices` are out of bound, raising an index error. On Ascend, out of bound checking is
not supported, if some values of the `indices` are out of bound, unknown errors may be caused.
Args:
indices (Tensor): The index of input tensor whose data type is int32 or int64.
The rank must be at least 2.
updates (Tensor): The tensor to update the input tensor, has the same type as input,
and updates.shape should be equal to indices.shape[:-1] + self.shape[indices.shape[-1]:].
Returns:
Tensor, has the same shape and type as self tensor.
Raises:
TypeError: If dtype of `indices` is neither int32 nor int64.
ValueError: If length of shape of self tensor is less than the last dimension of shape of `indices`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.2]).astype('float32'))
>>> output = x.scatter_sub(indices, updates)
>>> print(output)
[[-3.3000002 0.3 3.6 ]
[ 0.4 0.5 -3.2 ]]
"""
self._init_check()
return tensor_operator_registry.get('tensor_scatter_sub')()(self, indices, updates)
def scatter_min(self, indices, updates):
"""
By comparing the value at the position indicated by `indices` in self tensor with the value in the `updates`,
the value at the index will eventually be equal to the smallest one to create a new tensor.
The last axis of the index is the depth of each index vector. For each index vector,
there must be a corresponding value in `updates`. The shape of `updates` should be
equal to the shape of `input_x[indices]`. For more details, see case below.
Note:
If some values of the `indices` are out of range, instead of raising an index error,
the corresponding `updates` will not be updated to `input_x`.
Args:
indices (Tensor): The index of input tensor whose data type is int32 or int64.
The rank must be at least 2.
updates (Tensor): The tensor to update the input tensor, has the same type as input,
and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:].
Returns:
Tensor, has the same shape and type as `input_x`.
Raises:
TypeError: If dtype of `indices` is neither int32 nor int64.
ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`.
Supported Platforms:
``GPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]).astype('float32'))
>>> indices = Tensor(np.array([[0, 0], [0, 0]]).astype('int32'))
>>> updates = Tensor(np.array([1.0, 2.2]).astype('float32'))
>>> output = x.scatter_min(indices, updates)
>>> print(output)
[[ -0.1 0.3 3.6]
[ 0.4 0.5 -3.2]]
"""
self._init_check()
return tensor_operator_registry.get('tensor_scatter_min')()(self, indices, updates)
def scatter_max(self, indices, updates):
"""
By comparing the value at the position indicated by `indices` in `x` with the value in the `updates`,
the value at the index will eventually be equal to the largest one to create a new tensor.
The last axis of the index is the depth of each index vector. For each index vector,
there must be a corresponding value in `updates`. The shape of `updates` should be
equal to the shape of `input_x[indices]`. For more details, see case below.
Note:
If some values of the `indices` are out of bound, instead of raising an index error,
the corresponding `updates` will not be updated to `input_x`.
Args:
indices (Tensor): The index of input tensor whose data type is int32 or int64.
The rank must be at least 2.
updates (Tensor): The tensor to update the input tensor, has the same type as input,
and updates.shape should be equal to indices.shape[:-1] + input_x.shape[indices.shape[-1]:].
Returns:
Tensor, has the same shape and type as `input_x`.
Raises:
TypeError: If dtype of `indices` is neither int32 nor int64.
ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`.
Supported Platforms:
``GPU``
Examples:
>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 0], [0, 0]]), mindspore.int32)
>>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32)
>>> # Next, demonstrate the approximate operation process of this operator:
>>> # 1, indices[0] = [0, 0], indices[1] = [0, 0]
>>> # 2, And input_x[0, 0] = -0.1
>>> # 3, So input_x[indices] = [-0.1, -0.1]
>>> # 4, Satisfy the above formula: input_x[indices].shape=(2) == updates.shape=(2)
>>> op = ops.TensorScatterMax()
>>> # 5, Perform the max operation for the first time:
>>> # first_input_x = Max(input_x[0][0], updates[0]) = [[1.0, 0.3, 3.6], [0.4, 0.5, -3.2]]
>>> # 6, Perform the max operation for the second time:
>>> # second_input_x = Max(input_x[0][0], updates[1]) = [[2.2, 0.3, 3.6], [0.4, 0.5, -3.2]]
>>> output = op(input_x, indices, updates)
>>> print(output)
[[ 2.2 0.3 3.6]
[ 0.4 0.5 -3.2]]
"""
self._init_check()
return tensor_operator_registry.get('tensor_scatter_max')()(self, indices, updates)
def fill(self, value):
"""
Fill the tensor with a scalar value.
Note:
Unlike Numpy, tensor.fill() will always return a new tensor, instead of
filling the original tensor.
Args:
value (Union[None, int, float, bool]): All elements of a will be assigned this value.
Returns:
Tensor, with the original dtype and shape.
Raises:
TypeError: If input arguments have types not specified above.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape((2,2)).astype('float32'))
>>> print(a.fill(1.0))
[[1. 1.]
[1. 1.]]
"""
if value is None:
if self.dtype not in (mstype.float16, mstype.float32, mstype.float64):
raise TypeError("For 'Tensor.fill', if the argument 'value' is None, the type of the original "
"tensor must be float, but got {}.".format(self.dtype))
value = Tensor(float('nan')).astype("float32")
return tensor_operator_registry.get("tile")()(value, self.shape).astype(self.dtype)
if not isinstance(value, (int, float, bool)):
raise TypeError("For 'Tensor.fill', the type of the argument 'value' must be int, float or bool, "
"but got {}.".format(type(value)))
return tensor_operator_registry.get("fill")(self.dtype, self.shape, value)
def fills(self, value):
"""
Create a tensor of the same shape and type as the input tensor and fill it with specified value.
Note:
Unlike Numpy, tensor.fills() will always returns a new tensor, instead of
filling the original tensor.
Args:
value (Union[int, float, Tensor]): All elements of the output tensor will be assigned this value. The
type should be int, float or 0-dimensional tensor.
Returns:
Tensor, with the same shape and type as input tensor.
Raises:
TypeError: If `value` has types not specified above.
RuntimeError: If `value` cannot be converted to the same type as `x`.
ValueError: If `value` is a tensor and the length of dimension is not 0.
Supported Platforms:
``GPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.arange(4).reshape((2, 2)).astype('float32'))
>>> print(x.fills(1.0))
[[1. 1.]
[1. 1.]]
"""
self._init_check()
return tensor_operator_registry.get('fills')(self, value)
def masked_fill(self, mask, value):
"""
Fills elements of self tensor with value where mask is True.
The shapes of self tensor and `mask` need to be the same or broadcastable.
Args:
mask (Tensor[bool]): The boolean mask.
value (Union[float, Tensor]): The value to fill in with, which dtype is the same as self.
Returns:
Tensor, has the same type and shape as self.
Raises:
TypeError: If `mask` is not a Tensor.
TypeError: If dtype of `mask` is not bool.
ValueError: If the shapes of self tensor and `mask` could not be broadcast.
TypeError: If dtype of self tensor or `value` is not one of float16, float32, int8, int32.
TypeError: If dtype of `value` is different from that of self.
TypeError: If `value` is neither float number nor Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4)).astype('float32')
>>> print(a)
[0. 1. 2. 3.]
>>> mask = Tensor([False, False, True, True])
>>> print(a.masked_fill(mask, 0.0))
[0. 1. 0. 0.]
"""
self._init_check()
if isinstance(value, (float, int)):
value = tensor_operator_registry.get("scalar_to_tensor")(value, self.dtype)
if not isinstance(mask, Tensor):
raise TypeError("For 'Tensor.masked_fill', the type of the argument 'mask' must be Tensor, but "
"got {}.".format(type(mask)))
validator.check_type_name('mask', mask.dtype, [mstype.bool_], "Tensor")
return tensor_operator_registry.get("masked_fill")(self, mask, value)
def ptp(self, axis=None, keepdims=False):
"""
The name of the function comes from the acronym for "peak to peak". Calculate the difference between the
maximum value and the minimum value along the axis.
Note:
Numpy argument `out` is not supported.
Args:
axis (Union[None, int, tuple(int)]): Axis or axes along which the range is computed.
The default is to compute the variance of the flattened tensor. Default: None.
keepdims (bool): If this is set to True, the axes which are reduced are left in the result as
dimensions with size one. With this option, the result will broadcast correctly against the tensor.
Default is False.
Returns:
Tensor.
Raises:
TypeError: If `self` is not a tensor, or `axis` and `keepdims` have types not specified above.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> x = Tensor([[4.0, 9.0, 2.0, 10.0], [6.0, 9.0, 7.0, 12.0]]).astype("float32")
>>> print(x.ptp(axis=1))
[8. 6.]
>>> print(x.ptp(axis=0))
[2. 0. 5. 2.]
"""
if not isinstance(keepdims, bool):
raise TypeError("For 'Tensor.ptp', the type of the argument 'keepdims' must be bool, "
"but got {}.".format(type(keepdims)))
if axis is None:
axis = ()
else:
validator.check_axis_type(axis, True, True, False)
axis = validator.check_axis_valid(axis, self.ndim)
return self.max(axis, keepdims) - self.min(axis, keepdims)
def clip(self, xmin, xmax, dtype=None):
"""
Clips (limits) the values in a Tensor.
Given an interval, values outside the interval are clipped to the interval edges.
For example, if an interval of :math:`[0, 1]` is specified, values smaller than 0 become 0,
and values larger than 1 become 1.
Note:
Currently, clip with `xmin=nan` or `xmax=nan` is not supported.
Args:
xmin (Tensor, scalar, None): Minimum value. If None, clipping is not performed
on the lower interval edge. Not more than one of `xmin` and `xmax` may be None.
xmax (Tensor, scalar, None): Maximum value. If None, clipping is not performed
on the upper interval edge. Not more than one of `xmin` and `xmax` may be None.
If `xmin` or `xmax` are tensors, then `xmin`, `xmax` and the given tensor
will be broadcasted to match their shapes.
dtype (:class:`mindspore.dtype`, optional): Overrides the dtype of the
output Tensor. Default is None.
Returns:
Tensor, a tensor with the elements of the input tensor, but where values
< `xmin` are replaced with `xmin`, and those > `xmax` with `xmax`.
Raises:
TypeError: If inputs have types not specified above.
ValueError: If the shapes of `x1` and `x2` cannot broadcast, or both `xmin` and `xmax` are `None`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> from mindspore import Tensor
>>> x = Tensor([1, 2, 3, -4, 0, 3, 2, 0]).astype("float32")
>>> y = x.clip(0, 2)
>>> print(y)
[1. 2. 2. 0. 0. 2. 2. 0.]
>>> t = Tensor([1, 1, 1, 1, 1, 1, 1, 1])
>>> y = x.clip(t, 2)
>>> print(y)
[1. 2. 2. 1. 1. 2. 2. 1.]
"""
if xmin is None and xmax is None:
raise ValueError("For 'Tensor.clip', the argument 'xmin' and 'xman' cannot all be None.")
x = self
# F.maximum/minimum does not support when both operands are scalar
if xmin is not None:
xmin = Tensor(xmin).astype(x.dtype)
if x.ndim == 0 and xmin.ndim == 0:
x = tensor_operator_registry.get("maximum")()(x.reshape((1,)), xmin).squeeze()
else:
x = tensor_operator_registry.get("maximum")()(x, xmin)
if xmax is not None:
xmax = Tensor(xmax).astype(x.dtype)
if x.ndim == 0 and xmax.ndim == 0:
x = tensor_operator_registry.get("minimum")()(x.reshape((1,)), xmax).squeeze()
else:
x = tensor_operator_registry.get("minimum")()(x, xmax)
if dtype is not None and dtype != x.dtype:
return x.astype(dtype)
return x
def _init_check(self):
if self.has_init:
self.init_data()
return self
def init_data(self, slice_index=None, shape=None, opt_shard_group=None):
"""
Get the tensor format data of this Tensor.
Note:
The init_data function can be called once for the same tensor.
Args:
slice_index (int): Slice index of a parameter's slices.
It is used when initialize a slice of a parameter, it guarantees that devices
using the same slice can generate the same tensor. Default: None.
shape (list[int]): Shape of the slice, it is used when initialize a slice of the parameter. Default: None.
opt_shard_group(str): Optimizer shard group which is used in auto or semi auto parallel mode
to get one shard of a parameter's slice. Default: None.
Returns:
Initialized Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore as ms
>>> from mindspore.common.initializer import initializer, Constant
>>> x = initializer(Constant(1), [2, 2], ms.float32)
>>> out = x.init_data()
>>> print(out)
[[1. 1.]
[1. 1.]]
"""
if self.init is None:
raise TypeError("init_data must be set Tensor.init, init can't be None")
if shape is None:
shape = self.shape
try:
data = np.ndarray(shape, dtype=mstype.dtype_to_nptype(self.dtype))
except ValueError:
msg = "Error shape={}".format(shape)
logger.critical(msg)
raise ValueError(msg)
class seed_context:
"""Set and restore seed."""
def __init__(self, init):
self.init = init
from .seed import get_seed
global_seed = get_seed()
self._np_seed = np.random.get_state()[1][0]
self.need_set_seed = (slice_index is not None)
self._global_seed = global_seed
self._device_num = 1
if self.need_set_seed:
self._device_num = get_group_size()
def __enter__(self):
if self.need_set_seed:
self.seed = self.init.seed
if self._global_seed is not None:
np.random.seed(slice_index + self._global_seed)
self.init.seed = slice_index + self._global_seed
else:
np.random.seed(slice_index + Tensor.delta_seed)
self.init.seed = slice_index + Tensor.delta_seed
Tensor.delta_seed += self._device_num
def __exit__(self, ptype, value, trace):
if self.need_set_seed:
np.random.seed(self._np_seed)
self.init.seed, _ = self.seed
with seed_context(self.init):
self.init(data)
if opt_shard_group:
rank = get_rank(opt_shard_group)
size = get_group_size(opt_shard_group)
data = np.split(data, size)[rank]
self.init = None
self.assign_value(Tensor_.from_numpy(data))
return self
def to_tensor(self, slice_index=None, shape=None, opt_shard_group=None):
"""
Return init_data() and get the tensor format data of this Tensor.
Note:
The usage of `to_tensor` is deprecated. Please use `init_data`.
Args:
slice_index (int): Slice index of a parameter's slices.
It is used when initialize a slice of a parameter, it guarantees that devices
using the same slice can generate the same tensor. Default: None.
shape (list[int]): Shape of the slice, it is used when initialize a slice of the parameter. Default: None.
opt_shard_group(str): Optimizer shard group which is used in auto or semi auto parallel mode
to get one shard of a parameter's slice. Default: None.
Returns:
Initialized Tensor.
Raises:
TypeError: `indices` is neither int32 nor int64.
ValueError: The length of the shape of the tensor is less than the last dimension of `indices`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import mindspore as ms
>>> from mindspore.common.initializer import initializer, Constant
>>> x = initializer(Constant(1), [2, 2], ms.float32)
>>> out = x.to_tensor()
>>> print(out)
[[1. 1.]
[1. 1.]]
"""
logger.warning("WARN_DEPRECATED: The usage of to_tensor is deprecated."
" Please use init_data")
return self.init_data(slice_index, shape, opt_shard_group)
def resize(self, *new_shape):
"""
Changes shape and size of tensor in-place.
If the shape of the new tensor is larger than the shape of the original tensor, the new tensor will be filled
with 0. And if the shape of the new tensor is smaller than the shape of the original tensor, the new tensor is
filled with the elements of the original tensor in order.
Note:
Instead of changing the size of the input tensor and returns nothing as in numpy,
this method returns a new Tensor with the input size.
Numpy argument `refcheck` is not supported.
Args:
new_shape (Union[ints, tuple of ints]): Shape of resized tensor.
Returns:
Tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.reshape`: Give a new shape to a tensor without changing its data.
:func:`mindspore.Tensor.repeat`: Repeat elements of a tensor.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32))
>>> y = x.resize(3, 3)
>>> print(y)
[[1. 2. 3.]
[4. 5. 6.]
[0. 0. 0.]]
>>> y = x.resize(2, 2)
>>> print(y)
[[1. 2.]
[3. 4.]]
"""
if not new_shape:
return self
if len(new_shape) == 1:
if isinstance(new_shape[0], tuple):
new_shape = new_shape[0]
flattened = self.ravel()
cur_size = flattened.size
new_size = tensor_operator_registry.get('shape_mul')(new_shape)
diff_size = new_size - cur_size
if diff_size > 0:
pad_val = tensor_operator_registry.get('fill')(self.dtype, (diff_size,), 0)
res = tensor_operator_registry.get('concatenate')(0)((flattened, pad_val))
else:
res = flattened[:new_size]
return res.reshape(new_shape)
def diagonal(self, offset=0, axis1=0, axis2=1):
"""
Return specified diagonals.
Args:
offset (int, optional): Offset of the diagonal from the main diagonal.
Can be positive or negative. Defaults to main diagonal.
axis1 (int, optional): Axis to be used as the first axis of the 2-D
sub-arrays from which the diagonals should be taken. Defaults to
first axis (0).
axis2 (int, optional): Axis to be used as the second axis of the 2-D
sub-arrays from which the diagonals should be taken. Defaults to
second axis.
Returns:
Tensor, if Tensor is 2-D, return a 1-D Tensor containing the diagonal.
Raises:
ValueError: If the input tensor has less than two dimensions.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.trace`: Return the sum along diagonals of the tensor.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.arange(4).reshape(2, 2))
>>> print(a)
[[0 1]
[2 3]]
>>> output = a.diagonal()
>>> print(output)
[0 3]
"""
ndim = self.ndim
if ndim < 2:
raise ValueError("For 'Tensor.diagonal', the original tensor requires at least two dimensions, "
"but got {}.".format(ndim))
dtype = self.dtype
axes = validator.check_axis_valid((axis1, axis2), ndim)
perm = ()
for i in range(ndim):
if i not in axes:
perm += (i,)
perm += axes
a = self.transpose(perm)
shape = a.shape
n, m = shape[-2:]
e = tensor_operator_registry.get('eye')(n, m, dtype)
if offset >= m or offset <= -n:
e = tensor_operator_registry.get('fill')(dtype, (n, m), 0)
elif offset != 0:
e = e.astype(mstype.float32)
if offset > 0:
e_left = tensor_operator_registry.get('fill')(dtype, (n, offset), 0)
e_right = e[..., 0:m - offset:1]
e = tensor_operator_registry.get('concatenate')(1)((e_left, e_right)).astype(dtype)
elif offset < 0:
e_upper = tensor_operator_registry.get('fill')(dtype, (-offset, m), 0)
e_lower = e[0:n + offset:1, ...]
e = tensor_operator_registry.get('concatenate')(0)((e_upper, e_lower)).astype(dtype)
e = tensor_operator_registry.get('broadcast_to')(shape)(e)
prod = tensor_operator_registry.get('__mul__')(a, e)
res = tensor_operator_registry.get('reduce_sum')(prod.astype(mstype.float32), -1)
begin = ()
for i in range(ndim - 2):
begin += (0,)
last_dim_begin = max(0, -offset)
begin += (last_dim_begin,)
size = res.shape[:-1]
last_dim_end = min(
shape[-2], max(0, shape[-1] - offset)) - last_dim_begin
if last_dim_end <= 0:
return Tensor([])
size += (last_dim_end,)
res = tensor_operator_registry.get('tensor_slice')(res, begin, size)
return res.astype(dtype)
def trace(self, offset=0, axis1=0, axis2=1, dtype=None):
"""
Return the sum along diagonals of the tensor.
Args:
offset (int, optional): Offset of the diagonal from the main diagonal.
Can be positive or negative. Defaults to main diagonal.
axis1 (int, optional): Axis to be used as the first axis of the 2-D
sub-arrays from which the diagonals should be taken. Defaults to
first axis (0).
axis2 (int, optional): Axis to be used as the second axis of the 2-D
sub-arrays from which the diagonals should be taken. Defaults to
second axis.
dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
output Tensor.
Returns:
Tensor, the sum along diagonals.
Raises:
ValueError: If the input tensor has less than two dimensions.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.diagonal`: Return specified diagonals.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.eye(3, dtype=np.float32))
>>> print(x.trace())
3.0
"""
d = self.diagonal(offset, axis1=axis1, axis2=axis2)
shape = d.shape
if dtype is None:
dtype = d.dtype
if shape[-1] == 0:
return tensor_operator_registry.get('fill')(dtype, shape[:-1], 0)
res = tensor_operator_registry.get('reduce_sum')(d.astype(mstype.float32), -1)
return res.astype(dtype)
def take(self, indices, axis=None, mode='clip'):
"""
Takes elements from a tensor along an axis.
Args:
indices (Tensor): The indices with shape `(Nj...)` of the values to extract.
axis (int, optional): The axis over which to select values. By default,
the flattened input tensor is used. Default: `None`.
mode ('raise', 'wrap', 'clip', optional): Default: "clip".
'raise' – Raises an error;
'wrap' – Wraps around;
'clip' – Clips to the range. 'clip' mode means that all indices that are
too large are replaced by the index that addresses the last element
along that axis. Note that this disables indexing with negative numbers.
Default: 'clip'.
Returns:
Tensor, the indexed result.
Raises:
ValueError: If `axis` is out of range, or `mode` has values other than ('raise', 'wrap', 'clip')
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> a = Tensor(np.array([4, 3, 5, 7, 6, 8]))
>>> indices = Tensor(np.array([0, 1, 4]))
>>> output = a.take(indices)
>>> print(output)
[4 3 6]
"""
if mode not in ('raise', 'wrap', 'clip'):
raise ValueError(f"For 'Tensor.take', the argument 'mode' should be one of in ['raise', 'wrap', 'clip'],"
f" but got {mode}.")
if axis is None:
a = self.ravel()
axis = 0
else:
a = self
ndim = a.ndim
validator.check_axis_in_range(axis, ndim)
axis = axis + ndim if axis < 0 else axis
shape_a = a.shape
shape_indices = indices.shape
size_indices = indices.size
indices = tensor_operator_registry.get('check_indices')(shape_a[axis], indices, mode)
# reshapes indices to shape (Ni..., Nj..., Nk)
shape_ni = shape_a[:axis]
shape_nk = shape_a[axis + 1:]
shape_out = shape_ni + shape_indices + shape_nk
shape_indices = tuple(size_indices if i == axis else 1 for i in range(ndim))
indices = indices.reshape(shape_indices)
shape_indices = shape_ni + (indices.size,) + shape_nk
indices = tensor_operator_registry.get('broadcast_to')(shape_indices)(indices)
res = tensor_operator_registry.get('gather_d')(a, axis, indices)
return res.reshape(shape_out)
def choose(self, choices, mode='clip'):
"""
Construct a tensor from an index tensor and a list of tensors to choose from.
Args:
choices (Union[tuple, list, Tensor]): Choice tensors. The input tensor and all of the
`choices` must be broadcasted to the same shape. If `choices` is itself a tensor,
then its outermost dimension (i.e., the one corresponding to ``choices.shape[0]``)
is taken as defining the "sequence".
mode ('raise', 'wrap', 'clip', optional): Specifies how indices outside
``[0, n-1]`` will be treated:
'raise' – Raises an error;
'wrap' – Wraps around;
'clip' – Clips to the range. 'clip' mode means that values greater than n-1 are mapped to n-1.
Note that this disables indexing with negative numbers.
Default: 'clip'.
Returns:
Tensor, the merged result.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Raises:
ValueError: If the input tensor and any of the `choices` cannot be broadcast.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
>>> x = Tensor(np.array([2, 3, 1, 0]))
>>> print(x.choose(choices))
[20 31 12 3]
"""
if isinstance(choices, Tensor):
shape_choice = validator.infer_out_shape(self.shape, choices.shape[1:])
choices = tensor_operator_registry.get('broadcast_to')((choices.shape[0],) + shape_choice)(choices)
else:
# broadcasts choices to the same shape if choices is a sequence
choicelist = []
shapes = ()
for choice in choices:
if not isinstance(choice, Tensor):
choice = tensor_operator_registry.get('make_tensor')(choice)
shapes += (choice.shape,)
choicelist.append(choice)
shape_choice = validator.infer_out_shape(self.shape, *shapes)
tmp = []
for choice in choicelist:
tmp.append(tensor_operator_registry.get('broadcast_to')(shape_choice)(choice))
choices = tensor_operator_registry.get('stack')(tmp, 0)
if self.ndim == 0 or choices.ndim == 0:
raise ValueError(f"For 'Tensor.choose', the original tensor and the argument 'choices' cannot be scalars."
f" Their dimensions should all be > 0, but got the original tensor's dimension "
f"{self.ndim}, 'choices' dimension {choices.ndim}.")
a = tensor_operator_registry.get('broadcast_to')(shape_choice)(self)
dtype = choices.dtype
# adjusts dtype for F.tensor_mul and F.gather_nd
a = a.astype(mstype.int32)
choices = choices.astype(mstype.int32)
a = tensor_operator_registry.get('check_indices')(choices.shape[0], a, mode, allow_negative_index=False)
grids = []
ndim = len(a.shape)
for i in range(ndim):
dim_grid = Tensor(list(range(a.shape[i])), mstype.int32)
dim_shape = validator.expanded_shape(ndim, a.shape[i], i)
dim_grid = tensor_operator_registry.get('broadcast_to')(a.shape)(dim_grid.reshape(dim_shape))
grids.append(dim_grid)
grid = tensor_operator_registry.get('stack')(grids, -1)
indices = tensor_operator_registry.get('concatenate')(-1)((a.reshape(a.shape + (1,)), grid))
return tensor_operator_registry.get('gather_nd')(choices, indices).astype(dtype)
def searchsorted(self, v, side='left', sorter=None):
"""
Finds indices where elements should be inserted to maintain order.
Args:
v (Union[int, float, bool, list, tuple, Tensor]): Values to insert into the tensor.
side ('left', 'right', optional): If 'left', the index of the first suitable
location found is given. If 'right', return the last such index. If there is
no suitable index, return either 0 or N (where N is the length of the tensor).
Default: 'left'.
sorter (Union[int, float, bool, list, tuple, Tensor]): 1-D optional tensor of
integer indices that sort the tensor into ascending order. They are typically
the result of argsort. Default: None.
Returns:
Tensor, array of insertion points with the same shape as `v`.
Raises:
ValueError: If argument for `side` or `sorter` is invalid.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> x = Tensor(np.array([1, 2, 3, 4, 5]))
>>> print(x.searchsorted(3))
2
"""
if side not in ('left', 'right'):
raise ValueError(f"For 'Tensor.searchsorted', the argument 'side' should be one of in "
f"['left', 'right'], but got {side}.")
a = self.astype(mstype.float32)
if not isinstance(v, Tensor):
v = tensor_operator_registry.get('make_tensor')(v)
shape = v.shape
if sorter is not None:
if not isinstance(sorter, (int, float, bool, list, tuple, Tensor)):
raise TypeError("For Tensor.searchsorted, the type of the argument 'sorter' must be one of 'int', "
"'float', 'bool', 'list', 'tuple', 'Tensor', but got {}.".format(type(sorter)))
if not isinstance(sorter, Tensor):
sorter = tensor_operator_registry.get('make_tensor')(sorter)
if sorter.ndim != 1 or sorter.size != a.size:
raise ValueError('sorter must be 1-D array with the same size as the Tensor')
sorter = sorter.reshape(sorter.shape + (1,))
a = tensor_operator_registry.get('gather_nd')(a, sorter)
less_op = tensor_operator_registry.get('__le__') if side == 'left' else tensor_operator_registry.get('__lt__')
i = tensor_operator_registry.get('fill')(mstype.int32, shape, 0)
j = tensor_operator_registry.get('fill')(mstype.int32, shape, a.size)
sort_range = tuple(range(validator.get_log2_size(tensor_operator_registry.get('shape_mul')(a.shape) + 1)))
for _ in sort_range:
mid = (i - -j) // 2
mask = less_op(v, tensor_operator_registry.get('gather_nd')(a, mid.reshape(mid.shape + (1,))))
i = tensor_operator_registry.get('select')(mask, i, mid)
j = tensor_operator_registry.get('select')(mask, mid, j)
return j
def gather_nd(self, indices):
r"""
Gathers slices from a input tensor by indices.
Using given indices to gather slices from a input tensor with a specified shape.
input tensor's shape is :math:`(N,*)` where :math:`*` means any number of additional dimensions. For convenience
define it as `input_x`, the variable `input_x` refers to input tensor.
`indices` is an K-dimensional integer tensor. Suppose that it is a (K-1)-dimensional tensor and each element
of it defines a slice of input tensor:
.. math::
output[(i_0, ..., i_{K-2})] = input\_x[indices[(i_0, ..., i_{K-2})]]
The last dimension of `indices` can not more than the rank of input tensor:
:math:`indices.shape[-1] <= input\_x.rank`.
Args:
indices (Tensor): The index tensor that gets the collected elements, with int32 or int64 data type.
Returns:
Tensor, has the same type as input tensor and the shape is
:math:`indices\_shape[:-1] + input\_x\_shape[indices\_shape[-1]:]`.
Raises:
ValueError: If length of shape of input tensor is less than the last dimension of `indices`.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
>>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
>>> output = input_x.gather_nd(indices)
>>> print(output)
[-0.1 0.5]
"""
self._init_check()
validator.check_value_type('indices', indices, (Tensor_,), 'Tensor.gather_nd')
return tensor_operator_registry.get('gather_nd')(self, indices)
def gather(self, input_indices, axis):
r"""
Returns the slice of the input tensor corresponding to the elements of `input_indices` on the specified `axis`.
The shape of input tensor is :math:`(x_1, x_2, ..., x_R)`. For convenience, define it as `input_params`,
the variable `input_params` refers to input tensor.
Note:
1. The value of `input_indices` must be in the range of `[0, input_param.shape[axis])`, the result
is undefined out of range.
2. The data type of `input_params` cannot be
`bool_ <https://www.mindspore.cn/docs/en/r1.8/api_python/mindspore.html#mindspore.dtype>`_ on Ascend
platform currently.
Args:
input_indices (Tensor): Index tensor to be sliced, the shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
Specifies the indices of elements of the original Tensor. The data type can be int32 or int64.
axis (int): Specifies the dimension index to gather indices.
Returns:
Tensor, the shape of tensor is
:math:`input\_params.shape[:axis] + input\_indices.shape + input\_params.shape[axis + 1:]`.
Raises:
TypeError: If `axis` is not an int.
TypeError: If `input_indices` is not a tensor of type int.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
Examples:
>>> # case1: input_indices is a Tensor with shape (5, ).
>>> input_params = Tensor(np.array([1, 2, 3, 4, 5, 6, 7]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2, 4, 2, 6]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[1. 3. 5. 3. 7.]
>>> # case2: input_indices is a Tensor with shape (2, 2). When the input_params has one dimension,
>>> # the output shape is equal to the input_indices shape.
>>> input_indices = Tensor(np.array([[0, 2], [2, 6]]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[ 1. 3.]
[ 3. 7.]]
>>> # case3: input_indices is a Tensor with shape (2, ) and
>>> # input_params is a Tensor with shape (3, 4) and axis is 0.
>>> input_params = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2]), mindspore.int32)
>>> axis = 0
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[1. 2. 3. 4.]
[9. 10. 11. 12.]]
>>> # case4: input_indices is a Tensor with shape (2, ) and
>>> # input_params is a Tensor with shape (3, 4) and axis is 1.
>>> input_params = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]), mindspore.float32)
>>> input_indices = Tensor(np.array([0, 2]), mindspore.int32)
>>> axis = 1
>>> output = input_params.gather(input_indices, axis)
>>> print(output)
[[1. 3.]
[5. 7.]
[9. 11.]]
"""
self._init_check()
validator.check_is_int(axis, 'axis')
return tensor_operator_registry.get('gather')(self, input_indices, axis)
def var(self, axis=None, ddof=0, keepdims=False):
"""
Compute the variance along the specified axis.
The variance is the average of the squared deviations from the mean, i.e.,
:math:`var = mean(abs(x - x.mean())**2)`.
Return the variance, which is computed for the flattened array by default,
otherwise over the specified axis.
Note:
Numpy arguments `dtype`, `out` and `where` are not supported.
Args:
axis (Union[None, int, tuple(int)]): Axis or axes along which the variance is computed.
The default is to compute the variance of the flattened array. Default: `None`.
ddof (int): Means Delta Degrees of Freedom. Default: 0.
The divisor used in calculations is :math:`N - ddof`, where :math:`N` represents the number of elements.
keepdims (bool): Default: `False`.
Returns:
Variance tensor.
Supported Platforms:
``Ascend`` ``GPU`` ``CPU``
See also:
:func:`mindspore.Tensor.mean`: Reduce a dimension of a tensor by averaging all elements in the dimension.
:func:`mindspore.Tensor.std`: Compute the standard deviation along the specified axis.
Examples:
>>> import numpy as np
>>> from mindspore import Tensor
>>> input_x = Tensor(np.array([1., 2., 3., 4.], np.float32))
>>> output = input_x.var()
>>> print(output)
1.25
"""
if 0 in self.shape:
return Tensor(float('nan'), self.dtype)
if not isinstance(ddof, int):
raise TypeError("For 'Tensor.var', the type of the argument 'ddof' must be int, but got "
"{}.".format(type(ddof)))
if not isinstance(keepdims, bool):
raise TypeError("For 'Tensor.var', the type of the argument 'keepdims' must be bool, but "
"got {}.".format(type(keepdims)))
if axis is None:
axis = ()
else:
axis = validator.check_and_canonicalize_axes(axis, self.ndim)
x_mean = tensor_operator_registry.get('mean')(True)(self, axis)
x_sub = tensor_operator_registry.get('__sub__')(self, x_mean)
x_pow = tensor_operator_registry.get('__pow__')(x_sub, 2)
x_sum = tensor_operator_registry.get('sum')(bool(keepdims))(x_pow, axis)
nums = 1
if axis == ():
nums = self.size
else:
for ax in axis:
nums *= self.shape[ax]
return tensor_operator_registry.get