manifest abs absolute add all amax amin append arange arccos arccosh arcsin arcsinh arctan arctan2 arctanh argmax argmin argsort array average bincount broadcastto ceil clip concatenate conj conjugate copy cos cosh countnonzero cross cumprod cumsum diag diagonal diff digitize divide dot dtype einsum empty equal exp expanddims expm1 eye flip floor full fulllike greater greaterequal hstack identity imag interp isclose isfinite isinf isnan less lessequal linspace log log10 log1p log2 logaddexp logicaland logicalnot logicalor logspace matmul max maximum mean median meshgrid mgrid min minimum mod moveaxis multiply nantonum ndim nonzero notequal ones oneslike outer pad percentile power prod quantile ravel real reciprocal repeat reshape roll round sign sin sinh size sort split sqrt square squeeze stack std subtract sum swapaxes take takealongaxis tan tanh tensordot tile trace transpose tri tril triu truedivide vdot vstack where zeros zeroslike check if two shapes are equal args shape1 a list or tuple of integers for first shape to be compared shape2 a list or tuple of integers for second shape to be compared axis an integer list or tuple of integers optional axes to ignore during comparison defaults to none allownone bool optional if true allows none in a shape to match any value in the corresponding position of the other shape defaults to true returns bool true if shapes are considered equal based on the criteria false otherwise examples shapeequal32 64 128 32 64 128 true shapeequal32 64 128 32 64 127 false shapeequal32 64 none 32 64 128 allownonetrue true shapeequal32 64 none 32 64 128 allownonefalse false shapeequal32 64 128 32 63 128 axis1 true shapeequal32 64 128 32 63 127 axis1 2 true shapeequal32 64 128 32 63 127 axis1 2 true shapeequal32 64 32 64 128 false compute the absolute value elementwise keras ops abs is a shorthand for this function args x input tensor returns an array containing the absolute value of each element in x example x keras ops converttotensor1 2 1 2 keras ops absolutex array1 2 1 2 dtypefloat32 shorthand for keras ops absolute return absolutex class addoperation def callself x1 x2 return backend numpy addx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape outputdtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 x1sparse getattrx1 sparse false x2sparse getattrx2 sparse false outputsparse x1sparse and x2sparse return kerastensor outputshape dtypeoutputdtype sparseoutputsparse kerasexportkeras ops add keras ops numpy add def addx1 x2 if anysymbolictensorsx1 x2 return add symboliccallx1 x2 return backend numpy addx1 x2 class alloperation def initself axisnone keepdimsfalse super init if isinstanceaxis int self axis axis else self axis axis self keepdims keepdims def callself x return backend numpy all x axisself axis keepdimsself keepdims def computeoutputspecself x return kerastensor reduceshape x shape axisself axis keepdimsself keepdims dtypebool kerasexportkeras ops all keras ops numpy all def allx axisnone keepdimsfalse if anysymbolictensorsx return allaxisaxis keepdimskeepdims symboliccallx return backend numpy allx axisaxis keepdimskeepdims class anyoperation def initself axisnone keepdimsfalse super init if isinstanceaxis int self axis axis else self axis axis self keepdims keepdims def callself x return backend numpy any x axisself axis keepdimsself keepdims def computeoutputspecself x return kerastensor reduceshape x shape axisself axis keepdimsself keepdims dtypebool kerasexportkeras ops any keras ops numpy any def anyx axisnone keepdimsfalse if anysymbolictensorsx return anyaxisaxis keepdimskeepdims symboliccallx return backend numpy anyx axisaxis keepdimskeepdims class amaxoperation def initself axisnone keepdimsfalse super init if isinstanceaxis int axis axis self axis axis self keepdims keepdims def callself x return backend numpy amax x axisself axis keepdimsself keepdims def computeoutputspecself x return kerastensor reduceshapex shape axisself axis keepdimsself keepdims dtypex dtype kerasexportkeras ops amax keras ops numpy amax def amaxx axisnone keepdimsfalse if anysymbolictensorsx return amaxaxisaxis keepdimskeepdims symboliccallx return backend numpy amaxx axisaxis keepdimskeepdims class aminoperation def initself axisnone keepdimsfalse super init if isinstanceaxis int axis axis self axis axis self keepdims keepdims def callself x return backend numpy aminx axisself axis keepdimsself keepdims def computeoutputspecself x return kerastensor reduceshapex shape axisself axis keepdimsself keepdims dtypex dtype kerasexportkeras ops amin keras ops numpy amin def aminx axisnone keepdimsfalse if anysymbolictensorsx return aminaxisaxis keepdimskeepdims symboliccallx return backend numpy aminx axisaxis keepdimskeepdims class appendoperation def initself axisnone super init self axis axis def callself x1 x2 return backend numpy appendx1 x2 axisself axis def computeoutputspecself x1 x2 x1shape x1 shape x2shape x2 shape dtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 if self axis is none if none in x1shape or none in x2shape outputshape none else outputshape intnp prodx1shape np prodx2shape return kerastensoroutputshape dtypedtype if not shapeequalx1shape x2shape self axis raise valueerror append requires inputs to have the same shape except the faxisself axis but received shape x1shape and fx2shape outputshape listx1shape outputshapeself axis x1shapeself axis x2shapeself axis return kerastensoroutputshape dtypedtype kerasexportkeras ops append keras ops numpy append def append x1 x2 axisnone if anysymbolictensorsx1 x2 return appendaxisaxis symboliccallx1 x2 return backend numpy appendx1 x2 axisaxis class arangeoperation def callself start stopnone step1 dtypenone return backend numpy arangestart stop stepstep dtypedtype def computeoutputspecself start stopnone step1 dtypenone if stop is none start stop 0 start outputshape intnp ceilstop start step if dtype is none dtypestoresolve getattrstart dtype typestart getattrstep dtype typestep if stop is not none dtypestoresolve appendgetattrstop dtype typestop dtype dtypes resulttypedtypestoresolve return kerastensoroutputshape dtypedtype kerasexportkeras ops arange keras ops numpy arange def arangestart stopnone step1 dtypenone return backend numpy arangestart stop stepstep dtypedtype class arccosoperation def callself x return backend numpy arccosx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float return kerastensorx shape dtypedtype kerasexportkeras ops arccos keras ops numpy arccos def arccosx if anysymbolictensorsx return arccos symboliccallx return backend numpy arccosx class arccoshoperation def callself x return backend numpy arccoshx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float return kerastensorx shape dtypedtype kerasexportkeras ops arccosh keras ops numpy arccosh def arccoshx if anysymbolictensorsx return arccosh symboliccallx return backend numpy arccoshx class arcsinoperation def callself x return backend numpy arcsinx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops arcsin keras ops numpy arcsin def arcsinx if anysymbolictensorsx return arcsin symboliccallx return backend numpy arcsinx class arcsinhoperation def callself x return backend numpy arcsinhx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops arcsinh keras ops numpy arcsinh def arcsinhx if anysymbolictensorsx return arcsinh symboliccallx return backend numpy arcsinhx class arctanoperation def callself x return backend numpy arctanx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops arctan keras ops numpy arctan def arctanx if anysymbolictensorsx return arctan symboliccallx return backend numpy arctanx class arctan2operation def callself x1 x2 return backend numpy arctan2x1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputsshape broadcastshapesx1shape x2shape x1dtype backend standardizedtype getattrx1 dtype backend floatx x2dtype backend standardizedtype getattrx2 dtype backend floatx dtype dtypes resulttypex1dtype x2dtype float return kerastensoroutputsshape dtypedtype kerasexportkeras ops arctan2 keras ops numpy arctan2 def arctan2x1 x2 if anysymbolictensorsx1 x2 return arctan2 symboliccallx1 x2 return backend numpy arctan2x1 x2 class arctanhoperation def callself x return backend numpy arctanhx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops arctanh keras ops numpy arctanh def arctanhx if anysymbolictensorsx return arctanh symboliccallx return backend numpy arctanhx class argmaxoperation def initself axisnone super init self axis axis def callself x return backend numpy argmaxx axisself axis def computeoutputspecself x if self axis is none return kerastensor dtypeint32 return kerastensor reduceshapex shape axisself axis dtypeint32 kerasexportkeras ops argmax keras ops numpy argmax def argmaxx axisnone if anysymbolictensorsx return argmaxaxisaxis symboliccallx return backend numpy argmaxx axisaxis class argminoperation def initself axisnone super init self axis axis def callself x return backend numpy argminx axisself axis def computeoutputspecself x if self axis is none return kerastensor dtypeint32 return kerastensor reduceshapex shape axisself axis dtypeint32 kerasexportkeras ops argmin keras ops numpy argmin def argminx axisnone if anysymbolictensorsx return argminaxisaxis symboliccallx return backend numpy argminx axisaxis class argsortoperation def initself axis1 super init self axis axis def callself x return backend numpy argsortx axisself axis def computeoutputspecself x if self axis is none return kerastensorintnp prodx shape dtypeint32 return kerastensorx shape dtypeint32 kerasexportkeras ops argsort keras ops numpy argsort def argsortx axis1 if anysymbolictensorsx return argsortaxisaxis symboliccallx return backend numpy argsortx axisaxis class arrayoperation def callself x dtypenone return backend numpy arrayx dtypedtype def computeoutputspecself x dtypenone return kerastensorx shape dtypedtype kerasexportkeras ops array keras ops numpy array def arrayx dtypenone if anysymbolictensorsx return array symboliccallx dtypedtype return backend numpy arrayx dtypedtype class averageoperation def initself axisnone super init np average does not support axis as tuple as declared by the docstring it only supports int or none self axis axis def callself x weightsnone return backend numpy averagex weightsweights axisself axis def computeoutputspecself x weightsnone dtypestoresolve getattrx dtype typex float if weights is not none shapematch shapeequalx shape weights shape allownonetrue if self axis is not none shapematchonaxis shapeequal x shapeself axis weights shape allownonetrue dtypestoresolve appendgetattrweights dtype typeweights dtype dtypes resulttypedtypestoresolve if self axis is none if weights is none or shapematch return kerastensor dtypedtype else raise valueerror weights must have the same shape as x when faxisnone but received weights shapeweights shape f and x shapex shape if weights is none or shapematchonaxis or shapematch return kerastensor reduceshapex shape axisself axis dtypedtype else weights can either be a 1d array of length x shapeaxis or of the same shape as x raise valueerror weights must have the same size as x at faxisself axis but received fweights shapeweights shape while x shape at fself axis is x shapeself axis kerasexportkeras ops average keras ops numpy average def averagex axisnone weightsnone if anysymbolictensorsx return averageaxisaxis symboliccallx weightsweights return backend numpy averagex weightsweights axisaxis class bincountoperation def initself weightsnone minlength0 super init self weights weights self minlength minlength def callself x return backend numpy bincount x weightsself weights minlengthself minlength def computeoutputspecself x dtypestoresolve x dtype if self weights is not none weights backend converttotensorself weights dtypestoresolve appendweights dtype dtype dtypes resulttypedtypestoresolve else dtype int32 return kerastensorlistx shape 1 none dtypedtype kerasexportkeras ops bincount keras ops numpy bincount def bincountx weightsnone minlength0 if anysymbolictensorsx return bincountweightsweights minlengthminlength symboliccallx return backend numpy bincountx weightsweights minlengthminlength class broadcasttooperation def initself shape super init self shape shape def callself x return backend numpy broadcasttox self shape def computeoutputspecself x catch broadcasting errors for clear error messages broadcastshapesx shape self shape return kerastensorself shape dtypex dtype kerasexport keras ops broadcastto keras ops numpy broadcastto def broadcasttox shape if anysymbolictensorsx return broadcasttoshapeshape symboliccallx return backend numpy broadcasttox shape class ceiloperation def callself x return backend numpy ceilx def computeoutputspecself x if backend standardizedtypex dtype int64 dtype backend floatx else dtype dtypes resulttypex dtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops ceil keras ops numpy ceil def ceilx if anysymbolictensorsx return ceil symboliccallx return backend numpy ceilx class clipoperation def initself xmin xmax super init self xmin xmin self xmax xmax def callself x return backend numpy clipx self xmin self xmax def computeoutputspecself x dtype backend standardizedtypex dtype if dtype bool dtype int32 return kerastensorx shape dtypedtype kerasexportkeras ops clip keras ops numpy clip def clipx xmin xmax if anysymbolictensorsx return clipxmin xmax symboliccallx return backend numpy clipx xmin xmax class concatenateoperation def initself axis0 super init if axis is none raise valueerroraxis cannot be none for concatenate self axis axis def callself xs return backend numpy concatenatexs axisself axis def computeoutputspecself xs firstshape xs0 shape totalsizeonaxis 0 allsparse true dtypestoresolve for x in xs if not shapeequal x shape firstshape axisself axis allownonetrue raise valueerror every value in xs must have the same shape except on fthe axis dim but found element of shape x shape fwhich is different from the first element s fshape firstshape if totalsizeonaxis is none or x shapeself axis is none totalsizeonaxis none else totalsizeonaxis x shapeself axis allsparse allsparse and getattrx sparse false dtypestoresolve appendgetattrx dtype typex outputshape listfirstshape outputshapeself axis totalsizeonaxis dtype dtypes resulttypedtypestoresolve return kerastensoroutputshape dtypedtype sparseallsparse kerasexport keras ops concatenate keras ops numpy concatenate def concatenatexs axis0 if anysymbolictensorsxs return concatenateaxisaxis symboliccallxs return backend numpy concatenatexs axisaxis class conjugateoperation def callself x return backend numpy conjugatex def computeoutputspecself x sparse getattrx sparse false return kerastensorx shape dtypex dtype sparsesparse kerasexportkeras ops conjugate keras ops numpy conjugate def conjugatex if anysymbolictensorsx return conjugate symboliccallx return backend numpy conjugatex class conjconjugate pass kerasexportkeras ops conj keras ops numpy conj def conjx returns a copy of x args x input tensor returns a copy of x cosine elementwise args x input tensor returns the corresponding cosine values hyperbolic cosine elementwise arguments x input tensor returns output tensor of same shape as x counts the number of nonzero values in x along the given axis if no axis is specified then all nonzeros in the tensor are counted args x input tensor axis axis or tuple of axes along which to count the number of nonzeros defaults to none returns int or tensor of ints examples x keras ops array0 1 7 0 3 0 2 19 keras ops countnonzerox 5 keras ops countnonzerox axis0 array1 1 2 1 dtypeint64 keras ops countnonzerox axis1 array2 3 dtypeint64 returns the cross product of two arrays of vectors the cross product of x1 and x2 in r3 is a vector perpendicular to both x1 and x2 if x1 and x2 are arrays of vectors the vectors are defined by the last axis of x1 and x2 by default and these axes can have dimensions 2 or 3 where the dimension of either x1 or x2 is 2 the third component of the input vector is assumed to be zero and the cross product calculated accordingly in cases where both input vectors have dimension 2 the zcomponent of the cross product is returned args x1 components of the first vectors x2 components of the second vectors axisa axis of x1 that defines the vectors defaults to 1 axisb axis of x2 that defines the vectors defaults to 1 axisc axis of the result containing the cross product vectors ignored if both input vectors have dimension 2 as the return is scalar by default the last axis axis if defined the axis of x1 x2 and the result that defines the vectors and cross products overrides axisa axisb and axisc note torch backend does not support two dimensional vectors or the arguments axisa axisb and axisc use axis instead returns vector cross products return the cumulative product of elements along a given axis args x input tensor axis axis along which the cumulative product is computed by default the input is flattened dtype dtype of returned tensor defaults to x dtype returns output tensor returns the cumulative sum of elements along a given axis args x input tensor axis axis along which the cumulative sum is computed by default the input is flattened dtype dtype of returned tensor defaults to x dtype returns output tensor extract a diagonal or construct a diagonal array args x input tensor if x is 2d returns the kth diagonal of x if x is 1d return a 2d tensor with x on the kth diagonal k the diagonal to consider defaults to 0 use k 0 for diagonals above the main diagonal and k 0 for diagonals below the main diagonal returns the extracted diagonal or constructed diagonal tensor examples from keras import ops x ops arange9 reshape3 3 x array0 1 2 3 4 5 6 7 8 ops diagx array0 4 8 ops diagx k1 array1 5 ops diagx k1 array3 7 ops diagops diagx array0 0 0 0 4 0 0 0 8 return specified diagonals if x is 2d returns the diagonal of x with the given offset i e the collection of elements of the form xi ioffset if x has more than two dimensions the axes specified by axis1 and axis2 are used to determine the 2d subarray whose diagonal is returned the shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals args x input tensor offset offset of the diagonal from the main diagonal can be positive or negative defaults to 0 main diagonal axis1 axis to be used as the first axis of the 2d subarrays defaults to 0 first axis axis2 axis to be used as the second axis of the 2d subarrays defaults to 1 second axis returns tensor of diagonals examples from keras import ops x ops arange4 reshape2 2 x array0 1 2 3 x diagonal array0 3 x diagonal1 array1 x ops arange8 reshape2 2 2 x array0 1 2 3 4 5 6 7 x diagonal0 0 1 array0 6 1 7 calculate the nth discrete difference along the given axis the first difference is given by outi ai1 ai along the given axis higher differences are calculated by using diff recursively args a input tensor n the number of times values are differenced defaults to 1 axis axis to compute discrete differences along defaults to 1 last axis returns tensor of diagonals examples from keras import ops x ops converttotensor1 2 4 7 0 ops diffx array 1 2 3 7 ops diffx n2 array 1 1 10 x ops converttotensor1 3 6 10 0 5 6 8 ops diffx array2 3 4 5 1 2 ops diffx axis0 array1 2 0 2 returns the indices of the bins to which each value in x belongs args x input array to be binned bins array of bins it has to be onedimensional and monotonically increasing returns output array of indices of same shape as x example x np array0 0 1 0 3 0 1 6 bins np array0 0 3 0 4 5 7 0 keras ops digitizex bins array1 1 2 1 dot product of two tensors if both x1 and x2 are 1d tensors it is inner product of vectors without complex conjugation if both x1 and x2 are 2d tensors it is matrix multiplication if either x1 or x2 is 0d scalar it is equivalent to x1 x2 if x1 is an nd tensor and x2 is a 1d tensor it is a sum product over the last axis of x1 and x2 if x1 is an nd tensor and x2 is an md tensor where m2 it is a sum product over the last axis of x1 and the secondtolast axis of x2 dotx1 x2i j k m sumai j bk m args x1 first argument x2 second argument note torch backend does not accept 0d tensors as arguments returns dot product of x1 and x2 compute the output shape of einsum the shape computation follows the steps below 1 find all letters in the input specs left part of and break them into two categories letters appearing more than once go to reduceddims otherwise go to keptdims 2 adjust reduceddims and keptdims based on the output spec right part of the rule is if the letter appears in the output spec then move it to keptdims otherwise move it to reduceddims 3 compute the target output shape if no output spec is set then the target output shape will be keptdims e g ijk else it will be the same as output spec is a wildcard that could map shape of arbitrary length 4 for each operand in operands map the shape specified in the input spec to the output target e g if operand is of shape 2 3 4 input spec is i and output target is i jk then 2 will go the index 0 for dims not represented by any letter insert to the wildcard part for each letter in output target not appearing in input spec the dim will be 1 for broadcasting after 4 each operand should have a target shape containing only number and none 5 broadcast all shapes computed from 4 and the result is the output shape let s take an example to illustrate the steps above let s define python x kerastensornone 3 4 y kerastensor2 4 3 z knp einsum ij kji k x y 1 reduceddims is i j keptdims is k 2 reduceddims is still i j and keptdims is k 3 output target is k 4 for x the input spec is ij and the output target is k i and j do not appear in the output target so no replacement happens and none goes to wildcard afterwards k is replaced by 1 so we get shape none 1 applying the same logic to y we get shape 2 5 broadcast none 1 and 2 and we get none 2 which is the output shape the output spec changes the rule of keptdims and reduceddims in short dims appearing in the output spec will be kept and dims not appearing in the output spec will be reduced in this case the input spec is just a string of letters e g ijk replace the letter with the right shape in this case the input spec has e g i j i or j shape matched by will be inserted to the position of replace all letters not yet handled with 1 for broadcasting evaluates the einstein summation convention on the operands args subscripts specifies the subscripts for summation as comma separated list of subscript labels an implicit classical einstein summation calculation is performed unless the explicit indicator is included as well as subscript labels of the precise output form operands the operands to compute the einstein sum of returns the calculation based on the einstein summation convention example from keras import ops a ops arange25 reshape5 5 b ops arange5 c ops arange6 reshape2 3 trace of a matrix ops einsumii a 60 ops einsuma 0 0 60 ops tracea 60 extract the diagonal ops einsumii i a array 0 6 12 18 24 ops einsuma 0 0 0 array 0 6 12 18 24 ops diaga array 0 6 12 18 24 sum over an axis ops einsumij i a array 10 35 60 85 110 ops einsuma 0 1 0 array 10 35 60 85 110 ops suma axis1 array 10 35 60 85 110 for higher dimensional tensors summing a single axis can be done with ellipsis ops einsum j a array 10 35 60 85 110 np einsuma 1 array 10 35 60 85 110 compute a matrix transpose or reorder any number of axes ops einsumji c array0 3 1 4 2 5 ops einsumij ji c array0 3 1 4 2 5 ops einsumc 1 0 array0 3 1 4 2 5 ops transposec array0 3 1 4 2 5 matrix vector multiplication ops einsumij j a b array 30 80 130 180 230 ops einsuma 0 1 b 1 array 30 80 130 180 230 ops einsum j j a b array 30 80 130 180 230 return a tensor of given shape and type filled with uninitialized data args shape shape of the empty tensor dtype desired data type of the empty tensor returns the empty tensor returns x1 x2 elementwise args x1 tensor to compare x2 tensor to compare returns output tensor elementwise comparison of x1 and x2 calculate the exponential of all elements in the input tensor args x input tensor returns output tensor elementwise exponential of x expand the shape of a tensor insert a new axis at the axis position in the expanded tensor shape args x input tensor axis position in the expanded axes where the new axis or axes is placed returns output tensor with the number of dimensions increased calculate expx 1 for all elements in the tensor args x input values returns output tensor elementwise exponential minus one reverse the order of elements in the tensor along the given axis the shape of the tensor is preserved but the elements are reordered args x input tensor axis axis or axes along which to flip the tensor the default axisnone will flip over all of the axes of the input tensor returns output tensor with entries of axis reversed return the floor of the input elementwise the floor of the scalar x is the largest integer i such that i x args x input tensor returns output tensor elementwise floor of x return a new tensor of given shape and type filled with fillvalue args shape shape of the new tensor fillvalue fill value dtype desired data type of the tensor returns output tensor return a full tensor with the same shape and type as the given tensor args x input tensor fillvalue fill value dtype overrides data type of the result returns tensor of fillvalue with the same shape and type as x add an implicit final ellipsis consume slice key element by element check for newaxis and ellipsis keep as many slices remain in our key omitting newaxis all frameworks follow numpy for newaxis np newaxis none at this point we need to consume a new axis from the shape python3 friendly way to compute a slice length return xkey if anysymbolictensorsx return getitem symboliccallx key return xkey class greateroperation def callself x1 x2 return backend numpy greaterx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape return kerastensoroutputshape dtypebool kerasexportkeras ops greater keras ops numpy greater def greaterx1 x2 if anysymbolictensorsx1 x2 return greater symboliccallx1 x2 return backend numpy greaterx1 x2 class greaterequaloperation def callself x1 x2 return backend numpy greaterequalx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape return kerastensoroutputshape dtypebool kerasexport keras ops greaterequal keras ops numpy greaterequal def greaterequalx1 x2 if anysymbolictensorsx1 x2 return greaterequal symboliccallx1 x2 return backend numpy greaterequalx1 x2 class hstackoperation def callself xs return backend numpy hstackxs def computeoutputspecself xs firstshape xs0 shape totalsizeonaxis 0 dtypestoresolve for x in xs if not shapeequalx shape firstshape axis1 allownonetrue raise valueerror every value in xs must have the same shape except on fthe axis dim but found element of shape x shape fwhich is different from the first element s fshape firstshape if totalsizeonaxis is none or x shape1 is none totalsizeonaxis none else totalsizeonaxis x shape1 dtypestoresolve appendgetattrx dtype typex outputshape listfirstshape outputshape1 totalsizeonaxis dtype dtypes resulttypedtypestoresolve return kerastensoroutputshape dtypedtype kerasexportkeras ops hstack keras ops numpy hstack def hstackxs if anysymbolictensorsxs return hstack symboliccallxs return backend numpy hstackxs class identityoperation def callself n dtypenone return backend numpy identityn dtypedtype def computeoutputspecself n dtypenone dtype dtype or backend floatx return kerastensorn n dtypedtype kerasexportkeras ops identity keras ops numpy identity def identityn dtypenone return backend numpy identityn dtypedtype class imagoperation def callself x return backend numpy imagx def computeoutputspecself x sparse getattrx sparse false return kerastensorx shape dtypex dtype sparsesparse kerasexportkeras ops imag keras ops numpy imag def imagx if anysymbolictensorsx return imag symboliccallx return backend numpy imagx class iscloseoperation def callself x1 x2 return backend numpy isclosex1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape return kerastensoroutputshape dtypebool kerasexportkeras ops isclose keras ops numpy isclose def isclosex1 x2 if anysymbolictensorsx1 x2 return isclose symboliccallx1 x2 return backend numpy isclosex1 x2 class isfiniteoperation def callself x return backend numpy isfinitex def computeoutputspecself x return kerastensorx shape dtypebool kerasexportkeras ops isfinite keras ops numpy isfinite def isfinitex if anysymbolictensorsx return isfinite symboliccallx return backend numpy isfinitex class isinfoperation def callself x return backend numpy isinfx def computeoutputspecself x return kerastensorx shape dtypebool kerasexportkeras ops isinf keras ops numpy isinf def isinfx if anysymbolictensorsx return isinf symboliccallx return backend numpy isinfx class isnanoperation def callself x return backend numpy isnanx def computeoutputspecself x return kerastensorx shape dtypebool kerasexportkeras ops isnan keras ops numpy isnan def isnanx if anysymbolictensorsx return isnan symboliccallx return backend numpy isnanx class lessoperation def callself x1 x2 return backend numpy lessx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape return kerastensoroutputshape dtypebool kerasexportkeras ops less keras ops numpy less def lessx1 x2 if anysymbolictensorsx1 x2 return less symboliccallx1 x2 return backend numpy lessx1 x2 class lessequaloperation def callself x1 x2 return backend numpy lessequalx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape return kerastensoroutputshape dtypebool kerasexport keras ops lessequal keras ops numpy lessequal def lessequalx1 x2 if anysymbolictensorsx1 x2 return lessequal symboliccallx1 x2 return backend numpy lessequalx1 x2 class linspaceoperation def init self num50 endpointtrue retstepfalse dtypefloat axis0 super init self num num self endpoint endpoint self retstep retstep self dtype dtype self axis axis def callself start stop return backend numpy linspace start stop numself num endpointself endpoint retstepself retstep dtypeself dtype axisself axis def computeoutputspecself start stop startshape getattrstart shape stopshape getattrstop shape outputshape broadcastshapesstartshape stopshape if self axis 1 outputshape outputshape self num elif self axis 0 outputshape outputshape self axis self num outputshapeself axis else outputshape outputshape self axis 1 self num outputshapeself axis 1 dtype self dtype if self dtype is not none else getattrstart dtype typestart dtype backend resulttypedtype float if self retstep return kerastensoroutputshape dtypedtype none return kerastensoroutputshape dtypedtype kerasexportkeras ops linspace keras ops numpy linspace def linspace start stop num50 endpointtrue retstepfalse dtypenone axis0 if anysymbolictensorsstart stop return linspacenum endpoint retstep dtype axisstart stop return backend numpy linspace start stop numnum endpointendpoint retstepretstep dtypedtype axisaxis class logoperation def callself x return backend numpy logx def computeoutputspecself x dtype backend floatx if backend standardizedtypex dtype int64 else dtypes resulttypex dtype float return kerastensorx shape dtypedtype kerasexportkeras ops log keras ops numpy log def logx if anysymbolictensorsx return log symboliccallx return backend numpy logx class log10operation def callself x return backend numpy log10x def computeoutputspecself x dtype backend floatx if backend standardizedtypex dtype int64 else dtypes resulttypex dtype float return kerastensorx shape dtypedtype kerasexportkeras ops log10 keras ops numpy log10 def log10x if anysymbolictensorsx return log10 symboliccallx return backend numpy log10x class log1poperation def callself x return backend numpy log1px def computeoutputspecself x dtype backend floatx if backend standardizedtypex dtype int64 else dtypes resulttypex dtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops log1p keras ops numpy log1p def log1px if anysymbolictensorsx return log1p symboliccallx return backend numpy log1px class log2operation def callself x return backend numpy log2x def computeoutputspecself x dtype backend floatx if backend standardizedtypex dtype int64 else dtypes resulttypex dtype float return kerastensorx shape dtypedtype kerasexportkeras ops log2 keras ops numpy log2 def log2x if anysymbolictensorsx return log2 symboliccallx return backend numpy log2x class logaddexpoperation def callself x1 x2 return backend numpy logaddexpx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape dtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 float return kerastensoroutputshape dtypedtype kerasexportkeras ops logaddexp keras ops numpy logaddexp def logaddexpx1 x2 if anysymbolictensorsx1 x2 return logaddexp symboliccallx1 x2 return backend numpy logaddexpx1 x2 class logicalandoperation def callself x1 x2 return backend numpy logicalandx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape return kerastensoroutputshape dtypebool kerasexport keras ops logicaland keras ops numpy logicaland def logicalandx1 x2 if anysymbolictensorsx1 x2 return logicaland symboliccallx1 x2 return backend numpy logicalandx1 x2 class logicalnotoperation def callself x return backend numpy logicalnotx def computeoutputspecself x return kerastensorx shape dtypebool kerasexport keras ops logicalnot keras ops numpy logicalnot def logicalnotx if anysymbolictensorsx return logicalnot symboliccallx return backend numpy logicalnotx class logicaloroperation def callself x1 x2 return backend numpy logicalorx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape return kerastensoroutputshape dtypebool kerasexport keras ops logicalor keras ops numpy logicalor def logicalorx1 x2 if anysymbolictensorsx1 x2 return logicalor symboliccallx1 x2 return backend numpy logicalorx1 x2 class logspaceoperation def initself num50 endpointtrue base10 dtypefloat axis0 super init self num num self endpoint endpoint self base base self dtype dtype self axis axis def callself start stop return backend numpy logspace start stop numself num endpointself endpoint baseself base dtypeself dtype axisself axis def computeoutputspecself start stop startshape getattrstart shape stopshape getattrstop shape outputshape broadcastshapesstartshape stopshape if self axis 1 outputshape outputshape self num elif self axis 0 outputshape outputshape self axis self num outputshapeself axis else outputshape outputshape self axis 1 self num outputshapeself axis 1 dtype self dtype if self dtype is not none else getattrstart dtype typestart dtype backend resulttypedtype float return kerastensoroutputshape dtypedtype kerasexportkeras ops logspace keras ops numpy logspace def logspacestart stop num50 endpointtrue base10 dtypenone axis0 if anysymbolictensorsstart stop return logspacenum endpoint base dtype axisstart stop return backend numpy logspace start stop numnum endpointendpoint basebase dtypedtype axisaxis class matmuloperation def callself x1 x2 return backend numpy matmulx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape operationutils computematmuloutputshape x1shape x2shape x1sparse getattrx1 sparse true x2sparse getattrx2 sparse true outputsparse x1sparse and x2sparse dtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 return kerastensoroutputshape dtypedtype sparseoutputsparse kerasexportkeras ops matmul keras ops numpy matmul def matmulx1 x2 if anysymbolictensorsx1 x2 return matmul symboliccallx1 x2 return backend numpy matmulx1 x2 class maxoperation def initself axisnone keepdimsfalse initialnone super init if isinstanceaxis int self axis axis else self axis axis self keepdims keepdims self initial initial def callself x return backend numpy max x axisself axis keepdimsself keepdims initialself initial def computeoutputspecself x return kerastensor reduceshapex shape axisself axis keepdimsself keepdims dtypex dtype kerasexportkeras ops max keras ops numpy max def maxx axisnone keepdimsfalse initialnone if anysymbolictensorsx return maxaxisaxis keepdimskeepdims initialinitial symboliccall x return backend numpy maxx axisaxis keepdimskeepdims initialinitial class maximumoperation def callself x1 x2 return backend numpy maximumx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape outputdtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 x1sparse getattrx1 sparse false x2sparse getattrx2 sparse false outputsparse x1sparse and x2sparse return kerastensor outputshape dtypeoutputdtype sparseoutputsparse kerasexportkeras ops maximum keras ops numpy maximum def maximumx1 x2 if anysymbolictensorsx1 x2 return maximum symboliccallx1 x2 return backend numpy maximumx1 x2 class medianoperation def initself axisnone keepdimsfalse super init if isinstanceaxis int axis axis self axis axis self keepdims keepdims def callself x return backend numpy medianx axisself axis keepdimsself keepdims def computeoutputspecself x outputshape reduceshape x shape axisself axis keepdimsself keepdims if backend standardizedtypex dtype int64 dtype backend floatx else dtype dtypes resulttypex dtype float return kerastensoroutputshape dtypedtype kerasexportkeras ops median keras ops numpy median def medianx axisnone keepdimsfalse if anysymbolictensorsx return medianaxisaxis keepdimskeepdims symboliccallx return backend numpy medianx axisaxis keepdimskeepdims class meshgridoperation def initself indexingxy super init if indexing not in xy ij raise valueerror valid values for indexing are xy and ij but received index self indexing indexing def callself x return backend numpy meshgridx indexingself indexing def computeoutputspecself x outputshape for xi in x if lenxi shape 0 size 1 else if none in xi shape size none else size intnp prodxi shape outputshape appendsize if self indexing ij return kerastensoroutputshape for in rangelenx tmp outputshape0 outputshape0 outputshape1 outputshape1 tmp return kerastensoroutputshape dtypexi dtype for in rangelenx kerasexportkeras ops meshgrid keras ops numpy meshgrid def meshgridx indexingxy if anysymbolictensorsx return meshgridindexingindexing symboliccallx return backend numpy meshgridx indexingindexing class minoperation def initself axisnone keepdimsfalse initialnone super init if isinstanceaxis int self axis axis else self axis axis self keepdims keepdims self initial initial def callself x return backend numpy min x axisself axis keepdimsself keepdims initialself initial def computeoutputspecself x return kerastensor reduceshapex shape axisself axis keepdimsself keepdims dtypex dtype kerasexportkeras ops min keras ops numpy min def minx axisnone keepdimsfalse initialnone if anysymbolictensorsx return minaxisaxis keepdimskeepdims initialinitial symboliccall x return backend numpy minx axisaxis keepdimskeepdims initialinitial class minimumoperation def callself x1 x2 return backend numpy minimumx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape outputdtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 x1sparse getattrx1 sparse false x2sparse getattrx2 sparse false outputsparse x1sparse and x2sparse return kerastensor outputshape dtypeoutputdtype sparseoutputsparse kerasexportkeras ops minimum keras ops numpy minimum def minimumx1 x2 if anysymbolictensorsx1 x2 return minimum symboliccallx1 x2 return backend numpy minimumx1 x2 class modoperation def callself x1 x2 return backend numpy modx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape outputdtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 if outputdtype bool outputdtype int32 x1sparse getattrx1 sparse false x2sparse getattrx2 sparse false outputsparse x1sparse and not x2sparse return kerastensor outputshape dtypeoutputdtype sparseoutputsparse kerasexportkeras ops mod keras ops numpy mod def modx1 x2 if anysymbolictensorsx1 x2 return mod symboliccallx1 x2 return backend numpy modx1 x2 class moveaxisoperation def initself source destination super init if isinstancesource int self source source else self source source if isinstancedestination int self destination destination else self destination destination if lenself source lenself destination raise valueerror source and destination arguments must have the same fnumber of elements but received sourcesource and fdestinationdestination def callself x return backend numpy moveaxisx self source self destination def computeoutputspecself x xshape listx shape outputshape 1 for in rangelenx shape for sc dst in zipself source self destination outputshapedst xshapesc xshapesc 1 i j 0 0 while i lenoutputshape while i lenoutputshape and outputshapei 1 find the first dim unset i 1 while j lenoutputshape and xshapej 1 find the first dim not being passed j 1 if i lenoutputshape break outputshapei xshapej i 1 j 1 return kerastensoroutputshape dtypex dtype kerasexportkeras ops moveaxis keras ops numpy moveaxis def moveaxisx source destination if anysymbolictensorsx return moveaxissource destination symboliccallx return backend numpy moveaxisx sourcesource destinationdestination class nantonumoperation def callself x return backend numpy nantonumx kerasexport keras ops nantonum keras ops numpy nantonum def nantonumx return backend numpy nantonumx class ndimoperation def callself x return backend numpy ndim x def computeoutputspecself x return kerastensorlenx shape kerasexportkeras ops ndim keras ops numpy ndim def ndimx if anysymbolictensorsx return ndim symboliccallx return backend numpy ndimx class nonzerooperation def callself x return backend numpy nonzerox kerasexportkeras ops nonzero keras ops numpy nonzero def nonzerox return backend numpy nonzerox class notequaloperation def callself x1 x2 return backend numpy notequalx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape return kerastensoroutputshape dtypebool kerasexportkeras ops notequal keras ops numpy notequal def notequalx1 x2 if anysymbolictensorsx1 x2 return notequal symboliccallx1 x2 return backend numpy notequalx1 x2 class oneslikeoperation def callself x dtypenone return backend numpy oneslikex dtypedtype def computeoutputspecself x dtypenone if dtype is none dtype x dtype return kerastensorx shape dtypedtype kerasexportkeras ops oneslike keras ops numpy oneslike def oneslikex dtypenone if anysymbolictensorsx return oneslike symboliccallx dtypedtype return backend numpy oneslikex dtypedtype class zeroslikeoperation def callself x dtypenone return backend numpy zeroslikex dtypedtype def computeoutputspecself x dtypenone if dtype is none dtype x dtype return kerastensorx shape dtypedtype kerasexport keras ops zeroslike keras ops numpy zeroslike def zeroslikex dtypenone if anysymbolictensorsx return zeroslike symboliccallx dtypedtype return backend numpy zeroslikex dtypedtype class outeroperation def callself x1 x2 return backend numpy outerx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape 1 x2shape getattrx2 shape 1 if none in x1shape x1flattenshape none else x1flattenshape intnp prodx1shape if none in x2shape x2flattenshape none else x2flattenshape intnp prodx2shape outputshape x1flattenshape x2flattenshape outputdtype backend resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 return kerastensoroutputshape dtypeoutputdtype kerasexportkeras ops outer keras ops numpy outer def outerx1 x2 if anysymbolictensorsx1 x2 return outer symboliccallx1 x2 return backend numpy outerx1 x2 class padoperation def initself padwidth modeconstant super init self padwidth self processpadwidthpadwidth self mode mode def processpadwidthself padwidth if isinstancepadwidth int return padwidth padwidth if isinstancepadwidth tuple list and isinstance padwidth0 int return padwidth firstlen lenpadwidth0 for i pw in enumeratepadwidth if lenpw firstlen raise valueerror padwidth should be a list of tuples of length f1 or 2 received padwidthpadwidth if lenpw 1 padwidthi pw0 pw0 return padwidth def callself x constantvaluesnone return backend numpy pad x padwidthself padwidth modeself mode constantvaluesconstantvalues def computeoutputspecself x constantvaluesnone outputshape listx shape if lenself padwidth 1 padwidth self padwidth0 for in rangelenoutputshape elif lenself padwidth lenoutputshape padwidth self padwidth else raise valueerror padwidth must have the same length as x shape freceived padwidthself padwidth fof length lenself padwidth and x shapex shape fof length lenx shape for i in rangelenoutputshape if outputshapei is none outputshapei none else outputshapei padwidthi0 padwidthi1 return kerastensoroutputshape dtypex dtype kerasexportkeras ops pad keras ops numpy pad def padx padwidth modeconstant constantvaluesnone return padpadwidth modemodex constantvaluesconstantvalues class prodoperation def initself axisnone keepdimsfalse dtypenone super init if isinstanceaxis int self axis axis else self axis axis self keepdims keepdims self dtype dtype def callself x return backend numpy prod x axisself axis keepdimsself keepdims dtypeself dtype def computeoutputspecself x if self dtype is not none dtype self dtype else dtype backend resulttypex dtype if dtype bool dtype int32 elif dtype in int8 int16 dtype int32 elif dtype in uint8 uint16 dtype uint32 todo torch doesn t support uint32 if backend backend torch and dtype uint32 dtype int32 return kerastensor reduceshapex shape axisself axis keepdimsself keepdims dtypedtype kerasexportkeras ops prod keras ops numpy prod def prodx axisnone keepdimsfalse dtypenone if anysymbolictensorsx return prodaxisaxis keepdimskeepdims dtypedtype symboliccallx return backend numpy prodx axisaxis keepdimskeepdims dtypedtype class quantileoperation def initself axisnone methodlinear keepdimsfalse super init if isinstanceaxis int axis axis self axis axis self method method self keepdims keepdims def callself x q return backend numpy quantile x q axisself axis keepdimsself keepdims def computeoutputspecself x q outputshape reduceshape x shape axisself axis keepdimsself keepdims if hasattrq shape if lenq shape 0 outputshape q shape0 outputshape if backend standardizedtypex dtype int64 dtype backend floatx else dtype dtypes resulttypex dtype float return kerastensoroutputshape dtypedtype kerasexportkeras ops quantile keras ops numpy quantile def quantilex q axisnone methodlinear keepdimsfalse if anysymbolictensorsx q return quantile axisaxis methodmethod keepdimskeepdims symboliccallx q return backend numpy quantile x q axisaxis methodmethod keepdimskeepdims class raveloperation def callself x return backend numpy ravelx def computeoutputspecself x if none in x shape outputshape none else outputshape intnp prodx shape return kerastensoroutputshape dtypex dtype kerasexportkeras ops ravel keras ops numpy ravel def ravelx if anysymbolictensorsx return ravel symboliccallx return backend numpy ravelx class realoperation def callself x return backend numpy realx def computeoutputspecself x sparse getattrx sparse false return kerastensorx shape dtypex dtype sparsesparse kerasexportkeras ops real keras ops numpy real def realx if anysymbolictensorsx return real symboliccallx return backend numpy realx class reciprocaloperation def callself x return backend numpy reciprocalx def computeoutputspecself x return kerastensorx shape kerasexport keras ops reciprocal keras ops numpy reciprocal def reciprocalx if anysymbolictensorsx return reciprocal symboliccallx return backend numpy reciprocalx class repeatoperation def initself repeats axisnone super init self axis axis self repeats repeats def callself x return backend numpy repeatx self repeats axisself axis def computeoutputspecself x xshape listx shape if self axis is none if none in xshape return kerastensornone dtypex dtype xflattensize intnp prodxshape if isinstanceself repeats int outputshape xflattensize self repeats else outputshape intnp sumself repeats return kerastensoroutputshape dtypex dtype sizeonax xshapeself axis outputshape xshape if isinstanceself repeats int if sizeonax is none outputshapeself axis none else outputshapeself axis sizeonax self repeats else outputshapeself axis intnp sumself repeats return kerastensoroutputshape dtypex dtype kerasexportkeras ops repeat keras ops numpy repeat def repeatx repeats axisnone if anysymbolictensorsx return repeatrepeats axisaxis symboliccallx return backend numpy repeatx repeats axisaxis class reshapeoperation def initself newshape super init self newshape newshape def callself x return backend numpy reshapex self newshape def computeoutputspecself x outputshape operationutils computereshapeoutputshape x shape self newshape newshape sparse getattrx sparse false return kerastensoroutputshape dtypex dtype sparsesparse kerasexportkeras ops reshape keras ops numpy reshape def reshapex newshape if anysymbolictensorsx return reshapenewshape symboliccallx return backend numpy reshapex newshape class rolloperation def initself shift axisnone super init self shift shift self axis axis def callself x return backend numpy rollx self shift self axis def computeoutputspecself x return kerastensorx shape dtypex dtype kerasexportkeras ops roll keras ops numpy roll def rollx shift axisnone if anysymbolictensorsx return rollshift axisaxis symboliccallx return backend numpy rollx shift axisaxis class roundoperation def initself decimals0 super init self decimals decimals def callself x return backend numpy roundx self decimals def computeoutputspecself x sparse getattrx sparse false return kerastensorx shape dtypex dtype sparsesparse kerasexportkeras ops round keras ops numpy round def roundx decimals0 if anysymbolictensorsx return rounddecimals symboliccallx return backend numpy roundx decimals class signoperation def callself x return backend numpy signx def computeoutputspecself x sparse getattrx sparse false return kerastensorx shape dtypex dtype sparsesparse kerasexportkeras ops sign keras ops numpy sign def signx if anysymbolictensorsx return sign symboliccallx return backend numpy signx class sinoperation def callself x return backend numpy sinx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops sin keras ops numpy sin def sinx if anysymbolictensorsx return sin symboliccallx return backend numpy sinx class sinhoperation def callself x return backend numpy sinhx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops sinh keras ops numpy sinh def sinhx if anysymbolictensorsx return sinh symboliccallx return backend numpy sinhx class sizeoperation def callself x return backend numpy sizex def computeoutputspecself x return kerastensor dtypeint32 kerasexportkeras ops size keras ops numpy size def sizex if anysymbolictensorsx return size symboliccallx return backend numpy sizex class sortoperation def initself axis1 super init self axis axis def callself x return backend numpy sortx axisself axis def computeoutputspecself x return kerastensorx shape x dtype kerasexportkeras ops sort keras ops numpy sort def sortx axis1 if anysymbolictensorsx return sortaxisaxis symboliccallx return backend numpy sortx axisaxis class splitoperation def initself indicesorsections axis0 super init if not isinstanceindicesorsections int indicesorsections tupleindicesorsections self indicesorsections indicesorsections self axis axis def callself x return backend numpy splitx self indicesorsections axisself axis def computeoutputspecself x xshape listx shape xsizeonaxis xshapeself axis if isinstanceself indicesorsections int if xsizeonaxis is none xshapeself axis none return kerastensorxshape dtypex dtype for in rangeself indicesorsections if np modxsizeonaxis self indicesorsections 0 raise valueerror x size on given axis must be dividible by indicesorsections when indicesorsections is an fint but received xsizeonaxis and fself indicesorsections size xsizeonaxis self indicesorsections xshapeself axis size return kerastensorxshape dtypex dtype for in rangeself indicesorsections indicesorsections 0 self indicesorsections xsizeonaxis outputsize np diffindicesorsections outputs for i in rangelenoutputsize outputshape listxshape outputshapeself axis intoutputsizei outputs appendkerastensoroutputshape dtypex dtype return outputs kerasexportkeras ops split keras ops numpy split def splitx indicesorsections axis0 if anysymbolictensorsx return splitindicesorsections axisaxis symboliccallx return backend numpy splitx indicesorsections axisaxis class stackoperation def initself axis0 super init self axis axis def callself xs return backend numpy stackxs axisself axis def computeoutputspecself xs firstshape xs0 shape dtypestoresolve for x in xs if not shapeequalx shape firstshape axis allownonetrue raise valueerror every value in xs must have the same shape but found felement of shape x shape which is different from the ffirst element s shape firstshape dtypestoresolve appendgetattrx dtype typex sizeonaxis lenxs outputshape listfirstshape if self axis 1 outputshape outputshape sizeonaxis elif self axis 0 outputshape insertself axis sizeonaxis else outputshape insertself axis 1 sizeonaxis outputdtype dtypes resulttypedtypestoresolve return kerastensoroutputshape dtypeoutputdtype kerasexportkeras ops stack keras ops numpy stack def stackx axis0 if anysymbolictensorsx return stackaxisaxis symboliccallx return backend numpy stackx axisaxis class stdoperation def initself axisnone keepdimsfalse super init if isinstanceaxis int self axis axis else self axis axis self keepdims keepdims def callself x return backend numpy stdx axisself axis keepdimsself keepdims def computeoutputspecself x outputdtype backend standardizedtypex dtype if int in outputdtype or outputdtype bool outputdtype backend floatx return kerastensor reduceshapex shape axisself axis keepdimsself keepdims dtypeoutputdtype kerasexportkeras ops std keras ops numpy std def stdx axisnone keepdimsfalse if anysymbolictensorsx return stdaxisaxis keepdimskeepdims symboliccallx return backend numpy stdx axisaxis keepdimskeepdims class swapaxesoperation def initself axis1 axis2 super init self axis1 axis1 self axis2 axis2 def callself x return backend numpy swapaxesx self axis1 self axis2 def computeoutputspecself x xshape listx shape tmp xshapeself axis1 xshapeself axis1 xshapeself axis2 xshapeself axis2 tmp return kerastensorxshape dtypex dtype kerasexportkeras ops swapaxes keras ops numpy swapaxes def swapaxesx axis1 axis2 if anysymbolictensorsx return swapaxesaxis1 axis2 symboliccallx return backend numpy swapaxesx axis1axis1 axis2axis2 class takeoperation def initself axisnone super init self axis axis def callself x indices return backend numpy takex indices axisself axis def computeoutputspecself x indices xshape listx shape if isinstanceindices kerastensor indicesshape listindices shape else indicesshape listgetattrnp arrayindices shape if self axis is none return kerastensorindicesshape dtypex dtype make sure axis is nonnegative axis lenxshape self axis if self axis 0 else self axis outputshape xshape axis indicesshape xshapeaxis 1 return kerastensoroutputshape dtypex dtype kerasexportkeras ops take keras ops numpy take def takex indices axisnone if anysymbolictensorsx indices return takeaxisaxis symboliccallx indices return backend numpy takex indices axisaxis class takealongaxisoperation def initself axisnone super init self axis axis def callself x indices return backend numpy takealongaxisx indices axisself axis def computeoutputspecself x indices xshape listx shape indicesshape listindices shape if self axis is none xshape none if none in xshape else intnp prodxshape if lenxshape lenindicesshape raise valueerror x and indices must have the same number of dimensions fbut receive shape xshape and indicesshape del xshapeself axis del indicesshapeself axis outputshape broadcastshapesxshape indicesshape sizeonaxis indices shapeself axis if self axis 1 outputshape outputshape sizeonaxis elif self axis 0 outputshape insertself axis sizeonaxis else outputshape insertself axis 1 sizeonaxis return kerastensoroutputshape dtypex dtype kerasexport keras ops takealongaxis keras ops numpy takealongaxis def takealongaxisx indices axisnone if anysymbolictensorsx indices return takealongaxisaxisaxis symboliccallx indices return backend numpy takealongaxisx indices axisaxis class tanoperation def callself x return backend numpy tanx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops tan keras ops numpy tan def tanx if anysymbolictensorsx return tan symboliccallx return backend numpy tanx class tanhoperation def callself x return backend numpy tanhx def computeoutputspecself x dtype backend standardizedtypegetattrx dtype backend floatx if dtype int64 dtype backend floatx else dtype dtypes resulttypedtype float sparse getattrx sparse false return kerastensorx shape dtypedtype sparsesparse kerasexportkeras ops tanh keras ops numpy tanh def tanhx if anysymbolictensorsx return tanh symboliccallx return backend numpy tanhx class tensordotoperation def initself axes2 super init self axes axes def callself x1 x2 return backend numpy tensordotx1 x2 axesself axes def computeoutputspecself x1 x2 x1shape listgetattrx1 shape x2shape listgetattrx2 shape dtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 if not isinstanceself axes int x1selectshape x1shapeax for ax in self axes0 x2selectshape x2shapeax for ax in self axes1 if not shapeequal x1selectshape x2selectshape allownonetrue raise valueerror shape mismatch on x1axes0 and x2axes1 freceived x1selectshape and x2selectshape for ax in self axes0 x1shapeax 1 for ax in self axes1 x2shapeax 1 x1shape listfilter1 ne x1shape x2shape listfilter1 ne x2shape outputshape x1shape x2shape return kerastensoroutputshape dtypedtype if self axes 0 outputshape x1shape x2shape else outputshape x1shape self axes x2shapeself axes return kerastensoroutputshape dtypedtype kerasexportkeras ops tensordot keras ops numpy tensordot def tensordotx1 x2 axes2 if anysymbolictensorsx1 x2 return tensordotaxesaxes symboliccallx1 x2 return backend numpy tensordotx1 x2 axesaxes class tileoperation def initself repeats super init self repeats repeats def callself x return backend numpy tilex self repeats def computeoutputspecself x xshape listx shape repeats self repeats if lenxshape lenrepeats repeats 1 lenxshape lenrepeats repeats else xshape 1 lenrepeats lenxshape xshape outputshape for xsize repeat in zipxshape repeats if xsize is none outputshape appendnone else outputshape appendxsize repeat return kerastensoroutputshape dtypex dtype kerasexportkeras ops tile keras ops numpy tile def tilex repeats if anysymbolictensorsx return tile repeats symboliccallx return backend numpy tilex repeats class traceoperation def initself offset0 axis10 axis21 super init self offset offset self axis1 axis1 self axis2 axis2 def callself x return backend numpy trace x offsetself offset axis1self axis1 axis2self axis2 def computeoutputspecself x xshape listx shape xshapeself axis1 1 xshapeself axis2 1 outputshape listfilter1 ne xshape outputdtype backend standardizedtypex dtype if outputdtype not in int64 uint32 uint64 outputdtype dtypes resulttypeoutputdtype int32 return kerastensoroutputshape dtypeoutputdtype kerasexportkeras ops trace keras ops numpy trace def tracex offset0 axis10 axis21 if anysymbolictensorsx return traceoffset axis1 axis2 symboliccallx return backend numpy tracex offsetoffset axis1axis1 axis2axis2 class trioperation def callself n mnone k0 dtypenone return backend numpy trin mm kk dtypedtype def computeoutputspecself n mnone k0 dtypenone if m is none m n dtype dtype or backend floatx return kerastensorn m dtypedtype kerasexportkeras ops tri keras ops numpy tri def trin mnone k0 dtypenone return backend numpy trin mm kk dtypedtype class triloperation def initself k0 super init self k k def callself x return backend numpy trilx kself k def computeoutputspecself x return kerastensorx shape dtypex dtype kerasexportkeras ops tril keras ops numpy tril def trilx k0 if anysymbolictensorsx return trilkk symboliccallx return backend numpy trilx kk class triuoperation def initself k0 super init self k k def callself x return backend numpy triux kself k def computeoutputspecself x return kerastensorx shape dtypex dtype kerasexportkeras ops triu keras ops numpy triu def triux k0 if anysymbolictensorsx return triukk symboliccallx return backend numpy triux kk class vdotoperation def callself x1 x2 return backend numpy vdotx1 x2 def computeoutputspecself x1 x2 dtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 return kerastensor dtypedtype kerasexportkeras ops vdot keras ops numpy vdot def vdotx1 x2 if anysymbolictensorsx1 x2 return vdot symboliccallx1 x2 return backend numpy vdotx1 x2 class vstackoperation def callself xs return backend numpy vstackxs def computeoutputspecself xs firstshape xs0 shape totalsizeonaxis 0 dtypestoresolve for x in xs if not shapeequalx shape firstshape axis0 allownonetrue raise valueerror every value in xs must have the same shape except on fthe axis dim but found element of shape x shape fwhich is different from the first element s fshape firstshape if totalsizeonaxis is none or x shape0 is none totalsizeonaxis none else totalsizeonaxis x shape0 dtypestoresolve appendgetattrx dtype typex outputshape listfirstshape outputshape0 totalsizeonaxis outputdtype dtypes resulttypedtypestoresolve return kerastensoroutputshape outputdtype kerasexportkeras ops vstack keras ops numpy vstack def vstackxs if anysymbolictensorsxs return vstack symboliccallxs return backend numpy vstackxs class whereoperation def callself condition x1none x2none return backend numpy wherecondition x1 x2 def computeoutputspecself condition x1 x2 conditionshape getattrcondition shape x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesconditionshape x1shape outputshape broadcastshapesoutputshape x2shape outputdtype dtypes resulttype getattrx1 dtype typex1 if x1 is not none else int getattrx2 dtype typex2 if x2 is not none else int return kerastensoroutputshape dtypeoutputdtype kerasexportkeras ops where keras ops numpy where def wherecondition x1none x2none if x1 is none and x2 is not none or x1 is not none and x2 is none raise valueerror x1 and x2 either both should be none or both should have nonnone value if anysymbolictensorscondition x1 x2 return where symboliccallcondition x1 x2 return backend numpy wherecondition x1 x2 class subtractoperation def callself x1 x2 return backend numpy subtractx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape x1sparse getattrx1 sparse false x2sparse getattrx2 sparse false outputsparse x1sparse and x2sparse dtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 return kerastensoroutputshape dtypedtype sparseoutputsparse kerasexportkeras ops subtract keras ops numpy subtract def subtractx1 x2 if anysymbolictensorsx1 x2 return subtract symboliccallx1 x2 return backend numpy subtractx1 x2 class multiplyoperation def callself x1 x2 return backend numpy multiplyx1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape x1sparse getattrx1 sparse true x2sparse getattrx2 sparse true outputsparse x1sparse or x2sparse dtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 return kerastensoroutputshape dtypedtype sparseoutputsparse kerasexportkeras ops multiply keras ops numpy multiply def multiplyx1 x2 if anysymbolictensorsx1 x2 return multiply symboliccallx1 x2 return backend numpy multiplyx1 x2 class divideoperation def callself x1 x2 return backend numpy dividex1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape outputdtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 float x1sparse getattrx1 sparse false x2sparse getattrx2 sparse false outputsparse x1sparse and not x2sparse return kerastensor outputshape dtypeoutputdtype sparseoutputsparse kerasexportkeras ops divide keras ops numpy divide def dividex1 x2 if anysymbolictensorsx1 x2 return divide symboliccallx1 x2 return backend numpy dividex1 x2 class truedivideoperation def callself x1 x2 return backend numpy truedividex1 x2 def computeoutputspecself x1 x2 x1shape getattrx1 shape x2shape getattrx2 shape outputshape broadcastshapesx1shape x2shape outputdtype dtypes resulttype getattrx1 dtype typex1 getattrx2 dtype typex2 float x1sparse getattrx1 sparse false x2sparse getattrx2 sparse false outputsparse x1sparse and not x2sparse return kerastensor outputshape dtypeoutputdtype sparseoutputsparse kerasexport keras ops truedivide keras ops numpy truedivide def truedividex1 x2 first tensor elements raised to powers from second tensor elementwise args x1 the bases x2 the exponents returns output tensor the bases in x1 raised to the exponents in x2 numerical negative elementwise args x input tensor returns output tensor y x return the elementwise square of the input args x input tensor returns output tensor the square of x return the nonnegative square root of a tensor elementwise args x input tensor returns output tensor the nonnegative square root of x remove axes of length one from x args x input tensor axis select a subset of the entries of length one in the shape returns the input tensor with all or a subset of the dimensions of length 1 removed returns a tensor with axes transposed args x input tensor axes sequence of integers permutation of the dimensions of x by default the order of the axes are reversed returns x with its axes permuted compute the arithmetic mean along the specified axes args x input tensor axis axis or axes along which the means are computed the default is to compute the mean of the flattened tensor keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one returns output tensor containing the mean values compute the variance along the specified axes args x input tensor axis axis or axes along which the variance is computed the default is to compute the variance of the flattened tensor keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one returns output tensor containing the variance follow jax s rule todo torch doesn t support uint32 sum of a tensor over the given axes args x input tensor axis axis or axes along which the sum is computed the default is to compute the sum of the flattened tensor keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one returns output tensor containing the sum return a new tensor of given shape and type filled with zeros args shape shape of the new tensor dtype desired data type of the tensor returns tensor of zeros with the given shape and dtype return a new tensor of given shape and type filled with ones args shape shape of the new tensor dtype desired data type of the tensor returns tensor of ones with the given shape and dtype return a 2d tensor with ones on the diagonal and zeros elsewhere args n number of rows in the output m number of columns in the output if none defaults to n k index of the diagonal 0 the default refers to the main diagonal a positive value refers to an upper diagonal and a negative value to a lower diagonal dtype data type of the returned tensor returns tensor with ones on the kth diagonal and zeros elsewhere returns the largest integer smaller or equal to the division of inputs args x1 numerator x2 denominator returns output tensor y floorx1x2 compute the truth value of x1 xor x2 elementwise args x1 first input tensor x2 second input tensor returns output boolean tensor check if two shapes are equal args shape1 a list or tuple of integers for first shape to be compared shape2 a list or tuple of integers for second shape to be compared axis an integer list or tuple of integers optional axes to ignore during comparison defaults to none allow_none bool optional if true allows none in a shape to match any value in the corresponding position of the other shape defaults to true returns bool true if shapes are considered equal based on the criteria false otherwise examples shape_equal 32 64 128 32 64 128 true shape_equal 32 64 128 32 64 127 false shape_equal 32 64 none 32 64 128 allow_none true true shape_equal 32 64 none 32 64 128 allow_none false false shape_equal 32 64 128 32 63 128 axis 1 true shape_equal 32 64 128 32 63 127 axis 1 2 true shape_equal 32 64 128 32 63 127 axis 1 2 true shape_equal 32 64 32 64 128 false compute the absolute value element wise keras ops abs is a shorthand for this function args x input tensor returns an array containing the absolute value of each element in x example x keras ops convert_to_tensor 1 2 1 2 keras ops absolute x array 1 2 1 2 dtype float32 shorthand for keras ops absolute add arguments element wise args x1 first input tensor x2 second input tensor returns the tensor containing the element wise sum of x1 and x2 examples x1 keras ops convert_to_tensor 1 4 x2 keras ops convert_to_tensor 5 6 keras ops add x1 x2 array 6 10 dtype int32 keras ops add also broadcasts shapes x1 keras ops convert_to_tensor 5 4 5 6 x2 keras ops convert_to_tensor 5 6 keras ops add x1 x2 array 10 10 10 12 shape 2 2 dtype int32 test whether all array elements along a given axis evaluate to true args x input tensor axis an integer or tuple of integers that represent the axis along which a logical and reduction is performed the default axis none is to perform a logical and over all the dimensions of the input array axis may be negative in which case it counts for the last to the first axis keepdims if true 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 defaults to false returns the tensor containing the logical and reduction over the axis examples x keras ops convert_to_tensor true false keras ops all x array false shape dtype bool x keras ops convert_to_tensor true false true true keras ops all x axis 0 array true false shape 2 dtype bool keepdims true outputs a tensor with dimensions reduced to one x keras ops convert_to_tensor true false true true keras ops all x keepdims true array false shape 1 1 dtype bool test whether any array element along a given axis evaluates to true args x input tensor axis an integer or tuple of integers that represent the axis along which a logical or reduction is performed the default axis none is to perform a logical or over all the dimensions of the input array axis may be negative in which case it counts for the last to the first axis keepdims if true 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 defaults to false returns the tensor containing the logical or reduction over the axis examples x keras ops convert_to_tensor true false keras ops any x array true shape dtype bool x keras ops convert_to_tensor true false true true keras ops any x axis 0 array true true shape 2 dtype bool keepdims true outputs a tensor with dimensions reduced to one x keras ops convert_to_tensor true false true true keras ops all x keepdims true array false shape 1 1 dtype bool returns the maximum of an array or maximum value along an axis args x input tensor axis axis along which to compute the maximum by default axis none find the maximum value in all the dimensions of the input array keepdims if true axes which are reduced are left in the result as dimensions that are broadcast to the size of the original input tensor defaults to false returns an array with the maximum value if axis none the result is a scalar value representing the maximum element in the entire array if axis is given the result is an array with the maximum values along the specified axis examples x keras ops convert_to_tensor 1 3 5 2 3 6 keras ops amax x array 6 dtype int32 x keras ops convert_to_tensor 1 6 8 1 5 2 keras ops amax x axis 0 array 1 6 8 dtype int32 x keras ops convert_to_tensor 1 6 8 1 5 2 keras ops amax x axis 1 keepdims true array 8 5 dtype int32 returns the minimum of an array or minimum value along an axis args x input tensor axis axis along which to compute the minimum by default axis none find the minimum value in all the dimensions of the input array keepdims if true axes which are reduced are left in the result as dimensions that are broadcast to the size of the original input tensor defaults to false returns an array with the minimum value if axis none the result is a scalar value representing the minimum element in the entire array if axis is given the result is an array with the minimum values along the specified axis examples x keras ops convert_to_tensor 1 3 5 2 3 6 keras ops amin x array 1 dtype int32 x keras ops convert_to_tensor 1 6 8 7 5 3 keras ops amin x axis 0 array 1 5 3 dtype int32 x keras ops convert_to_tensor 1 6 8 7 5 3 keras ops amin x axis 1 keepdims true array 1 3 dtype int32 append tensor x2 to the end of tensor x1 args x1 first input tensor x2 second input tensor axis axis along which tensor x2 is appended to tensor x1 if none both tensors are flattened before use returns a tensor with the values of x2 appended to x1 examples x1 keras ops convert_to_tensor 1 2 3 x2 keras ops convert_to_tensor 4 5 6 7 8 9 keras ops append x1 x2 array 1 2 3 4 5 6 7 8 9 dtype int32 when axis is specified x1 and x2 must have compatible shapes x1 keras ops convert_to_tensor 1 2 3 4 5 6 x2 keras ops convert_to_tensor 7 8 9 keras ops append x1 x2 axis 0 array 1 2 3 4 5 6 7 8 9 dtype int32 x3 keras ops convert_to_tensor 7 8 9 keras ops append x1 x3 axis 0 traceback most recent call last typeerror cannot concatenate arrays with different numbers of dimensions got 2 3 3 return evenly spaced values within a given interval arange can be called with a varying number of positional arguments arange stop values are generated within the half open interval 0 stop in other words the interval including start but excluding stop arange start stop values are generated within the half open interval start stop arange start stop step values are generated within the half open interval start stop with spacing between values given by step args start integer or real representing the start of the interval the interval includes this value stop integer or real representing the end of the interval the interval does not include this value except in some cases where step is not an integer and floating point round off affects the lenght of out defaults to none step integer or real represent the spacing between values for any output out this is the distance between two adjacent values out i 1 out i the default step size is 1 if step is specified as a position argument start must also be given dtype the type of the output array if dtype is not given infer the data type from the other input arguments returns tensor of evenly spaced values for floating point arguments the length of the result is ceil stop start step because of floating point overflow this rule may result in the last element of out being greater than stop examples keras ops arange 3 array 0 1 2 dtype int32 keras ops arange 3 0 array 0 1 2 dtype float32 keras ops arange 3 7 array 3 4 5 6 dtype int32 keras ops arange 3 7 2 array 3 5 dtype int32 trigonometric inverse cosine element wise the inverse of cos so that if y cos x then x arccos y args x input tensor returns tensor of the angle of the ray intersecting the unit circle at the given x coordinate in radians 0 pi example x keras ops convert_to_tensor 1 1 keras ops arccos x array 0 0 3 1415927 dtype float32 inverse hyperbolic cosine element wise arguments x input tensor returns output tensor of same shape as x example x keras ops convert_to_tensor 10 100 keras ops arccosh x array 2 993223 5 298292 dtype float32 inverse sine element wise args x input tensor returns tensor of the inverse sine of each element in x in radians and in the closed interval pi 2 pi 2 example x keras ops convert_to_tensor 1 1 0 keras ops arcsin x array 1 5707964 1 5707964 0 dtype float32 inverse hyperbolic sine element wise arguments x input tensor returns output tensor of same shape as x example x keras ops convert_to_tensor 1 1 0 keras ops arcsinh x array 0 88137364 0 88137364 0 0 dtype float32 trigonometric inverse tangent element wise args x input tensor returns tensor of the inverse tangent of each element in x in the interval pi 2 pi 2 example x keras ops convert_to_tensor 0 1 keras ops arctan x array 0 0 7853982 dtype float32 element wise arc tangent of x1 x2 choosing the quadrant correctly the quadrant i e branch is chosen so that arctan2 x1 x2 is the signed angle in radians between the ray ending at the origin and passing through the point 1 0 and the ray ending at the origin and passing through the point x2 x1 note the role reversal the y coordinate is the first function parameter the x coordinate is the second by ieee convention this function is defined for x2 0 and for either or both of x1 and x2 inf args x1 first input tensor x2 second input tensor returns tensor of angles in radians in the range pi pi examples consider four points in different quadrants x keras ops convert_to_tensor 1 1 1 1 y keras ops convert_to_tensor 1 1 1 1 keras ops arctan2 y x 180 numpy pi array 135 45 45 135 dtype float32 note the order of the parameters arctan2 is defined also when x2 0 and at several other points obtaining values in the range pi pi keras ops arctan2 keras ops array 1 1 keras ops array 0 0 array 1 5707964 1 5707964 dtype float32 keras ops arctan2 keras ops array 0 0 numpy inf keras ops array 0 0 numpy inf array 0 3 1415925 0 7853982 dtype float32 inverse hyperbolic tangent element wise arguments x input tensor returns output tensor of same shape as x returns the indices of the maximum values along an axis args x input tensor axis by default the index is into the flattened tensor otherwise along the specified axis returns tensor of indices it has the same shape as x with the dimension along axis removed example x keras ops arange 6 reshape 2 3 10 x array 10 11 12 13 14 15 dtype int32 keras ops argmax x array 5 dtype int32 keras ops argmax x axis 0 array 1 1 1 dtype int32 keras ops argmax x axis 1 array 2 2 dtype int32 returns the indices of the minium values along an axis args x input tensor axis by default the index is into the flattened tensor otherwise along the specified axis returns tensor of indices it has the same shape as x with the dimension along axis removed example x keras ops arange 6 reshape 2 3 10 x array 10 11 12 13 14 15 dtype int32 keras ops argmin x array 0 dtype int32 keras ops argmin x axis 0 array 0 0 0 dtype int32 keras ops argmin x axis 1 array 0 0 dtype int32 returns the indices that would sort a tensor args x input tensor axis axis along which to sort defaults to 1 the last axis if none the flattened tensor is used returns tensor of indices that sort x along the specified axis examples one dimensional array x keras ops array 3 1 2 keras ops argsort x array 1 2 0 dtype int32 two dimensional array x keras ops array 0 3 3 2 4 5 x array 0 3 3 2 4 5 dtype int32 keras ops argsort x axis 0 array 0 1 1 0 2 2 dtype int32 keras ops argsort x axis 1 array 0 1 1 0 0 1 dtype int32 create a tensor args x input tensor dtype the desired data type for the tensor returns a tensor examples keras ops array 1 2 3 array 1 2 3 dtype int32 keras ops array 1 2 3 dtype float32 array 1 2 3 dtype float32 np average does not support axis as tuple as declared by the docstring it only supports int or none weights can either be a 1d array of length x shape axis or of the same shape as x compute the weighted average along the specified axis args x input tensor axis integer along which to average x the default axis none will average over all of the elements of the input tensor if axis is negative it counts from the last to the first axis weights tensor of wieghts associated with the values in x each value in x contributes to the average according to its associated weight the weights array can either be 1 d in which case its length must be the size of a along the given axis or of the same shape as x if weights none default then all data in x are assumed to have a weight equal to one the 1 d calculation is avg sum a weights sum weights the only constraint on weights is that sum weights must not be 0 returns return the average along the specified axis examples data keras ops arange 1 5 data array 1 2 3 4 dtype int32 keras ops average data array 2 5 dtype float32 keras ops average keras ops arange 1 11 weights keras ops arange 10 0 1 array 4 dtype float32 data keras ops arange 6 reshape 3 2 data array 0 1 2 3 4 5 dtype int32 keras ops average data axis 1 weights keras ops array 1 4 3 4 array 0 75 2 75 4 75 dtype float32 keras ops average data weights keras ops array 1 4 3 4 traceback most recent call last valueerror axis must be specified when shapes of a and weights differ count the number of occurrences of each value in a tensor of integers args x input tensor it must be of dimension 1 and it must only contain non negative integer s weights weight tensor it must have the same length as x the default value is none if specified x is weighted by it i e if n x i out n weight i instead of the default behavior out n 1 minlength an integer the default value is 0 if specified there will be at least this number of bins in the output tensor if greater than max x 1 each value of the output at an index higher than max x is set to 0 returns 1d tensor where each element gives the number of occurrence s of its index value in x its length is the maximum between max x 1 and minlength examples x keras ops array 1 2 2 3 dtype uint8 keras ops bincount x array 0 1 2 1 dtype int32 weights x 2 weights array 0 5 1 1 1 5 dtype float64 keras ops bincount x weights weights array 0 0 5 2 1 5 dtype float64 minlength keras ops max x numpy 1 2 6 keras ops bincount x minlength minlength array 0 1 2 1 0 0 dtype int32 catch broadcasting errors for clear error messages broadcast a tensor to a new shape args x the tensor to broadcast shape the shape of the desired tensor a single integer i is interpreted as i returns a tensor with the desired shape examples x keras ops array 1 2 3 keras ops broadcast_to x 3 3 array 1 2 3 1 2 3 1 2 3 return the ceiling of the input element wise the ceil of the scalar x is the smallest integer i such that i x args x input tensor returns the ceiling of each element in x with float dtype clip limit the values in a tensor given an interval values outside the interval are clipped to the interval edges for example if an interval of 0 1 is specified values smaller than 0 become 0 and values larger than 1 become 1 args x input tensor x_min minimum value x_max maximum value returns the clipped tensor join a sequence of tensors along an existing axis args xs the sequence of tensors to concatenate axis the axis along which the tensors will be joined defaults to 0 returns the concatenated tensor returns the complex conjugate element wise the complex conjugate of a complex number is obtained by changing the sign of its imaginary part keras ops conj is a shorthand for this function args x input tensor returns the complex conjugate of each element in x shorthand for keras ops conjugate returns a copy of x args x input tensor returns a copy of x cosine element wise args x input tensor returns the corresponding cosine values hyperbolic cosine element wise arguments x input tensor returns output tensor of same shape as x counts the number of non zero values in x along the given axis if no axis is specified then all non zeros in the tensor are counted args x input tensor axis axis or tuple of axes along which to count the number of non zeros defaults to none returns int or tensor of ints examples x keras ops array 0 1 7 0 3 0 2 19 keras ops count_nonzero x 5 keras ops count_nonzero x axis 0 array 1 1 2 1 dtype int64 keras ops count_nonzero x axis 1 array 2 3 dtype int64 returns the cross product of two arrays of vectors the cross product of x1 and x2 in r 3 is a vector perpendicular to both x1 and x2 if x1 and x2 are arrays of vectors the vectors are defined by the last axis of x1 and x2 by default and these axes can have dimensions 2 or 3 where the dimension of either x1 or x2 is 2 the third component of the input vector is assumed to be zero and the cross product calculated accordingly in cases where both input vectors have dimension 2 the z component of the cross product is returned args x1 components of the first vector s x2 components of the second vector s axisa axis of x1 that defines the vector s defaults to 1 axisb axis of x2 that defines the vector s defaults to 1 axisc axis of the result containing the cross product vector s ignored if both input vectors have dimension 2 as the return is scalar by default the last axis axis if defined the axis of x1 x2 and the result that defines the vector s and cross product s overrides axisa axisb and axisc note torch backend does not support two dimensional vectors or the arguments axisa axisb and axisc use axis instead returns vector cross product s return the cumulative product of elements along a given axis args x input tensor axis axis along which the cumulative product is computed by default the input is flattened dtype dtype of returned tensor defaults to x dtype returns output tensor returns the cumulative sum of elements along a given axis args x input tensor axis axis along which the cumulative sum is computed by default the input is flattened dtype dtype of returned tensor defaults to x dtype returns output tensor extract a diagonal or construct a diagonal array args x input tensor if x is 2 d returns the k th diagonal of x if x is 1 d return a 2 d tensor with x on the k th diagonal k the diagonal to consider defaults to 0 use k 0 for diagonals above the main diagonal and k 0 for diagonals below the main diagonal returns the extracted diagonal or constructed diagonal tensor examples from keras import ops x ops arange 9 reshape 3 3 x array 0 1 2 3 4 5 6 7 8 ops diag x array 0 4 8 ops diag x k 1 array 1 5 ops diag x k 1 array 3 7 ops diag ops diag x array 0 0 0 0 4 0 0 0 8 return specified diagonals if x is 2 d returns the diagonal of x with the given offset i e the collection of elements of the form x i i offset if x has more than two dimensions the axes specified by axis1 and axis2 are used to determine the 2 d sub array whose diagonal is returned the shape of the resulting array can be determined by removing axis1 and axis2 and appending an index to the right equal to the size of the resulting diagonals args x input tensor offset offset of the diagonal from the main diagonal can be positive or negative defaults to 0 main diagonal axis1 axis to be used as the first axis of the 2 d sub arrays defaults to 0 first axis axis2 axis to be used as the second axis of the 2 d sub arrays defaults to 1 second axis returns tensor of diagonals examples from keras import ops x ops arange 4 reshape 2 2 x array 0 1 2 3 x diagonal array 0 3 x diagonal 1 array 1 x ops arange 8 reshape 2 2 2 x array 0 1 2 3 4 5 6 7 x diagonal 0 0 1 array 0 6 1 7 calculate the n th discrete difference along the given axis the first difference is given by out i a i 1 a i along the given axis higher differences are calculated by using diff recursively args a input tensor n the number of times values are differenced defaults to 1 axis axis to compute discrete difference s along defaults to 1 last axis returns tensor of diagonals examples from keras import ops x ops convert_to_tensor 1 2 4 7 0 ops diff x array 1 2 3 7 ops diff x n 2 array 1 1 10 x ops convert_to_tensor 1 3 6 10 0 5 6 8 ops diff x array 2 3 4 5 1 2 ops diff x axis 0 array 1 2 0 2 returns the indices of the bins to which each value in x belongs args x input array to be binned bins array of bins it has to be one dimensional and monotonically increasing returns output array of indices of same shape as x example x np array 0 0 1 0 3 0 1 6 bins np array 0 0 3 0 4 5 7 0 keras ops digitize x bins array 1 1 2 1 dot product of two tensors if both x1 and x2 are 1 d tensors it is inner product of vectors without complex conjugation if both x1 and x2 are 2 d tensors it is matrix multiplication if either x1 or x2 is 0 d scalar it is equivalent to x1 x2 if x1 is an n d tensor and x2 is a 1 d tensor it is a sum product over the last axis of x1 and x2 if x1 is an n d tensor and x2 is an m d tensor where m 2 it is a sum product over the last axis of x1 and the second to last axis of x2 dot x1 x2 i j k m sum a i j b k m args x1 first argument x2 second argument note torch backend does not accept 0 d tensors as arguments returns dot product of x1 and x2 compute the output shape of einsum the shape computation follows the steps below 1 find all letters in the input specs left part of and break them into two categories letters appearing more than once go to reduced_dims otherwise go to kept_dims 2 adjust reduced_dims and kept_dims based on the output spec right part of the rule is if the letter appears in the output spec then move it to kept_dims otherwise move it to reduced_dims 3 compute the target output shape if no output spec is set then the target output shape will be kept_dims e g ijk else it will be the same as output spec is a wildcard that could map shape of arbitrary length 4 for each operand in operands map the shape specified in the input spec to the output target e g if operand is of shape 2 3 4 input spec is i and output target is i jk then 2 will go the index 0 for dims not represented by any letter insert to the wildcard part for each letter in output target not appearing in input spec the dim will be 1 for broadcasting after 4 each operand should have a target shape containing only number and none 5 broadcast all shapes computed from 4 and the result is the output shape let s take an example to illustrate the steps above let s define python x kerastensor none 3 4 y kerastensor 2 4 3 z knp einsum ij kji k x y 1 reduced_dims is i j kept_dims is k 2 reduced_dims is still i j and kept_dims is k 3 output target is k 4 for x the input spec is ij and the output target is k i and j do not appear in the output target so no replacement happens and none goes to wildcard afterwards k is replaced by 1 so we get shape none 1 applying the same logic to y we get shape 2 5 broadcast none 1 and 2 and we get none 2 which is the output shape the output spec changes the rule of kept_dims and reduced_dims in short dims appearing in the output spec will be kept and dims not appearing in the output spec will be reduced in this case the input spec is just a string of letters e g ijk replace the letter with the right shape in this case the input spec has e g i j i or j shape matched by will be inserted to the position of replace all letters not yet handled with 1 for broadcasting evaluates the einstein summation convention on the operands args subscripts specifies the subscripts for summation as comma separated list of subscript labels an implicit classical einstein summation calculation is performed unless the explicit indicator is included as well as subscript labels of the precise output form operands the operands to compute the einstein sum of returns the calculation based on the einstein summation convention example from keras import ops a ops arange 25 reshape 5 5 b ops arange 5 c ops arange 6 reshape 2 3 trace of a matrix ops einsum ii a 60 ops einsum a 0 0 60 ops trace a 60 extract the diagonal ops einsum ii i a array 0 6 12 18 24 ops einsum a 0 0 0 array 0 6 12 18 24 ops diag a array 0 6 12 18 24 sum over an axis ops einsum ij i a array 10 35 60 85 110 ops einsum a 0 1 0 array 10 35 60 85 110 ops sum a axis 1 array 10 35 60 85 110 for higher dimensional tensors summing a single axis can be done with ellipsis ops einsum j a array 10 35 60 85 110 np einsum a 1 array 10 35 60 85 110 compute a matrix transpose or reorder any number of axes ops einsum ji c array 0 3 1 4 2 5 ops einsum ij ji c array 0 3 1 4 2 5 ops einsum c 1 0 array 0 3 1 4 2 5 ops transpose c array 0 3 1 4 2 5 matrix vector multiplication ops einsum ij j a b array 30 80 130 180 230 ops einsum a 0 1 b 1 array 30 80 130 180 230 ops einsum j j a b array 30 80 130 180 230 return a tensor of given shape and type filled with uninitialized data args shape shape of the empty tensor dtype desired data type of the empty tensor returns the empty tensor returns x1 x2 element wise args x1 tensor to compare x2 tensor to compare returns output tensor element wise comparison of x1 and x2 calculate the exponential of all elements in the input tensor args x input tensor returns output tensor element wise exponential of x expand the shape of a tensor insert a new axis at the axis position in the expanded tensor shape args x input tensor axis position in the expanded axes where the new axis or axes is placed returns output tensor with the number of dimensions increased calculate exp x 1 for all elements in the tensor args x input values returns output tensor element wise exponential minus one reverse the order of elements in the tensor along the given axis the shape of the tensor is preserved but the elements are reordered args x input tensor axis axis or axes along which to flip the tensor the default axis none will flip over all of the axes of the input tensor returns output tensor with entries of axis reversed return the floor of the input element wise the floor of the scalar x is the largest integer i such that i x args x input tensor returns output tensor element wise floor of x return a new tensor of given shape and type filled with fill_value args shape shape of the new tensor fill_value fill value dtype desired data type of the tensor returns output tensor return a full tensor with the same shape and type as the given tensor args x input tensor fill_value fill value dtype overrides data type of the result returns tensor of fill_value with the same shape and type as x add an implicit final ellipsis consume slice key element by element check for newaxis and ellipsis keep as many slices remain in our key omitting newaxis all frameworks follow numpy for newaxis np newaxis none at this point we need to consume a new axis from the shape python3 friendly way to compute a slice length return x key return the truth value of x1 x2 element wise args x1 first input tensor x2 second input tensor returns output tensor element wise comparison of x1 and x2 return the truth value of x1 x2 element wise args x1 first input tensor x2 second input tensor returns output tensor element wise comparison of x1 and x2 stack tensors in sequence horizontally column wise this is equivalent to concatenation along the first axis for 1 d tensors and along the second axis for all other tensors args xs sequence of tensors returns the tensor formed by stacking the given tensors return the identity tensor the identity tensor is a square tensor with ones on the main diagonal and zeros elsewhere args n number of rows and columns in the n x n output tensor dtype data type of the output tensor returns the identity tensor return the imaginary part of the complex argument args x input tensor returns the imaginary component of the complex argument return whether two tensors are element wise almost equal args x1 first input tensor x2 second input tensor returns output boolean tensor return whether a tensor is finite element wise real values are finite when they are not nan not positive infinity and not negative infinity complex values are finite when both their real and imaginary parts are finite args x input tensor returns output boolean tensor test element wise for positive or negative infinity args x input tensor returns output boolean tensor test element wise for nan and return result as a boolean tensor args x input tensor returns output boolean tensor return the truth value of x1 x2 element wise args x1 first input tensor x2 second input tensor returns output tensor element wise comparison of x1 and x2 return the truth value of x1 x2 element wise args x1 first input tensor x2 second input tensor returns output tensor element wise comparison of x1 and x2 return evenly spaced numbers over a specified interval returns num evenly spaced samples calculated over the interval start stop the endpoint of the interval can optionally be excluded args start the starting value of the sequence stop the end value of the sequence unless endpoint is set to false in that case the sequence consists of all but the last of num 1 evenly spaced samples so that stop is excluded note that the step size changes when endpoint is false num number of samples to generate defaults to 50 must be non negative endpoint if true stop is the last sample otherwise it is not included defaults to true retstep if true return samples step where step is the spacing between samples dtype the type of the output tensor axis the axis in the result to store the samples relevant only if start or stop are array like defaults to 0 note torch backend does not support axis argument returns a tensor of evenly spaced numbers if retstep is true returns samples step natural logarithm element wise args x input tensor returns output tensor element wise natural logarithm of x return the base 10 logarithm of the input tensor element wise args x input tensor returns output tensor element wise base 10 logarithm of x returns the natural logarithm of one plus the x element wise calculates log 1 x args x input tensor returns output tensor element wise natural logarithm of 1 x base 2 logarithm of x element wise args x input tensor returns output tensor element wise base 2 logarithm of x logarithm of the sum of exponentiations of the inputs calculates log exp x1 exp x2 args x1 input tensor x2 input tensor returns output tensor element wise logarithm of the sum of exponentiations of the inputs computes the element wise logical and of the given input tensors zeros are treated as false and non zeros are treated as true args x1 input tensor x2 input tensor returns output tensor element wise logical and of the inputs computes the element wise not of the given input tensor zeros are treated as false and non zeros are treated as true args x input tensor returns output tensor element wise logical not of the input computes the element wise logical or of the given input tensors zeros are treated as false and non zeros are treated as true args x1 input tensor x2 input tensor returns output tensor element wise logical or of the inputs returns numbers spaced evenly on a log scale in linear space the sequence starts at base start and ends with base stop see endpoint below args start the starting value of the sequence stop the final value of the sequence unless endpoint is false in that case num 1 values are spaced over the interval in log space of which all but the last a sequence of length num are returned num number of samples to generate defaults to 50 endpoint if true stop is the last sample otherwise it is not included defaults to true base the base of the log space defaults to 10 dtype the type of the output tensor axis the axis in the result to store the samples relevant only if start or stop are array like note torch backend does not support axis argument returns a tensor of evenly spaced samples on a log scale matrix product of two tensors if both tensors are 1 dimensional the dot product scalar is returned if either tensor is n d n 2 it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly if the first tensor is 1 d it is promoted to a matrix by prepending a 1 to its dimensions after matrix multiplication the prepended 1 is removed if the second tensor is 1 d it is promoted to a matrix by appending a 1 to its dimensions after matrix multiplication the appended 1 is removed args x1 first tensor x2 second tensor returns output tensor matrix product of the inputs return the maximum of a tensor or maximum along an axis args x input tensor axis axis or axes along which to operate by default flattened input is used keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one defaults to false initial the minimum value of an output element defaults to none returns maximum of x element wise maximum of x1 and x2 args x1 first tensor x2 second tensor returns output tensor element wise maximum of x1 and x2 compute the median along the specified axis args x input tensor axis axis or axes along which the medians are computed defaults to axis none which is to compute the median s along a flattened version of the array keepdims if this is set to true the axes which are reduce are left in the result as dimensions with size one returns the output tensor creates grids of coordinates from coordinate vectors given n 1 d tensors t0 t1 tn 1 as inputs with corresponding lengths s0 s1 sn 1 this creates an n n dimensional tensors g0 g1 gn 1 each with shape s0 sn 1 where the output gi is constructed by expanding ti to the result shape args x 1 d tensors representing the coordinates of a grid indexing cartesian xy default or matrix ij indexing of output returns sequence of n tensors example from keras import ops x ops array 1 2 3 y ops array 4 5 6 grid_x grid_y ops meshgrid x y indexing ij grid_x array 1 1 1 2 2 2 3 3 3 grid_y array 4 5 6 4 5 6 4 5 6 return the minimum of a tensor or minimum along an axis args x input tensor axis axis or axes along which to operate by default flattened input is used keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one defaults to false initial the maximum value of an output element defaults to none returns minimum of x element wise minimum of x1 and x2 args x1 first tensor x2 second tensor returns output tensor element wise minimum of x1 and x2 returns the element wise remainder of division args x1 first tensor x2 second tensor returns output tensor element wise remainder of division find the first dim unset find the first dim not being passed move axes of a tensor to new positions other axes remain in their original order args x tensor whose axes should be reordered source original positions of the axes to move these must be unique destination destinations positions for each of the original axes these must also be unique returns tensor with moved axes replace nan with zero and infinity with large finite numbers args x input data returns x with non finite values replaced return the number of dimensions of a tensor args x input tensor returns the number of dimensions in x return the indices of the elements that are non zero args x input tensor returns indices of elements that are non zero return x1 x2 element wise args x1 first input tensor x2 second input tensor returns output tensor element wise comparsion of x1 and x2 return a tensor of ones with the same shape and type of x args x input tensor dtype overrides the data type of the result returns a tensor of ones with the same shape and type as x return a tensor of zeros with the same shape and type as x args x input tensor dtype overrides the data type of the result returns a tensor of zeros with the same shape and type as x compute the outer product of two vectors given two vectors x1 and x2 the outer product is out i j x1 i x2 j args x1 first input tensor x2 second input tensor returns outer product of x1 and x2 pad a tensor args x tensor to pad pad_width number of values padded to the edges of each axis before_1 after_1 before_n after_n unique pad widths for each axis before after yields same before and after pad for each axis pad or int is a shortcut for before after pad width for all axes mode one of constant edge linear_ramp maximum mean median minimum reflect symmetric wrap empty circular defaults to constant constant_values value to pad with if mode constant defaults to 0 a valueerror is raised if not none and mode constant note torch backend only supports modes constant reflect symmetric and circular only torch backend supports circular mode note tensorflow backend only supports modes constant reflect and symmetric returns padded tensor todo torch doesn t support uint32 return the product of tensor elements over a given axis args x input tensor axis axis or axes along which a product is performed the default axis none will compute the product of all elements in the input tensor keepdims if this is set to true the axes which are reduce are left in the result as dimensions with size one dtype data type of the returned tensor returns product of elements of x over the given axis or axes compute the q th quantile s of the data along the specified axis args x input tensor q probability or sequence of probabilities for the quantiles to compute values must be between 0 and 1 inclusive axis axis or axes along which the quantiles are computed defaults to axis none which is to compute the quantile s along a flattened version of the array method a string specifies the method to use for estimating the quantile available methods are linear lower higher midpoint and nearest defaults to linear if the desired quantile lies between two data points i j linear i j i fraction where fraction is the fractional part of the index surrounded by i and j lower i higher j midpoint i j 2 nearest i or j whichever is nearest keepdims if this is set to true the axes which are reduce are left in the result as dimensions with size one returns the quantile s if q is a single probability and axis none then the result is a scalar if multiple probabilies levels are given first axis of the result corresponds to the quantiles the other axes are the axes that remain after the reduction of x return a contiguous flattened tensor a 1 d tensor containing the elements of the input is returned args x input tensor returns output tensor return the real part of the complex argument args x input tensor returns the real component of the complex argument return the reciprocal of the argument element wise calculates 1 x args x input tensor returns output tensor element wise reciprocal of x repeat each element of a tensor after themselves args x input tensor repeats the number of repetitions for each element axis the axis along which to repeat values by default use the flattened input array and return a flat output array returns output tensor gives a new shape to a tensor without changing its data args x input tensor new_shape the new shape should be compatible with the original shape one shape dimension can be 1 in which case the value is inferred from the length of the array and remaining dimensions returns the reshaped tensor roll tensor elements along a given axis elements that roll beyond the last position are re introduced at the first args x input tensor shift the number of places by which elements are shifted axis the axis along which elements are shifted by default the array is flattened before shifting after which the original shape is restored returns output tensor evenly round to the given number of decimals args x input tensor decimals number of decimal places to round to defaults to 0 returns output tensor returns a tensor with the signs of the elements of x args x input tensor returns output tensor of same shape as x trigonomeric sine element wise arguments x input tensor returns output tensor of same shape as x hyperbolic sine element wise arguments x input tensor returns output tensor of same shape as x return the number of elements in a tensor args x input tensor returns number of elements in x sorts the elements of x along a given axis in ascending order args x input tensor axis axis along which to sort if none the tensor is flattened before sorting defaults to 1 the last axis returns sorted tensor split a tensor into chunks args x input tensor indices_or_sections if an integer n the tensor will be split into n equal sections along axis if a 1 d array of sorted integers the entries indicate indices at which the tensor will be split along axis axis axis along which to split defaults to 0 note a split does not have to result in equal division when using torch backend returns a list of tensors join a sequence of tensors along a new axis the axis parameter specifies the index of the new axis in the dimensions of the result args x a sequence of tensors axis axis along which to stack defaults to 0 returns the stacked tensor compute the standard deviation along the specified axis args x input tensor axis axis along which to compute standard deviation default is to compute the standard deviation of the flattened tensor keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one returns output tensor containing the standard deviation values interchange two axes of a tensor args x input tensor axis1 first axis axis2 second axis returns a tensor with the axes swapped make sure axis is non negative take elements from a tensor along an axis args x source tensor indices the indices of the values to extract axis the axis over which to select values by default the flattened input tensor is used returns the corresponding tensor of values select values from x at the 1 d indices along the given axis args x source tensor indices the indices of the values to extract axis the axis over which to select values by default the flattened input tensor is used returns the corresponding tensor of values compute tangent element wise args x input tensor returns output tensor of same shape as x hyperbolic tangent element wise arguments x input tensor returns output tensor of same shape as x compute the tensor dot product along specified axes args x1 first tensor x2 second tensor axes if an integer n sum over the last n axes of x1 and the first n axes of x2 in order the sizes of the corresponding axes must match or a list of axes to be summed over first sequence applying to x1 second to x2 both sequences must be of the same length returns the tensor dot product of the inputs repeat x the number of times given by repeats if repeats has length d the result will have dimension of max d x ndim if x ndim d x is promoted to be d dimensional by prepending new axes if x ndim d repeats is promoted to x ndim by prepending 1 s to it args x input tensor repeats the number of repetitions of x along each axis returns the tiled output tensor return the sum along diagonals of the tensor if x is 2 d the sum along its diagonal with the given offset is returned i e the sum of elements x i i offset for all i if a has more than two dimensions then the axes specified by axis1 and axis2 are used to determine the 2 d sub arrays whose traces are returned the shape of the resulting tensor is the same as that of x with axis1 and axis2 removed args x input tensor offset offset of the diagonal from the main diagonal can be both positive and negative defaults to 0 axis1 axis to be used as the first axis of the 2 d sub arrays defaults to 0 first axis axis2 axis to be used as the second axis of the 2 d sub arrays defaults to 1 second axis returns if x is 2 d the sum of the diagonal is returned if x has larger dimensions then a tensor of sums along diagonals is returned return a tensor with ones at and below a diagonal and zeros elsewhere args n number of rows in the tensor m number of columns in the tensor k the sub diagonal at and below which the array is filled k 0 is the main diagonal while k 0 is below it and k 0 is above the default is 0 dtype data type of the returned tensor the default is float32 returns tensor with its lower triangle filled with ones and zeros elsewhere t i j 1 for j i k 0 otherwise return lower triangle of a tensor for tensors with ndim exceeding 2 tril will apply to the final two axes args x input tensor k diagonal above which to zero elements defaults to 0 the main diagonal k 0 is below it and k 0 is above it returns lower triangle of x of same shape and data type as x return upper triangle of a tensor for tensors with ndim exceeding 2 triu will apply to the final two axes args x input tensor k diagonal below which to zero elements defaults to 0 the main diagonal k 0 is below it and k 0 is above it returns upper triangle of x of same shape and data type as x return the dot product of two vectors if the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product multidimensional tensors are flattened before the dot product is taken args x1 first input tensor if complex its complex conjugate is taken before calculation of the dot product x2 second input tensor returns output tensor stack tensors in sequence vertically row wise args xs sequence of tensors returns tensor formed by stacking the given tensors return elements chosen from x1 or x2 depending on condition args condition where true yield x1 otherwise yield x2 x1 values from which to choose when condition is true x2 values from which to choose when condition is false returns a tensor with elements from x1 where condition is true and elements from x2 where condition is false subtract arguments element wise args x1 first input tensor x2 second input tensor returns output tensor element wise difference of x1 and x2 multiply arguments element wise args x1 first input tensor x2 second input tensor returns output tensor element wise product of x1 and x2 divide arguments element wise keras ops true_divide is an alias for this function args x1 first input tensor x2 second input tensor returns output tensor the quotient x1 x2 element wise alias for keras ops divide first tensor elements raised to powers from second tensor element wise args x1 the bases x2 the exponents returns output tensor the bases in x1 raised to the exponents in x2 numerical negative element wise args x input tensor returns output tensor y x return the element wise square of the input args x input tensor returns output tensor the square of x return the non negative square root of a tensor element wise args x input tensor returns output tensor the non negative square root of x remove axes of length one from x args x input tensor axis select a subset of the entries of length one in the shape returns the input tensor with all or a subset of the dimensions of length 1 removed returns a tensor with axes transposed args x input tensor axes sequence of integers permutation of the dimensions of x by default the order of the axes are reversed returns x with its axes permuted compute the arithmetic mean along the specified axes args x input tensor axis axis or axes along which the means are computed the default is to compute the mean of the flattened tensor keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one returns output tensor containing the mean values compute the variance along the specified axes args x input tensor axis axis or axes along which the variance is computed the default is to compute the variance of the flattened tensor keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one returns output tensor containing the variance follow jax s rule todo torch doesn t support uint32 sum of a tensor over the given axes args x input tensor axis axis or axes along which the sum is computed the default is to compute the sum of the flattened tensor keepdims if this is set to true the axes which are reduced are left in the result as dimensions with size one returns output tensor containing the sum return a new tensor of given shape and type filled with zeros args shape shape of the new tensor dtype desired data type of the tensor returns tensor of zeros with the given shape and dtype return a new tensor of given shape and type filled with ones args shape shape of the new tensor dtype desired data type of the tensor returns tensor of ones with the given shape and dtype return a 2 d tensor with ones on the diagonal and zeros elsewhere args n number of rows in the output m number of columns in the output if none defaults to n k index of the diagonal 0 the default refers to the main diagonal a positive value refers to an upper diagonal and a negative value to a lower diagonal dtype data type of the returned tensor returns tensor with ones on the k th diagonal and zeros elsewhere returns the largest integer smaller or equal to the division of inputs args x1 numerator x2 denominator returns output tensor y floor x1 x2 compute the truth value of x1 xor x2 element wise args x1 first input tensor x2 second input tensor returns output boolean tensor
import builtins
import re

import numpy as np

from keras import backend
from keras.api_export import keras_export
from keras.backend import KerasTensor
from keras.backend import any_symbolic_tensors
from keras.backend.common import dtypes
from keras.ops import operation_utils
from keras.ops.operation import Operation
from keras.ops.operation_utils import broadcast_shapes
from keras.ops.operation_utils import reduce_shape


def shape_equal(shape1, shape2, axis=None, allow_none=True):
    
    if len(shape1) != len(shape2):
        return False

    shape1 = list(shape1)
    shape2 = list(shape2)

    if axis is not None:
        if isinstance(axis, int):
            axis = [axis]
        for ax in axis:
            shape1[ax] = -1
            shape2[ax] = -1

    if allow_none:
        for i in range(len(shape1)):
            if shape1[i] is None:
                shape1[i] = shape2[i]
            if shape2[i] is None:
                shape2[i] = shape1[i]

    return shape1 == shape2


class Absolute(Operation):
    def call(self, x):
        return backend.numpy.absolute(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.absolute", "keras.ops.numpy.absolute"])
def absolute(x):
    
    if any_symbolic_tensors((x,)):
        return Absolute().symbolic_call(x)
    return backend.numpy.absolute(x)


class Abs(Absolute):
    pass


@keras_export(["keras.ops.abs", "keras.ops.numpy.abs"])
def abs(x):
    
    return absolute(x)


class Add(Operation):
    def call(self, x1, x2):
        return backend.numpy.add(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        output_dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        x1_sparse = getattr(x1, "sparse", False)
        x2_sparse = getattr(x2, "sparse", False)
        output_sparse = x1_sparse and x2_sparse
        return KerasTensor(
            output_shape, dtype=output_dtype, sparse=output_sparse
        )


@keras_export(["keras.ops.add", "keras.ops.numpy.add"])
def add(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Add().symbolic_call(x1, x2)
    return backend.numpy.add(x1, x2)


class All(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            self.axis = [axis]
        else:
            self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.all(
            x,
            axis=self.axis,
            keepdims=self.keepdims,
        )

    def compute_output_spec(self, x):
        return KerasTensor(
            reduce_shape(
                x.shape,
                axis=self.axis,
                keepdims=self.keepdims,
            ),
            dtype="bool",
        )


@keras_export(["keras.ops.all", "keras.ops.numpy.all"])
def all(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return All(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.all(x, axis=axis, keepdims=keepdims)


class Any(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            self.axis = [axis]
        else:
            self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.any(
            x,
            axis=self.axis,
            keepdims=self.keepdims,
        )

    def compute_output_spec(self, x):
        return KerasTensor(
            reduce_shape(
                x.shape,
                axis=self.axis,
                keepdims=self.keepdims,
            ),
            dtype="bool",
        )


@keras_export(["keras.ops.any", "keras.ops.numpy.any"])
def any(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return Any(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.any(x, axis=axis, keepdims=keepdims)


class Amax(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            axis = [axis]
        self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.amax(
            x,
            axis=self.axis,
            keepdims=self.keepdims,
        )

    def compute_output_spec(self, x):
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=x.dtype,
        )


@keras_export(["keras.ops.amax", "keras.ops.numpy.amax"])
def amax(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return Amax(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.amax(x, axis=axis, keepdims=keepdims)


class Amin(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            axis = [axis]
        self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.amin(x, axis=self.axis, keepdims=self.keepdims)

    def compute_output_spec(self, x):
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=x.dtype,
        )


@keras_export(["keras.ops.amin", "keras.ops.numpy.amin"])
def amin(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return Amin(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.amin(x, axis=axis, keepdims=keepdims)


class Append(Operation):
    def __init__(self, axis=None):
        super().__init__()
        self.axis = axis

    def call(self, x1, x2):
        return backend.numpy.append(x1, x2, axis=self.axis)

    def compute_output_spec(self, x1, x2):
        x1_shape = x1.shape
        x2_shape = x2.shape
        dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        if self.axis is None:
            if None in x1_shape or None in x2_shape:
                output_shape = [None]
            else:
                output_shape = [int(np.prod(x1_shape) + np.prod(x2_shape))]
            return KerasTensor(output_shape, dtype=dtype)

        if not shape_equal(x1_shape, x2_shape, [self.axis]):
            raise ValueError(
                "`append` requires inputs to have the same shape except the "
                f"`axis={self.axis}`, but received shape {x1_shape} and "
                f"{x2_shape}."
            )

        output_shape = list(x1_shape)
        output_shape[self.axis] = x1_shape[self.axis] + x2_shape[self.axis]
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.append", "keras.ops.numpy.append"])
def append(
    x1,
    x2,
    axis=None,
):
    
    if any_symbolic_tensors((x1, x2)):
        return Append(axis=axis).symbolic_call(x1, x2)
    return backend.numpy.append(x1, x2, axis=axis)


class Arange(Operation):
    def call(self, start, stop=None, step=1, dtype=None):
        return backend.numpy.arange(start, stop, step=step, dtype=dtype)

    def compute_output_spec(self, start, stop=None, step=1, dtype=None):
        if stop is None:
            start, stop = 0, start
        output_shape = [int(np.ceil((stop - start) / step))]
        if dtype is None:
            dtypes_to_resolve = [
                getattr(start, "dtype", type(start)),
                getattr(step, "dtype", type(step)),
            ]
            if stop is not None:
                dtypes_to_resolve.append(getattr(stop, "dtype", type(stop)))
            dtype = dtypes.result_type(*dtypes_to_resolve)
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.arange", "keras.ops.numpy.arange"])
def arange(start, stop=None, step=1, dtype=None):
    
    return backend.numpy.arange(start, stop, step=step, dtype=dtype)


class Arccos(Operation):
    def call(self, x):
        return backend.numpy.arccos(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.arccos", "keras.ops.numpy.arccos"])
def arccos(x):
    
    if any_symbolic_tensors((x,)):
        return Arccos().symbolic_call(x)
    return backend.numpy.arccos(x)


class Arccosh(Operation):
    def call(self, x):
        return backend.numpy.arccosh(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.arccosh", "keras.ops.numpy.arccosh"])
def arccosh(x):
    
    if any_symbolic_tensors((x,)):
        return Arccosh().symbolic_call(x)
    return backend.numpy.arccosh(x)


class Arcsin(Operation):
    def call(self, x):
        return backend.numpy.arcsin(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.arcsin", "keras.ops.numpy.arcsin"])
def arcsin(x):
    
    if any_symbolic_tensors((x,)):
        return Arcsin().symbolic_call(x)
    return backend.numpy.arcsin(x)


class Arcsinh(Operation):
    def call(self, x):
        return backend.numpy.arcsinh(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.arcsinh", "keras.ops.numpy.arcsinh"])
def arcsinh(x):
    
    if any_symbolic_tensors((x,)):
        return Arcsinh().symbolic_call(x)
    return backend.numpy.arcsinh(x)


class Arctan(Operation):
    def call(self, x):
        return backend.numpy.arctan(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.arctan", "keras.ops.numpy.arctan"])
def arctan(x):
    
    if any_symbolic_tensors((x,)):
        return Arctan().symbolic_call(x)
    return backend.numpy.arctan(x)


class Arctan2(Operation):
    def call(self, x1, x2):
        return backend.numpy.arctan2(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        outputs_shape = broadcast_shapes(x1_shape, x2_shape)
        x1_dtype = backend.standardize_dtype(
            getattr(x1, "dtype", backend.floatx())
        )
        x2_dtype = backend.standardize_dtype(
            getattr(x2, "dtype", backend.floatx())
        )
        dtype = dtypes.result_type(x1_dtype, x2_dtype, float)
        return KerasTensor(outputs_shape, dtype=dtype)


@keras_export(["keras.ops.arctan2", "keras.ops.numpy.arctan2"])
def arctan2(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Arctan2().symbolic_call(x1, x2)
    return backend.numpy.arctan2(x1, x2)


class Arctanh(Operation):
    def call(self, x):
        return backend.numpy.arctanh(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.arctanh", "keras.ops.numpy.arctanh"])
def arctanh(x):
    
    if any_symbolic_tensors((x,)):
        return Arctanh().symbolic_call(x)
    return backend.numpy.arctanh(x)


class Argmax(Operation):
    def __init__(self, axis=None):
        super().__init__()
        self.axis = axis

    def call(self, x):
        return backend.numpy.argmax(x, axis=self.axis)

    def compute_output_spec(self, x):
        if self.axis is None:
            return KerasTensor([], dtype="int32")
        return KerasTensor(
            reduce_shape(x.shape, axis=[self.axis]), dtype="int32"
        )


@keras_export(["keras.ops.argmax", "keras.ops.numpy.argmax"])
def argmax(x, axis=None):
    
    if any_symbolic_tensors((x,)):
        return Argmax(axis=axis).symbolic_call(x)
    return backend.numpy.argmax(x, axis=axis)


class Argmin(Operation):
    def __init__(self, axis=None):
        super().__init__()
        self.axis = axis

    def call(self, x):
        return backend.numpy.argmin(x, axis=self.axis)

    def compute_output_spec(self, x):
        if self.axis is None:
            return KerasTensor([], dtype="int32")
        return KerasTensor(
            reduce_shape(x.shape, axis=[self.axis]), dtype="int32"
        )


@keras_export(["keras.ops.argmin", "keras.ops.numpy.argmin"])
def argmin(x, axis=None):
    
    if any_symbolic_tensors((x,)):
        return Argmin(axis=axis).symbolic_call(x)
    return backend.numpy.argmin(x, axis=axis)


class Argsort(Operation):
    def __init__(self, axis=-1):
        super().__init__()
        self.axis = axis

    def call(self, x):
        return backend.numpy.argsort(x, axis=self.axis)

    def compute_output_spec(self, x):
        if self.axis is None:
            return KerasTensor([int(np.prod(x.shape))], dtype="int32")
        return KerasTensor(x.shape, dtype="int32")


@keras_export(["keras.ops.argsort", "keras.ops.numpy.argsort"])
def argsort(x, axis=-1):
    
    if any_symbolic_tensors((x,)):
        return Argsort(axis=axis).symbolic_call(x)
    return backend.numpy.argsort(x, axis=axis)


class Array(Operation):
    def call(self, x, dtype=None):
        return backend.numpy.array(x, dtype=dtype)

    def compute_output_spec(self, x, dtype=None):
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.array", "keras.ops.numpy.array"])
def array(x, dtype=None):
    
    if any_symbolic_tensors((x,)):
        return Array().symbolic_call(x, dtype=dtype)
    return backend.numpy.array(x, dtype=dtype)


class Average(Operation):
    def __init__(self, axis=None):
        super().__init__()
        
        
        self.axis = axis

    def call(self, x, weights=None):
        return backend.numpy.average(x, weights=weights, axis=self.axis)

    def compute_output_spec(self, x, weights=None):
        dtypes_to_resolve = [getattr(x, "dtype", type(x)), float]
        if weights is not None:
            shape_match = shape_equal(x.shape, weights.shape, allow_none=True)
            if self.axis is not None:
                shape_match_on_axis = shape_equal(
                    [x.shape[self.axis]], weights.shape, allow_none=True
                )
            dtypes_to_resolve.append(getattr(weights, "dtype", type(weights)))
        dtype = dtypes.result_type(*dtypes_to_resolve)
        if self.axis is None:
            if weights is None or shape_match:
                return KerasTensor([], dtype=dtype)
            else:
                raise ValueError(
                    "`weights` must have the same shape as `x` when "
                    f"`axis=None`, but received `weights.shape={weights.shape}`"
                    f" and `x.shape={x.shape}`."
                )

        if weights is None or shape_match_on_axis or shape_match:
            return KerasTensor(
                reduce_shape(x.shape, axis=[self.axis]), dtype=dtype
            )
        else:
            
            
            raise ValueError(
                "`weights` must have the same size as `x` at "
                f"`axis={self.axis}` but received "
                f"`weights.shape={weights.shape}` while x.shape at "
                f"`{self.axis}` is `{x.shape[self.axis]}`."
            )


@keras_export(["keras.ops.average", "keras.ops.numpy.average"])
def average(x, axis=None, weights=None):
    
    if any_symbolic_tensors((x,)):
        return Average(axis=axis).symbolic_call(x, weights=weights)
    return backend.numpy.average(x, weights=weights, axis=axis)


class Bincount(Operation):
    def __init__(self, weights=None, minlength=0):
        super().__init__()
        self.weights = weights
        self.minlength = minlength

    def call(self, x):
        return backend.numpy.bincount(
            x, weights=self.weights, minlength=self.minlength
        )

    def compute_output_spec(self, x):
        dtypes_to_resolve = [x.dtype]
        if self.weights is not None:
            weights = backend.convert_to_tensor(self.weights)
            dtypes_to_resolve.append(weights.dtype)
            dtype = dtypes.result_type(*dtypes_to_resolve)
        else:
            dtype = "int32"
        return KerasTensor(list(x.shape[:-1]) + [None], dtype=dtype)


@keras_export(["keras.ops.bincount", "keras.ops.numpy.bincount"])
def bincount(x, weights=None, minlength=0):
    
    if any_symbolic_tensors((x,)):
        return Bincount(weights=weights, minlength=minlength).symbolic_call(x)
    return backend.numpy.bincount(x, weights=weights, minlength=minlength)


class BroadcastTo(Operation):
    def __init__(self, shape):
        super().__init__()
        self.shape = shape

    def call(self, x):
        return backend.numpy.broadcast_to(x, self.shape)

    def compute_output_spec(self, x):
        
        broadcast_shapes(x.shape, self.shape)
        return KerasTensor(self.shape, dtype=x.dtype)


@keras_export(
    [
        "keras.ops.broadcast_to",
        "keras.ops.numpy.broadcast_to",
    ]
)
def broadcast_to(x, shape):
    
    if any_symbolic_tensors((x,)):
        return BroadcastTo(shape=shape).symbolic_call(x)
    return backend.numpy.broadcast_to(x, shape)


class Ceil(Operation):
    def call(self, x):
        return backend.numpy.ceil(x)

    def compute_output_spec(self, x):
        if backend.standardize_dtype(x.dtype) == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(x.dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.ceil", "keras.ops.numpy.ceil"])
def ceil(x):
    
    if any_symbolic_tensors((x,)):
        return Ceil().symbolic_call(x)
    return backend.numpy.ceil(x)


class Clip(Operation):
    def __init__(self, x_min, x_max):
        super().__init__()
        self.x_min = x_min
        self.x_max = x_max

    def call(self, x):
        return backend.numpy.clip(x, self.x_min, self.x_max)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(x.dtype)
        if dtype == "bool":
            dtype = "int32"
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.clip", "keras.ops.numpy.clip"])
def clip(x, x_min, x_max):
    
    if any_symbolic_tensors((x,)):
        return Clip(x_min, x_max).symbolic_call(x)
    return backend.numpy.clip(x, x_min, x_max)


class Concatenate(Operation):
    def __init__(self, axis=0):
        super().__init__()
        if axis is None:
            raise ValueError("`axis` cannot be None for `concatenate`.")
        self.axis = axis

    def call(self, xs):
        return backend.numpy.concatenate(xs, axis=self.axis)

    def compute_output_spec(self, xs):
        first_shape = xs[0].shape
        total_size_on_axis = 0
        all_sparse = True
        dtypes_to_resolve = []
        for x in xs:
            if not shape_equal(
                x.shape, first_shape, axis=[self.axis], allow_none=True
            ):
                raise ValueError(
                    "Every value in `xs` must have the same shape except on "
                    f"the `axis` dim. But found element of shape {x.shape}, "
                    f"which is different from the first element's "
                    f"shape {first_shape}."
                )
            if total_size_on_axis is None or x.shape[self.axis] is None:
                total_size_on_axis = None
            else:
                total_size_on_axis += x.shape[self.axis]
            all_sparse = all_sparse and getattr(x, "sparse", False)
            dtypes_to_resolve.append(getattr(x, "dtype", type(x)))
        output_shape = list(first_shape)
        output_shape[self.axis] = total_size_on_axis
        dtype = dtypes.result_type(*dtypes_to_resolve)
        return KerasTensor(output_shape, dtype=dtype, sparse=all_sparse)


@keras_export(
    [
        "keras.ops.concatenate",
        "keras.ops.numpy.concatenate",
    ]
)
def concatenate(xs, axis=0):
    
    if any_symbolic_tensors(xs):
        return Concatenate(axis=axis).symbolic_call(xs)
    return backend.numpy.concatenate(xs, axis=axis)


class Conjugate(Operation):
    def call(self, x):
        return backend.numpy.conjugate(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.conjugate", "keras.ops.numpy.conjugate"])
def conjugate(x):
    
    if any_symbolic_tensors((x,)):
        return Conjugate().symbolic_call(x)
    return backend.numpy.conjugate(x)


class Conj(Conjugate):
    pass


@keras_export(["keras.ops.conj", "keras.ops.numpy.conj"])
def conj(x):
    
    return conjugate(x)


class Copy(Operation):
    def call(self, x):
        return backend.numpy.copy(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.copy", "keras.ops.numpy.copy"])
def copy(x):
    
    if any_symbolic_tensors((x,)):
        return Copy().symbolic_call(x)
    return backend.numpy.copy(x)


class Cos(Operation):
    def call(self, x):
        return backend.numpy.cos(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.cos", "keras.ops.numpy.cos"])
def cos(x):
    
    if any_symbolic_tensors((x,)):
        return Cos().symbolic_call(x)
    return backend.numpy.cos(x)


class Cosh(Operation):
    def call(self, x):
        return backend.numpy.cosh(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.cosh", "keras.ops.numpy.cosh"])
def cosh(x):
    
    if any_symbolic_tensors((x,)):
        return Cosh().symbolic_call(x)
    return backend.numpy.cosh(x)


class CountNonzero(Operation):
    def __init__(self, axis=None):
        super().__init__()
        if isinstance(axis, int):
            self.axis = (axis,)
        else:
            self.axis = axis

    def call(self, x):
        return backend.numpy.count_nonzero(x, axis=self.axis)

    def compute_output_spec(self, x):
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis),
            dtype="int32",
        )


@keras_export(
    [
        "keras.ops.count_nonzero",
        "keras.ops.numpy.count_nonzero",
    ]
)
def count_nonzero(x, axis=None):
    
    if any_symbolic_tensors((x,)):
        return CountNonzero(axis=axis).symbolic_call(x)
    return backend.numpy.count_nonzero(x, axis=axis)


class Cross(Operation):
    def __init__(self, axisa=-1, axisb=-1, axisc=-1, axis=None):
        super().__init__()
        if axis is not None:
            self.axisa = axis
            self.axisb = axis
            self.axisc = axis
        else:
            self.axisa = axisa
            self.axisb = axisb
            self.axisc = axisc

    def call(self, x1, x2):
        return backend.numpy.cross(x1, x2, self.axisa, self.axisb, self.axisc)

    def compute_output_spec(self, x1, x2):
        x1_shape = list(x1.shape)
        x2_shape = list(x2.shape)

        x1_value_size = x1_shape[self.axisa]
        x2_value_size = x2_shape[self.axisa]
        del x1_shape[self.axisa]
        del x2_shape[self.axisb]
        output_shape = broadcast_shapes(x1_shape, x2_shape)

        if x1_value_size is not None and x1_value_size not in (2, 3):
            raise ValueError(
                "`x1`'s dim on `axis={axisa}` must be either 2 or 3, but "
                f"received: {x1_value_size}"
            )
        if x2_value_size is not None and x2_value_size not in (2, 3):
            raise ValueError(
                "`x2`'s dim on `axis={axisb}` must be either 2 or 3, but "
                f"received: {x2_value_size}"
            )

        if x1_value_size == 3 or x2_value_size == 3:
            value_size = [3]
        else:
            value_size = []

        output_shape = (
            output_shape[: self.axisc] + value_size + output_shape[self.axisc :]
        )

        dtype = dtypes.result_type(x1.dtype, x2.dtype)
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.cross", "keras.ops.numpy.cross"])
def cross(x1, x2, axisa=-1, axisb=-1, axisc=-1, axis=None):
    
    if any_symbolic_tensors((x1, x2)):
        return Cross(
            axisa=axisa, axisb=axisb, axisc=axisc, axis=axis
        ).symbolic_call(x1, x2)
    return backend.numpy.cross(
        x1,
        x2,
        axisa=axisa,
        axisb=axisb,
        axisc=axisc,
        axis=axis,
    )


class Cumprod(Operation):
    def __init__(self, axis=None, dtype=None):
        super().__init__()
        self.axis = axis
        self.dtype = dtype

    def call(self, x):
        return backend.numpy.cumprod(x, axis=self.axis, dtype=self.dtype)

    def compute_output_spec(self, x):
        if self.axis is None:
            if None in x.shape:
                output_shape = (None,)
            else:
                output_shape = (int(np.prod(x.shape)),)
        else:
            output_shape = x.shape
        output_dtype = backend.standardize_dtype(self.dtype or x.dtype)
        if output_dtype == "bool":
            output_dtype = "int32"
        return KerasTensor(output_shape, output_dtype)


@keras_export(["keras.ops.cumprod", "keras.ops.numpy.cumprod"])
def cumprod(x, axis=None, dtype=None):
    
    return Cumprod(axis=axis, dtype=dtype)(x)


class Cumsum(Operation):
    def __init__(self, axis=None, dtype=None):
        super().__init__()
        self.axis = axis
        self.dtype = dtype

    def call(self, x):
        return backend.numpy.cumsum(x, axis=self.axis, dtype=self.dtype)

    def compute_output_spec(self, x):
        if self.axis is None:
            if None in x.shape:
                output_shape = (None,)
            else:
                output_shape = (int(np.prod(x.shape)),)
        else:
            output_shape = x.shape
        output_dtype = backend.standardize_dtype(self.dtype or x.dtype)
        if output_dtype == "bool":
            output_dtype = "int32"
        return KerasTensor(output_shape, output_dtype)


@keras_export(["keras.ops.cumsum", "keras.ops.numpy.cumsum"])
def cumsum(x, axis=None, dtype=None):
    
    return Cumsum(axis=axis, dtype=dtype)(x)


class Diag(Operation):
    def __init__(self, k=0):
        super().__init__()
        self.k = k

    def call(self, x):
        return backend.numpy.diag(x, k=self.k)

    def compute_output_spec(self, x):
        x_shape = x.shape
        if len(x_shape) == 1:
            if x_shape[0] is None:
                output_shape = [None, None]
            else:
                output_shape = [
                    x_shape[0] + int(np.abs(self.k)),
                    x_shape[0] + int(np.abs(self.k)),
                ]
        elif len(x_shape) == 2:
            if None in x_shape:
                output_shape = [None]
            else:
                shorter_side = np.minimum(x_shape[0], x_shape[1])
                if self.k > 0:
                    remaining = x_shape[1] - self.k
                else:
                    remaining = x_shape[0] + self.k
                output_shape = [
                    int(np.maximum(0, np.minimum(remaining, shorter_side)))
                ]
        else:
            raise ValueError(
                f"`x` must be 1-D or 2-D, but received shape {x.shape}."
            )
        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(["keras.ops.diag", "keras.ops.numpy.diag"])
def diag(x, k=0):
    
    if any_symbolic_tensors((x,)):
        return Diag(k=k).symbolic_call(x)
    return backend.numpy.diag(x, k=k)


class Diagonal(Operation):
    def __init__(self, offset=0, axis1=0, axis2=1):
        super().__init__()
        self.offset = offset
        self.axis1 = axis1
        self.axis2 = axis2

    def call(self, x):
        return backend.numpy.diagonal(
            x,
            offset=self.offset,
            axis1=self.axis1,
            axis2=self.axis2,
        )

    def compute_output_spec(self, x):
        x_shape = list(x.shape)
        if len(x_shape) < 2:
            raise ValueError(
                "`diagonal` requires an array of at least two dimensions, but "
                "`x` is of shape {x.shape}."
            )

        shape_2d = [x_shape[self.axis1], x_shape[self.axis2]]
        x_shape[self.axis1] = -1
        x_shape[self.axis2] = -1
        output_shape = list(filter((-1).__ne__, x_shape))
        if None in shape_2d:
            diag_shape = [None]
        else:
            shorter_side = np.minimum(shape_2d[0], shape_2d[1])
            if self.offset > 0:
                remaining = shape_2d[1] - self.offset
            else:
                remaining = shape_2d[0] + self.offset
            diag_shape = [
                int(np.maximum(0, np.minimum(remaining, shorter_side)))
            ]
        output_shape = output_shape + diag_shape
        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(["keras.ops.diagonal", "keras.ops.numpy.diagonal"])
def diagonal(x, offset=0, axis1=0, axis2=1):
    
    if any_symbolic_tensors((x,)):
        return Diagonal(
            offset=offset,
            axis1=axis1,
            axis2=axis2,
        ).symbolic_call(x)
    return backend.numpy.diagonal(
        x,
        offset=offset,
        axis1=axis1,
        axis2=axis2,
    )


class Diff(Operation):
    def __init__(self, n=1, axis=-1):
        super().__init__()
        self.n = n
        self.axis = axis

    def call(self, a):
        return backend.numpy.diff(a, n=self.n, axis=self.axis)

    def compute_output_spec(self, a):
        shape = list(a.shape)
        size = shape[self.axis]
        if size is not None:
            shape[self.axis] = builtins.max(size - self.n, 0)
        return KerasTensor(shape, dtype=a.dtype)


@keras_export(["keras.ops.diff", "keras.ops.numpy.diff"])
def diff(a, n=1, axis=-1):
    
    return Diff(n=n, axis=axis)(a)


class Digitize(Operation):
    def call(self, x, bins):
        return backend.numpy.digitize(x, bins)

    def compute_output_spec(self, x, bins):
        bins_shape = bins.shape
        if len(bins_shape) > 1:
            raise ValueError(
                f"`bins` must be a 1D array. Received: bins={bins} "
                f"with shape bins.shape={bins_shape}"
            )
        return KerasTensor(x.shape, dtype="int32")


@keras_export(["keras.ops.digitize", "keras.ops.numpy.digitize"])
def digitize(x, bins):
    
    if any_symbolic_tensors((x, bins)):
        return Digitize().symbolic_call(x, bins)
    return backend.numpy.digitize(x, bins)


class Dot(Operation):
    def call(self, x1, x2):
        return backend.numpy.dot(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = list(getattr(x1, "shape", []))
        x2_shape = list(getattr(x2, "shape", []))
        dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        if x1_shape == [] or x2_shape == []:
            return multiply(x1, x2)
        if len(x1_shape) == 1 and len(x2_shape) == 1:
            return KerasTensor([], dtype=dtype)
        if len(x2_shape) == 1:
            if x1_shape[-1] != x2_shape[0]:
                raise ValueError(
                    "Shape must match on the last axis of `x1` and `x2` when "
                    "`x1` is N-d array while `x2` is 1-D, but receive shape "
                    f"`x1.shape={x1.shape}` and x2.shape=`{x2.shape}`."
                )
            return KerasTensor(x1_shape[:-1], dtype=dtype)

        if (
            x1_shape[-1] is None
            or x2_shape[-2] is None
            or x1_shape[-1] == x2_shape[-2]
        ):
            del x1_shape[-1]
            del x2_shape[-2]
            return KerasTensor(x1_shape + x2_shape, dtype=dtype)

        raise ValueError(
            "Shape must match on the last axis of `x1` and second last "
            "axis of `x2` when `x1` is N-d array while `x2` is M-D, but "
            f"received `x1.shape={x1.shape}` and x2.shape=`{x2.shape}`."
        )


@keras_export(["keras.ops.dot", "keras.ops.numpy.dot"])
def dot(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Dot().symbolic_call(x1, x2)
    return backend.numpy.dot(x1, x2)


class Einsum(Operation):
    def __init__(self, subscripts):
        super().__init__()
        self.subscripts = subscripts

    def call(self, *operands):
        return backend.numpy.einsum(self.subscripts, *operands)

    def compute_output_spec(self, *operands):
        
        split_subscripts = self.subscripts.split("->")
        if len(split_subscripts) > 2:
            raise ValueError(
                "At most one '->' is supported in `einsum` subscripts, but "
                f"received {self.subscripts}."
            )
        if len(split_subscripts) == 2:
            subscripts = split_subscripts[0]
            output_spec = split_subscripts[1]
        else:
            subscripts = self.subscripts
            output_spec = None
        input_specs = subscripts.split(",")
        if len(input_specs) != len(operands):
            raise ValueError(
                f"Number of operands ({len(operands)}) does not match the "
                f"number of input specs ({len(input_specs)}) in `einsum`, "
                f"received subscripts={self.subscripts}."
            )
        reduced_dims = set()
        kept_dims = set()
        for s in subscripts:
            if not s.isalpha():
                continue
            if s not in reduced_dims and s not in kept_dims:
                kept_dims.add(s)
            elif s in kept_dims:
                kept_dims.remove(s)
                reduced_dims.add(s)

        if output_spec is not None:
            
            
            
            kept_dims_copy = kept_dims.copy()
            reduced_dims_copy = reduced_dims.copy()
            for dim in kept_dims:
                if dim not in output_spec:
                    kept_dims_copy.remove(dim)
                    reduced_dims_copy.add(dim)
            for dim in reduced_dims:
                if dim in output_spec:
                    reduced_dims_copy.remove(dim)
                    kept_dims_copy.add(dim)
            kept_dims = kept_dims_copy
            reduced_dims = reduced_dims_copy

        reduced_dims = sorted(reduced_dims)
        kept_dims = sorted(kept_dims)

        if output_spec is None:
            target_broadcast_spec = "..." + "".join(kept_dims)
        else:
            target_broadcast_spec = output_spec

        expanded_operands_shapes = []
        for x, spec in zip(operands, input_specs):
            x_shape = getattr(x, "shape", [])
            x_shape = [-1 if size is None else size for size in x_shape]
            split_spec = spec.split("...")
            expanded_shape = target_broadcast_spec
            if len(split_spec) == 1:
                
                
                if len(x_shape) != len(split_spec[0]):
                    raise ValueError(
                        "Number of dimensions in the subscript does not "
                        "match the number of dimensions in the operand, "
                        f"received subscript `{spec}` and operand of shape "
                        f"{x_shape}."
                    )
                for size, s in zip(x_shape, split_spec[0]):
                    
                    expanded_shape = expanded_shape.replace(s, str(size) + " ")
                expanded_shape = expanded_shape.replace("...", "")
            else:
                
                
                for i in range(len(split_spec[0])):
                    expanded_shape = expanded_shape.replace(
                        split_spec[0][i], str(x_shape[i]) + " "
                    )
                for i in range(len(split_spec[1])):
                    expanded_shape = expanded_shape.replace(
                        split_spec[1][-i - 1], str(x_shape[-i - 1]) + " "
                    )
                
                
                wildcard_shape_start_index = len(split_spec[0])
                wildcard_shape_end_index = (
                    len(x_shape)
                    if len(split_spec[1]) == 0
                    else -len(split_spec[1])
                )
                wildcard_shape = x_shape[
                    wildcard_shape_start_index:wildcard_shape_end_index
                ]
                wildcard_shape_str = (
                    " ".join([str(size) for size in wildcard_shape]) + " "
                )
                expanded_shape = expanded_shape.replace(
                    "...", wildcard_shape_str
                )
            
            expanded_shape = re.sub("[a-z]", "1 ", expanded_shape)
            expanded_shape = expanded_shape.split()
            expanded_shape = [
                None if size == "-1" else int(size) for size in expanded_shape
            ]
            expanded_operands_shapes.append(expanded_shape)

        output_shape = expanded_operands_shapes[0]
        for shape in expanded_operands_shapes[1:]:
            output_shape = broadcast_shapes(output_shape, shape)
        dtypes_to_resolve = []
        for x in operands:
            dtypes_to_resolve.append(getattr(x, "dtype", type(x)))
        dtype = dtypes.result_type(*dtypes_to_resolve)
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.einsum", "keras.ops.numpy.einsum"])
def einsum(subscripts, *operands):
    
    if any_symbolic_tensors(operands):
        return Einsum(subscripts).symbolic_call(*operands)
    return backend.numpy.einsum(subscripts, *operands)


class Empty(Operation):
    def call(self, shape, dtype=None):
        return backend.numpy.empty(shape, dtype=dtype)

    def compute_output_spec(self, shape, dtype=None):
        dtype = dtype or backend.floatx()
        return KerasTensor(shape, dtype=dtype)


@keras_export(["keras.ops.empty", "keras.ops.numpy.empty"])
def empty(shape, dtype=None):
    
    return backend.numpy.empty(shape, dtype=dtype)


class Equal(Operation):
    def call(self, x1, x2):
        return backend.numpy.equal(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(["keras.ops.equal", "keras.ops.numpy.equal"])
def equal(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Equal().symbolic_call(x1, x2)
    return backend.numpy.equal(x1, x2)


class Exp(Operation):
    def call(self, x):
        return backend.numpy.exp(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(x.dtype)
        if "int" in dtype or dtype == "bool":
            dtype = backend.floatx()
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.exp", "keras.ops.numpy.exp"])
def exp(x):
    
    if any_symbolic_tensors((x,)):
        return Exp().symbolic_call(x)
    return backend.numpy.exp(x)


class ExpandDims(Operation):
    def __init__(self, axis):
        super().__init__()
        if isinstance(axis, list):
            raise ValueError(
                "The `axis` argument to `expand_dims` should be an integer, "
                f"but received a list: {axis}."
            )
        self.axis = axis

    def call(self, x):
        return backend.numpy.expand_dims(x, self.axis)

    def compute_output_spec(self, x):
        output_shape = operation_utils.compute_expand_dims_output_shape(
            x.shape, self.axis
        )
        sparse = getattr(x, "sparse", False)
        return KerasTensor(output_shape, dtype=x.dtype, sparse=sparse)


@keras_export(
    [
        "keras.ops.expand_dims",
        "keras.ops.numpy.expand_dims",
    ]
)
def expand_dims(x, axis):
    
    if any_symbolic_tensors((x,)):
        return ExpandDims(axis=axis).symbolic_call(x)
    return backend.numpy.expand_dims(x, axis)


class Expm1(Operation):
    def call(self, x):
        return backend.numpy.expm1(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(x.dtype)
        if "int" in dtype or dtype == "bool":
            dtype = backend.floatx()
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.expm1", "keras.ops.numpy.expm1"])
def expm1(x):
    
    if any_symbolic_tensors((x,)):
        return Expm1().symbolic_call(x)
    return backend.numpy.expm1(x)


class Flip(Operation):
    def __init__(self, axis=None):
        super().__init__()
        self.axis = axis

    def call(self, x):
        return backend.numpy.flip(x, axis=self.axis)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, dtype=x.dtype)


@keras_export(["keras.ops.flip", "keras.ops.numpy.flip"])
def flip(x, axis=None):
    
    if any_symbolic_tensors((x,)):
        return Flip(axis=axis).symbolic_call(x)
    return backend.numpy.flip(x, axis=axis)


class Floor(Operation):
    def call(self, x):
        return backend.numpy.floor(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        dtype = (
            backend.floatx()
            if backend.standardize_dtype(x.dtype) == "int64"
            else dtypes.result_type(x.dtype, float)
        )
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.floor", "keras.ops.numpy.floor"])
def floor(x):
    
    if any_symbolic_tensors((x,)):
        return Floor().symbolic_call(x)
    return backend.numpy.floor(x)


class Full(Operation):
    def call(self, shape, fill_value, dtype=None):
        return backend.numpy.full(shape, fill_value, dtype=dtype)

    def compute_output_spec(self, shape, fill_value, dtype=None):
        dtype = dtype or backend.floatx()
        return KerasTensor(shape, dtype=dtype)


@keras_export(["keras.ops.full", "keras.ops.numpy.full"])
def full(shape, fill_value, dtype=None):
    
    return backend.numpy.full(shape, fill_value, dtype=dtype)


class FullLike(Operation):
    def call(self, x, fill_value, dtype=None):
        return backend.numpy.full_like(x, fill_value, dtype=dtype)

    def compute_output_spec(self, x, fill_value, dtype=None):
        dtype = dtype or x.dtype
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.full_like", "keras.ops.numpy.full_like"])
def full_like(x, fill_value, dtype=None):
    
    if any_symbolic_tensors((x,)):
        return FullLike().symbolic_call(x, fill_value, dtype=dtype)
    return backend.numpy.full_like(x, fill_value, dtype=dtype)


class GetItem(Operation):
    def call(self, x, key):
        if isinstance(key, list):
            key = tuple(key)
        return x[key]

    def compute_output_spec(self, x, key):
        remaining_shape = list(x.shape)
        new_shape = []
        if isinstance(key, int):
            remaining_key = [key]
        elif isinstance(key, tuple):
            remaining_key = list(key)
        else:
            raise ValueError(
                f"Unsupported key type for array slice. Recieved: `{key}`"
            )
        num_ellipses = remaining_key.count(Ellipsis)
        if num_ellipses > 1:
            raise ValueError(
                f"Slice should only have one ellipsis. Recieved: `{key}`"
            )
        elif num_ellipses == 0:
            
            remaining_key.append(Ellipsis)
        
        while True:
            if not remaining_key:
                break
            subkey = remaining_key.pop(0)
            
            if subkey == Ellipsis:
                
                needed = len(remaining_key) - remaining_key.count(np.newaxis)
                consumed = len(remaining_shape) - needed
                new_shape += remaining_shape[:consumed]
                remaining_shape = remaining_shape[consumed:]
                continue
            
            if subkey == np.newaxis:
                new_shape.append(1)
                continue
            
            if not remaining_shape:
                raise ValueError(
                    f"Array has shape {x.shape} but slice "
                    f"has to many indices. Recieved: `{key}`"
                )
            length = remaining_shape.pop(0)
            if isinstance(subkey, int):
                if length is not None:
                    index = subkey if subkey >= 0 else subkey + length
                    if index < 0 or index >= length:
                        raise ValueError(
                            f"Array has shape {x.shape} but out-of-bounds "
                            f"index {key} was requested."
                        )
            elif isinstance(subkey, slice):
                if length is not None:
                    
                    new_length = len(range(*subkey.indices(length)))
                    new_shape.append(new_length)
                else:
                    new_shape.append(length)
            else:
                raise ValueError(
                    f"Unsupported key type for array slice. Recieved: `{key}`"
                )
        return KerasTensor(tuple(new_shape), dtype=x.dtype)


@keras_export(["keras.ops.get_item", "keras.ops.numpy.get_item"])
def get_item(x, key):
    
    if any_symbolic_tensors((x,)):
        return GetItem().symbolic_call(x, key)
    return x[key]


class Greater(Operation):
    def call(self, x1, x2):
        return backend.numpy.greater(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(["keras.ops.greater", "keras.ops.numpy.greater"])
def greater(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Greater().symbolic_call(x1, x2)
    return backend.numpy.greater(x1, x2)


class GreaterEqual(Operation):
    def call(self, x1, x2):
        return backend.numpy.greater_equal(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(
    [
        "keras.ops.greater_equal",
        "keras.ops.numpy.greater_equal",
    ]
)
def greater_equal(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return GreaterEqual().symbolic_call(x1, x2)
    return backend.numpy.greater_equal(x1, x2)


class Hstack(Operation):
    def call(self, xs):
        return backend.numpy.hstack(xs)

    def compute_output_spec(self, xs):
        first_shape = xs[0].shape
        total_size_on_axis = 0
        dtypes_to_resolve = []
        for x in xs:
            if not shape_equal(x.shape, first_shape, axis=[1], allow_none=True):
                raise ValueError(
                    "Every value in `xs` must have the same shape except on "
                    f"the `axis` dim. But found element of shape {x.shape}, "
                    f"which is different from the first element's "
                    f"shape {first_shape}."
                )
            if total_size_on_axis is None or x.shape[1] is None:
                total_size_on_axis = None
            else:
                total_size_on_axis += x.shape[1]
            dtypes_to_resolve.append(getattr(x, "dtype", type(x)))
        output_shape = list(first_shape)
        output_shape[1] = total_size_on_axis
        dtype = dtypes.result_type(*dtypes_to_resolve)
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.hstack", "keras.ops.numpy.hstack"])
def hstack(xs):
    
    if any_symbolic_tensors((xs,)):
        return Hstack().symbolic_call(xs)
    return backend.numpy.hstack(xs)


class Identity(Operation):
    def call(self, n, dtype=None):
        return backend.numpy.identity(n, dtype=dtype)

    def compute_output_spec(self, n, dtype=None):
        dtype = dtype or backend.floatx()
        return KerasTensor([n, n], dtype=dtype)


@keras_export(["keras.ops.identity", "keras.ops.numpy.identity"])
def identity(n, dtype=None):
    
    return backend.numpy.identity(n, dtype=dtype)


class Imag(Operation):
    def call(self, x):
        return backend.numpy.imag(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.imag", "keras.ops.numpy.imag"])
def imag(x):
    
    if any_symbolic_tensors((x,)):
        return Imag().symbolic_call(x)
    return backend.numpy.imag(x)


class Isclose(Operation):
    def call(self, x1, x2):
        return backend.numpy.isclose(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(["keras.ops.isclose", "keras.ops.numpy.isclose"])
def isclose(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Isclose().symbolic_call(x1, x2)
    return backend.numpy.isclose(x1, x2)


class Isfinite(Operation):
    def call(self, x):
        return backend.numpy.isfinite(x)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, dtype="bool")


@keras_export(["keras.ops.isfinite", "keras.ops.numpy.isfinite"])
def isfinite(x):
    
    if any_symbolic_tensors((x,)):
        return Isfinite().symbolic_call(x)
    return backend.numpy.isfinite(x)


class Isinf(Operation):
    def call(self, x):
        return backend.numpy.isinf(x)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, dtype="bool")


@keras_export(["keras.ops.isinf", "keras.ops.numpy.isinf"])
def isinf(x):
    
    if any_symbolic_tensors((x,)):
        return Isinf().symbolic_call(x)
    return backend.numpy.isinf(x)


class Isnan(Operation):
    def call(self, x):
        return backend.numpy.isnan(x)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, dtype="bool")


@keras_export(["keras.ops.isnan", "keras.ops.numpy.isnan"])
def isnan(x):
    
    if any_symbolic_tensors((x,)):
        return Isnan().symbolic_call(x)
    return backend.numpy.isnan(x)


class Less(Operation):
    def call(self, x1, x2):
        return backend.numpy.less(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(["keras.ops.less", "keras.ops.numpy.less"])
def less(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Less().symbolic_call(x1, x2)
    return backend.numpy.less(x1, x2)


class LessEqual(Operation):
    def call(self, x1, x2):
        return backend.numpy.less_equal(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(
    [
        "keras.ops.less_equal",
        "keras.ops.numpy.less_equal",
    ]
)
def less_equal(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return LessEqual().symbolic_call(x1, x2)
    return backend.numpy.less_equal(x1, x2)


class Linspace(Operation):
    def __init__(
        self, num=50, endpoint=True, retstep=False, dtype=float, axis=0
    ):
        super().__init__()
        self.num = num
        self.endpoint = endpoint
        self.retstep = retstep
        self.dtype = dtype
        self.axis = axis

    def call(self, start, stop):
        return backend.numpy.linspace(
            start,
            stop,
            num=self.num,
            endpoint=self.endpoint,
            retstep=self.retstep,
            dtype=self.dtype,
            axis=self.axis,
        )

    def compute_output_spec(self, start, stop):
        start_shape = getattr(start, "shape", [])
        stop_shape = getattr(stop, "shape", [])
        output_shape = broadcast_shapes(start_shape, stop_shape)
        if self.axis == -1:
            output_shape = output_shape + [self.num]
        elif self.axis >= 0:
            output_shape = (
                output_shape[: self.axis]
                + [self.num]
                + output_shape[self.axis :]
            )
        else:
            output_shape = (
                output_shape[: self.axis + 1]
                + [self.num]
                + output_shape[self.axis + 1 :]
            )

        dtype = (
            self.dtype
            if self.dtype is not None
            else getattr(start, "dtype", type(start))
        )
        dtype = backend.result_type(dtype, float)
        if self.retstep:
            return (KerasTensor(output_shape, dtype=dtype), None)
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.linspace", "keras.ops.numpy.linspace"])
def linspace(
    start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0
):
    
    if any_symbolic_tensors((start, stop)):
        return Linspace(num, endpoint, retstep, dtype, axis)(start, stop)
    return backend.numpy.linspace(
        start,
        stop,
        num=num,
        endpoint=endpoint,
        retstep=retstep,
        dtype=dtype,
        axis=axis,
    )


class Log(Operation):
    def call(self, x):
        return backend.numpy.log(x)

    def compute_output_spec(self, x):
        dtype = (
            backend.floatx()
            if backend.standardize_dtype(x.dtype) == "int64"
            else dtypes.result_type(x.dtype, float)
        )
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.log", "keras.ops.numpy.log"])
def log(x):
    
    if any_symbolic_tensors((x,)):
        return Log().symbolic_call(x)
    return backend.numpy.log(x)


class Log10(Operation):
    def call(self, x):
        return backend.numpy.log10(x)

    def compute_output_spec(self, x):
        dtype = (
            backend.floatx()
            if backend.standardize_dtype(x.dtype) == "int64"
            else dtypes.result_type(x.dtype, float)
        )
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.log10", "keras.ops.numpy.log10"])
def log10(x):
    
    if any_symbolic_tensors((x,)):
        return Log10().symbolic_call(x)
    return backend.numpy.log10(x)


class Log1p(Operation):
    def call(self, x):
        return backend.numpy.log1p(x)

    def compute_output_spec(self, x):
        dtype = (
            backend.floatx()
            if backend.standardize_dtype(x.dtype) == "int64"
            else dtypes.result_type(x.dtype, float)
        )
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.log1p", "keras.ops.numpy.log1p"])
def log1p(x):
    
    if any_symbolic_tensors((x,)):
        return Log1p().symbolic_call(x)
    return backend.numpy.log1p(x)


class Log2(Operation):
    def call(self, x):
        return backend.numpy.log2(x)

    def compute_output_spec(self, x):
        dtype = (
            backend.floatx()
            if backend.standardize_dtype(x.dtype) == "int64"
            else dtypes.result_type(x.dtype, float)
        )
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.log2", "keras.ops.numpy.log2"])
def log2(x):
    
    if any_symbolic_tensors((x,)):
        return Log2().symbolic_call(x)
    return backend.numpy.log2(x)


class Logaddexp(Operation):
    def call(self, x1, x2):
        return backend.numpy.logaddexp(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
            float,
        )
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.logaddexp", "keras.ops.numpy.logaddexp"])
def logaddexp(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Logaddexp().symbolic_call(x1, x2)
    return backend.numpy.logaddexp(x1, x2)


class LogicalAnd(Operation):
    def call(self, x1, x2):
        return backend.numpy.logical_and(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(
    [
        "keras.ops.logical_and",
        "keras.ops.numpy.logical_and",
    ]
)
def logical_and(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return LogicalAnd().symbolic_call(x1, x2)
    return backend.numpy.logical_and(x1, x2)


class LogicalNot(Operation):
    def call(self, x):
        return backend.numpy.logical_not(x)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, dtype="bool")


@keras_export(
    [
        "keras.ops.logical_not",
        "keras.ops.numpy.logical_not",
    ]
)
def logical_not(x):
    
    if any_symbolic_tensors((x,)):
        return LogicalNot().symbolic_call(x)
    return backend.numpy.logical_not(x)


class LogicalOr(Operation):
    def call(self, x1, x2):
        return backend.numpy.logical_or(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(
    [
        "keras.ops.logical_or",
        "keras.ops.numpy.logical_or",
    ]
)
def logical_or(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return LogicalOr().symbolic_call(x1, x2)
    return backend.numpy.logical_or(x1, x2)


class Logspace(Operation):
    def __init__(self, num=50, endpoint=True, base=10, dtype=float, axis=0):
        super().__init__()
        self.num = num
        self.endpoint = endpoint
        self.base = base
        self.dtype = dtype
        self.axis = axis

    def call(self, start, stop):
        return backend.numpy.logspace(
            start,
            stop,
            num=self.num,
            endpoint=self.endpoint,
            base=self.base,
            dtype=self.dtype,
            axis=self.axis,
        )

    def compute_output_spec(self, start, stop):
        start_shape = getattr(start, "shape", [])
        stop_shape = getattr(stop, "shape", [])
        output_shape = broadcast_shapes(start_shape, stop_shape)
        if self.axis == -1:
            output_shape = output_shape + [self.num]
        elif self.axis >= 0:
            output_shape = (
                output_shape[: self.axis]
                + [self.num]
                + output_shape[self.axis :]
            )
        else:
            output_shape = (
                output_shape[: self.axis + 1]
                + [self.num]
                + output_shape[self.axis + 1 :]
            )
        dtype = (
            self.dtype
            if self.dtype is not None
            else getattr(start, "dtype", type(start))
        )
        dtype = backend.result_type(dtype, float)
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.logspace", "keras.ops.numpy.logspace"])
def logspace(start, stop, num=50, endpoint=True, base=10, dtype=None, axis=0):
    
    if any_symbolic_tensors((start, stop)):
        return Logspace(num, endpoint, base, dtype, axis)(start, stop)
    return backend.numpy.logspace(
        start,
        stop,
        num=num,
        endpoint=endpoint,
        base=base,
        dtype=dtype,
        axis=axis,
    )


class Matmul(Operation):
    def call(self, x1, x2):
        return backend.numpy.matmul(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = operation_utils.compute_matmul_output_shape(
            x1_shape, x2_shape
        )
        x1_sparse = getattr(x1, "sparse", True)
        x2_sparse = getattr(x2, "sparse", True)
        output_sparse = x1_sparse and x2_sparse
        dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        return KerasTensor(output_shape, dtype=dtype, sparse=output_sparse)


@keras_export(["keras.ops.matmul", "keras.ops.numpy.matmul"])
def matmul(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Matmul().symbolic_call(x1, x2)
    return backend.numpy.matmul(x1, x2)


class Max(Operation):
    def __init__(self, axis=None, keepdims=False, initial=None):
        super().__init__()
        if isinstance(axis, int):
            self.axis = [axis]
        else:
            self.axis = axis
        self.keepdims = keepdims
        self.initial = initial

    def call(self, x):
        return backend.numpy.max(
            x, axis=self.axis, keepdims=self.keepdims, initial=self.initial
        )

    def compute_output_spec(self, x):
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=x.dtype,
        )


@keras_export(["keras.ops.max", "keras.ops.numpy.max"])
def max(x, axis=None, keepdims=False, initial=None):
    
    if any_symbolic_tensors((x,)):
        return Max(axis=axis, keepdims=keepdims, initial=initial).symbolic_call(
            x
        )
    return backend.numpy.max(x, axis=axis, keepdims=keepdims, initial=initial)


class Maximum(Operation):
    def call(self, x1, x2):
        return backend.numpy.maximum(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        output_dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        x1_sparse = getattr(x1, "sparse", False)
        x2_sparse = getattr(x2, "sparse", False)
        output_sparse = x1_sparse and x2_sparse
        return KerasTensor(
            output_shape, dtype=output_dtype, sparse=output_sparse
        )


@keras_export(["keras.ops.maximum", "keras.ops.numpy.maximum"])
def maximum(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Maximum().symbolic_call(x1, x2)
    return backend.numpy.maximum(x1, x2)


class Median(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            axis = [axis]
        self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.median(x, axis=self.axis, keepdims=self.keepdims)

    def compute_output_spec(self, x):
        output_shape = reduce_shape(
            x.shape, axis=self.axis, keepdims=self.keepdims
        )
        if backend.standardize_dtype(x.dtype) == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(x.dtype, float)
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.median", "keras.ops.numpy.median"])
def median(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return Median(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.median(x, axis=axis, keepdims=keepdims)


class Meshgrid(Operation):
    def __init__(self, indexing="xy"):
        super().__init__()
        if indexing not in ("xy", "ij"):
            raise ValueError(
                "Valid values for `indexing` are 'xy' and 'ij', "
                "but received {index}."
            )
        self.indexing = indexing

    def call(self, *x):
        return backend.numpy.meshgrid(*x, indexing=self.indexing)

    def compute_output_spec(self, *x):
        output_shape = []
        for xi in x:
            if len(xi.shape) == 0:
                size = 1
            else:
                if None in xi.shape:
                    size = None
                else:
                    size = int(np.prod(xi.shape))
            output_shape.append(size)
        if self.indexing == "ij":
            return [KerasTensor(output_shape) for _ in range(len(x))]
        tmp = output_shape[0]
        output_shape[0] = output_shape[1]
        output_shape[1] = tmp
        return [
            KerasTensor(output_shape, dtype=xi.dtype) for _ in range(len(x))
        ]


@keras_export(["keras.ops.meshgrid", "keras.ops.numpy.meshgrid"])
def meshgrid(*x, indexing="xy"):
    
    if any_symbolic_tensors(x):
        return Meshgrid(indexing=indexing).symbolic_call(*x)
    return backend.numpy.meshgrid(*x, indexing=indexing)


class Min(Operation):
    def __init__(self, axis=None, keepdims=False, initial=None):
        super().__init__()
        if isinstance(axis, int):
            self.axis = [axis]
        else:
            self.axis = axis
        self.keepdims = keepdims
        self.initial = initial

    def call(self, x):
        return backend.numpy.min(
            x, axis=self.axis, keepdims=self.keepdims, initial=self.initial
        )

    def compute_output_spec(self, x):
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=x.dtype,
        )


@keras_export(["keras.ops.min", "keras.ops.numpy.min"])
def min(x, axis=None, keepdims=False, initial=None):
    
    if any_symbolic_tensors((x,)):
        return Min(axis=axis, keepdims=keepdims, initial=initial).symbolic_call(
            x
        )
    return backend.numpy.min(x, axis=axis, keepdims=keepdims, initial=initial)


class Minimum(Operation):
    def call(self, x1, x2):
        return backend.numpy.minimum(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        output_dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        x1_sparse = getattr(x1, "sparse", False)
        x2_sparse = getattr(x2, "sparse", False)
        output_sparse = x1_sparse and x2_sparse
        return KerasTensor(
            output_shape, dtype=output_dtype, sparse=output_sparse
        )


@keras_export(["keras.ops.minimum", "keras.ops.numpy.minimum"])
def minimum(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Minimum().symbolic_call(x1, x2)
    return backend.numpy.minimum(x1, x2)


class Mod(Operation):
    def call(self, x1, x2):
        return backend.numpy.mod(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        output_dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        if output_dtype == "bool":
            output_dtype = "int32"
        x1_sparse = getattr(x1, "sparse", False)
        x2_sparse = getattr(x2, "sparse", False)
        output_sparse = x1_sparse and not x2_sparse
        return KerasTensor(
            output_shape, dtype=output_dtype, sparse=output_sparse
        )


@keras_export(["keras.ops.mod", "keras.ops.numpy.mod"])
def mod(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Mod().symbolic_call(x1, x2)
    return backend.numpy.mod(x1, x2)


class Moveaxis(Operation):
    def __init__(self, source, destination):
        super().__init__()
        if isinstance(source, int):
            self.source = [source]
        else:
            self.source = source
        if isinstance(destination, int):
            self.destination = [destination]
        else:
            self.destination = destination

        if len(self.source) != len(self.destination):
            raise ValueError(
                "`source` and `destination` arguments must have the same "
                f"number of elements, but received `source={source}` and "
                f"`destination={destination}`."
            )

    def call(self, x):
        return backend.numpy.moveaxis(x, self.source, self.destination)

    def compute_output_spec(self, x):
        x_shape = list(x.shape)
        output_shape = [-1 for _ in range(len(x.shape))]
        for sc, dst in zip(self.source, self.destination):
            output_shape[dst] = x_shape[sc]
            x_shape[sc] = -1
        i, j = 0, 0
        while i < len(output_shape):
            while i < len(output_shape) and output_shape[i] != -1:
                
                i += 1
            while j < len(output_shape) and x_shape[j] == -1:
                
                j += 1
            if i == len(output_shape):
                break
            output_shape[i] = x_shape[j]
            i += 1
            j += 1
        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(["keras.ops.moveaxis", "keras.ops.numpy.moveaxis"])
def moveaxis(x, source, destination):
    
    if any_symbolic_tensors((x,)):
        return Moveaxis(source, destination).symbolic_call(x)
    return backend.numpy.moveaxis(x, source=source, destination=destination)


class NanToNum(Operation):
    def call(self, x):
        return backend.numpy.nan_to_num(x)


@keras_export(
    [
        "keras.ops.nan_to_num",
        "keras.ops.numpy.nan_to_num",
    ]
)
def nan_to_num(x):
    
    return backend.numpy.nan_to_num(x)


class Ndim(Operation):
    def call(self, x):
        return backend.numpy.ndim(
            x,
        )

    def compute_output_spec(self, x):
        return KerasTensor([len(x.shape)])


@keras_export(["keras.ops.ndim", "keras.ops.numpy.ndim"])
def ndim(x):
    
    if any_symbolic_tensors((x,)):
        return Ndim().symbolic_call(x)
    return backend.numpy.ndim(x)


class Nonzero(Operation):
    def call(self, x):
        return backend.numpy.nonzero(x)


@keras_export(["keras.ops.nonzero", "keras.ops.numpy.nonzero"])
def nonzero(x):
    
    return backend.numpy.nonzero(x)


class NotEqual(Operation):
    def call(self, x1, x2):
        return backend.numpy.not_equal(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(["keras.ops.not_equal", "keras.ops.numpy.not_equal"])
def not_equal(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return NotEqual().symbolic_call(x1, x2)
    return backend.numpy.not_equal(x1, x2)


class OnesLike(Operation):
    def call(self, x, dtype=None):
        return backend.numpy.ones_like(x, dtype=dtype)

    def compute_output_spec(self, x, dtype=None):
        if dtype is None:
            dtype = x.dtype
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(["keras.ops.ones_like", "keras.ops.numpy.ones_like"])
def ones_like(x, dtype=None):
    
    if any_symbolic_tensors((x,)):
        return OnesLike().symbolic_call(x, dtype=dtype)
    return backend.numpy.ones_like(x, dtype=dtype)


class ZerosLike(Operation):
    def call(self, x, dtype=None):
        return backend.numpy.zeros_like(x, dtype=dtype)

    def compute_output_spec(self, x, dtype=None):
        if dtype is None:
            dtype = x.dtype
        return KerasTensor(x.shape, dtype=dtype)


@keras_export(
    [
        "keras.ops.zeros_like",
        "keras.ops.numpy.zeros_like",
    ]
)
def zeros_like(x, dtype=None):
    
    if any_symbolic_tensors((x,)):
        return ZerosLike().symbolic_call(x, dtype=dtype)
    return backend.numpy.zeros_like(x, dtype=dtype)


class Outer(Operation):
    def call(self, x1, x2):
        return backend.numpy.outer(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [1])
        x2_shape = getattr(x2, "shape", [1])
        if None in x1_shape:
            x1_flatten_shape = None
        else:
            x1_flatten_shape = int(np.prod(x1_shape))
        if None in x2_shape:
            x2_flatten_shape = None
        else:
            x2_flatten_shape = int(np.prod(x2_shape))
        output_shape = [x1_flatten_shape, x2_flatten_shape]
        output_dtype = backend.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        return KerasTensor(output_shape, dtype=output_dtype)


@keras_export(["keras.ops.outer", "keras.ops.numpy.outer"])
def outer(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Outer().symbolic_call(x1, x2)
    return backend.numpy.outer(x1, x2)


class Pad(Operation):
    def __init__(self, pad_width, mode="constant"):
        super().__init__()
        self.pad_width = self._process_pad_width(pad_width)
        self.mode = mode

    def _process_pad_width(self, pad_width):
        if isinstance(pad_width, int):
            return ((pad_width, pad_width),)
        if isinstance(pad_width, (tuple, list)) and isinstance(
            pad_width[0], int
        ):
            return (pad_width,)
        first_len = len(pad_width[0])
        for i, pw in enumerate(pad_width):
            if len(pw) != first_len:
                raise ValueError(
                    "`pad_width` should be a list of tuples of length "
                    f"1 or 2. Received: pad_width={pad_width}"
                )
            if len(pw) == 1:
                pad_width[i] = (pw[0], pw[0])
        return pad_width

    def call(self, x, constant_values=None):
        return backend.numpy.pad(
            x,
            pad_width=self.pad_width,
            mode=self.mode,
            constant_values=constant_values,
        )

    def compute_output_spec(self, x, constant_values=None):
        output_shape = list(x.shape)
        if len(self.pad_width) == 1:
            pad_width = [self.pad_width[0] for _ in range(len(output_shape))]
        elif len(self.pad_width) == len(output_shape):
            pad_width = self.pad_width
        else:
            raise ValueError(
                "`pad_width` must have the same length as `x.shape`. "
                f"Received: pad_width={self.pad_width} "
                f"(of length {len(self.pad_width)}) and x.shape={x.shape} "
                f"(of length {len(x.shape)})"
            )

        for i in range(len(output_shape)):
            if output_shape[i] is None:
                output_shape[i] = None
            else:
                output_shape[i] += pad_width[i][0] + pad_width[i][1]
        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(["keras.ops.pad", "keras.ops.numpy.pad"])
def pad(x, pad_width, mode="constant", constant_values=None):
    
    return Pad(pad_width, mode=mode)(x, constant_values=constant_values)


class Prod(Operation):
    def __init__(self, axis=None, keepdims=False, dtype=None):
        super().__init__()
        if isinstance(axis, int):
            self.axis = [axis]
        else:
            self.axis = axis
        self.keepdims = keepdims
        self.dtype = dtype

    def call(self, x):
        return backend.numpy.prod(
            x,
            axis=self.axis,
            keepdims=self.keepdims,
            dtype=self.dtype,
        )

    def compute_output_spec(self, x):
        if self.dtype is not None:
            dtype = self.dtype
        else:
            dtype = backend.result_type(x.dtype)
            if dtype == "bool":
                dtype = "int32"
            elif dtype in ("int8", "int16"):
                dtype = "int32"
            elif dtype in ("uint8", "uint16"):
                dtype = "uint32"
        
        if backend.backend() == "torch" and dtype == "uint32":
            dtype = "int32"
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=dtype,
        )


@keras_export(["keras.ops.prod", "keras.ops.numpy.prod"])
def prod(x, axis=None, keepdims=False, dtype=None):
    
    if any_symbolic_tensors((x,)):
        return Prod(axis=axis, keepdims=keepdims, dtype=dtype).symbolic_call(x)
    return backend.numpy.prod(x, axis=axis, keepdims=keepdims, dtype=dtype)


class Quantile(Operation):
    def __init__(self, axis=None, method="linear", keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            axis = [axis]
        self.axis = axis
        self.method = method
        self.keepdims = keepdims

    def call(self, x, q):
        return backend.numpy.quantile(
            x, q, axis=self.axis, keepdims=self.keepdims
        )

    def compute_output_spec(self, x, q):
        output_shape = reduce_shape(
            x.shape, axis=self.axis, keepdims=self.keepdims
        )
        if hasattr(q, "shape"):
            if len(q.shape) > 0:
                output_shape = (q.shape[0],) + output_shape
        if backend.standardize_dtype(x.dtype) == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(x.dtype, float)
        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.quantile", "keras.ops.numpy.quantile"])
def quantile(x, q, axis=None, method="linear", keepdims=False):
    
    if any_symbolic_tensors((x, q)):
        return Quantile(
            axis=axis, method=method, keepdims=keepdims
        ).symbolic_call(x, q)
    return backend.numpy.quantile(
        x, q, axis=axis, method=method, keepdims=keepdims
    )


class Ravel(Operation):
    def call(self, x):
        return backend.numpy.ravel(x)

    def compute_output_spec(self, x):
        if None in x.shape:
            output_shape = [
                None,
            ]
        else:
            output_shape = [int(np.prod(x.shape))]
        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(["keras.ops.ravel", "keras.ops.numpy.ravel"])
def ravel(x):
    
    if any_symbolic_tensors((x,)):
        return Ravel().symbolic_call(x)
    return backend.numpy.ravel(x)


class Real(Operation):
    def call(self, x):
        return backend.numpy.real(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.real", "keras.ops.numpy.real"])
def real(x):
    
    if any_symbolic_tensors((x,)):
        return Real().symbolic_call(x)
    return backend.numpy.real(x)


class Reciprocal(Operation):
    def call(self, x):
        return backend.numpy.reciprocal(x)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape)


@keras_export(
    [
        "keras.ops.reciprocal",
        "keras.ops.numpy.reciprocal",
    ]
)
def reciprocal(x):
    
    if any_symbolic_tensors((x,)):
        return Reciprocal().symbolic_call(x)
    return backend.numpy.reciprocal(x)


class Repeat(Operation):
    def __init__(self, repeats, axis=None):
        super().__init__()
        self.axis = axis
        self.repeats = repeats

    def call(self, x):
        return backend.numpy.repeat(x, self.repeats, axis=self.axis)

    def compute_output_spec(self, x):
        x_shape = list(x.shape)
        if self.axis is None:
            if None in x_shape:
                return KerasTensor([None], dtype=x.dtype)

            x_flatten_size = int(np.prod(x_shape))
            if isinstance(self.repeats, int):
                output_shape = [x_flatten_size * self.repeats]
            else:
                output_shape = [int(np.sum(self.repeats))]
            return KerasTensor(output_shape, dtype=x.dtype)

        size_on_ax = x_shape[self.axis]
        output_shape = x_shape
        if isinstance(self.repeats, int):
            if size_on_ax is None:
                output_shape[self.axis] = None
            else:
                output_shape[self.axis] = size_on_ax * self.repeats
        else:
            output_shape[self.axis] = int(np.sum(self.repeats))
        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(["keras.ops.repeat", "keras.ops.numpy.repeat"])
def repeat(x, repeats, axis=None):
    
    if any_symbolic_tensors((x,)):
        return Repeat(repeats, axis=axis).symbolic_call(x)
    return backend.numpy.repeat(x, repeats, axis=axis)


class Reshape(Operation):
    def __init__(self, new_shape):
        super().__init__()
        self.new_shape = new_shape

    def call(self, x):
        return backend.numpy.reshape(x, self.new_shape)

    def compute_output_spec(self, x):
        output_shape = operation_utils.compute_reshape_output_shape(
            x.shape, self.new_shape, "new_shape"
        )
        sparse = getattr(x, "sparse", False)
        return KerasTensor(output_shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.reshape", "keras.ops.numpy.reshape"])
def reshape(x, new_shape):
    
    if any_symbolic_tensors((x,)):
        return Reshape(new_shape).symbolic_call(x)
    return backend.numpy.reshape(x, new_shape)


class Roll(Operation):
    def __init__(self, shift, axis=None):
        super().__init__()
        self.shift = shift
        self.axis = axis

    def call(self, x):
        return backend.numpy.roll(x, self.shift, self.axis)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, dtype=x.dtype)


@keras_export(["keras.ops.roll", "keras.ops.numpy.roll"])
def roll(x, shift, axis=None):
    
    if any_symbolic_tensors((x,)):
        return Roll(shift, axis=axis).symbolic_call(x)
    return backend.numpy.roll(x, shift, axis=axis)


class Round(Operation):
    def __init__(self, decimals=0):
        super().__init__()
        self.decimals = decimals

    def call(self, x):
        return backend.numpy.round(x, self.decimals)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.round", "keras.ops.numpy.round"])
def round(x, decimals=0):
    
    if any_symbolic_tensors((x,)):
        return Round(decimals).symbolic_call(x)
    return backend.numpy.round(x, decimals)


class Sign(Operation):
    def call(self, x):
        return backend.numpy.sign(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.sign", "keras.ops.numpy.sign"])
def sign(x):
    
    if any_symbolic_tensors((x,)):
        return Sign().symbolic_call(x)
    return backend.numpy.sign(x)


class Sin(Operation):
    def call(self, x):
        return backend.numpy.sin(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.sin", "keras.ops.numpy.sin"])
def sin(x):
    
    if any_symbolic_tensors((x,)):
        return Sin().symbolic_call(x)
    return backend.numpy.sin(x)


class Sinh(Operation):
    def call(self, x):
        return backend.numpy.sinh(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.sinh", "keras.ops.numpy.sinh"])
def sinh(x):
    
    if any_symbolic_tensors((x,)):
        return Sinh().symbolic_call(x)
    return backend.numpy.sinh(x)


class Size(Operation):
    def call(self, x):
        return backend.numpy.size(x)

    def compute_output_spec(self, x):
        return KerasTensor([], dtype="int32")


@keras_export(["keras.ops.size", "keras.ops.numpy.size"])
def size(x):
    
    if any_symbolic_tensors((x,)):
        return Size().symbolic_call(x)
    return backend.numpy.size(x)


class Sort(Operation):
    def __init__(self, axis=-1):
        super().__init__()
        self.axis = axis

    def call(self, x):
        return backend.numpy.sort(x, axis=self.axis)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, x.dtype)


@keras_export(["keras.ops.sort", "keras.ops.numpy.sort"])
def sort(x, axis=-1):
    
    if any_symbolic_tensors((x,)):
        return Sort(axis=axis).symbolic_call(x)
    return backend.numpy.sort(x, axis=axis)


class Split(Operation):
    def __init__(self, indices_or_sections, axis=0):
        super().__init__()
        if not isinstance(indices_or_sections, int):
            indices_or_sections = tuple(indices_or_sections)
        self.indices_or_sections = indices_or_sections
        self.axis = axis

    def call(self, x):
        return backend.numpy.split(x, self.indices_or_sections, axis=self.axis)

    def compute_output_spec(self, x):
        x_shape = list(x.shape)
        x_size_on_axis = x_shape[self.axis]
        if isinstance(self.indices_or_sections, int):
            if x_size_on_axis is None:
                x_shape[self.axis] = None
                return [
                    KerasTensor(x_shape, dtype=x.dtype)
                    for _ in range(self.indices_or_sections)
                ]
            if np.mod(x_size_on_axis, self.indices_or_sections) != 0:
                raise ValueError(
                    "`x` size on given `axis` must be dividible by "
                    "`indices_or_sections` when `indices_or_sections` is an "
                    f"int. But received {x_size_on_axis} and "
                    f"{self.indices_or_sections}."
                )
            size = x_size_on_axis // self.indices_or_sections
            x_shape[self.axis] = size
            return [
                KerasTensor(x_shape, dtype=x.dtype)
                for _ in range(self.indices_or_sections)
            ]

        indices_or_sections = (0, *self.indices_or_sections, x_size_on_axis)
        output_size = np.diff(indices_or_sections)
        outputs = []
        for i in range(len(output_size)):
            output_shape = list(x_shape)
            output_shape[self.axis] = int(output_size[i])
            outputs.append(KerasTensor(output_shape, dtype=x.dtype))
        return outputs


@keras_export(["keras.ops.split", "keras.ops.numpy.split"])
def split(x, indices_or_sections, axis=0):
    
    if any_symbolic_tensors((x,)):
        return Split(indices_or_sections, axis=axis).symbolic_call(x)
    return backend.numpy.split(x, indices_or_sections, axis=axis)


class Stack(Operation):
    def __init__(self, axis=0):
        super().__init__()
        self.axis = axis

    def call(self, xs):
        return backend.numpy.stack(xs, axis=self.axis)

    def compute_output_spec(self, xs):
        first_shape = xs[0].shape
        dtypes_to_resolve = []
        for x in xs:
            if not shape_equal(x.shape, first_shape, axis=[], allow_none=True):
                raise ValueError(
                    "Every value in `xs` must have the same shape. But found "
                    f"element of shape {x.shape},  which is different from the "
                    f"first element's shape {first_shape}."
                )
            dtypes_to_resolve.append(getattr(x, "dtype", type(x)))

        size_on_axis = len(xs)
        output_shape = list(first_shape)
        if self.axis == -1:
            output_shape = output_shape + [size_on_axis]
        elif self.axis >= 0:
            output_shape.insert(self.axis, size_on_axis)
        else:
            output_shape.insert(self.axis + 1, size_on_axis)
        output_dtype = dtypes.result_type(*dtypes_to_resolve)
        return KerasTensor(output_shape, dtype=output_dtype)


@keras_export(["keras.ops.stack", "keras.ops.numpy.stack"])
def stack(x, axis=0):
    
    if any_symbolic_tensors((x,)):
        return Stack(axis=axis).symbolic_call(x)
    return backend.numpy.stack(x, axis=axis)


class Std(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            self.axis = [axis]
        else:
            self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.std(x, axis=self.axis, keepdims=self.keepdims)

    def compute_output_spec(self, x):
        output_dtype = backend.standardize_dtype(x.dtype)
        if "int" in output_dtype or output_dtype == "bool":
            output_dtype = backend.floatx()
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=output_dtype,
        )


@keras_export(["keras.ops.std", "keras.ops.numpy.std"])
def std(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return Std(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.std(x, axis=axis, keepdims=keepdims)


class Swapaxes(Operation):
    def __init__(self, axis1, axis2):
        super().__init__()

        self.axis1 = axis1
        self.axis2 = axis2

    def call(self, x):
        return backend.numpy.swapaxes(x, self.axis1, self.axis2)

    def compute_output_spec(self, x):
        x_shape = list(x.shape)
        tmp = x_shape[self.axis1]
        x_shape[self.axis1] = x_shape[self.axis2]
        x_shape[self.axis2] = tmp
        return KerasTensor(x_shape, dtype=x.dtype)


@keras_export(["keras.ops.swapaxes", "keras.ops.numpy.swapaxes"])
def swapaxes(x, axis1, axis2):
    
    if any_symbolic_tensors((x,)):
        return Swapaxes(axis1, axis2).symbolic_call(x)
    return backend.numpy.swapaxes(x, axis1=axis1, axis2=axis2)


class Take(Operation):
    def __init__(self, axis=None):
        super().__init__()
        self.axis = axis

    def call(self, x, indices):
        return backend.numpy.take(x, indices, axis=self.axis)

    def compute_output_spec(self, x, indices):
        x_shape = list(x.shape)
        if isinstance(indices, KerasTensor):
            indices_shape = list(indices.shape)
        else:
            indices_shape = list(getattr(np.array(indices), "shape", []))
        if self.axis is None:
            return KerasTensor(indices_shape, dtype=x.dtype)

        
        axis = len(x_shape) + self.axis if self.axis < 0 else self.axis
        output_shape = x_shape[:axis] + indices_shape + x_shape[axis + 1 :]
        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(["keras.ops.take", "keras.ops.numpy.take"])
def take(x, indices, axis=None):
    
    if any_symbolic_tensors((x, indices)):
        return Take(axis=axis).symbolic_call(x, indices)
    return backend.numpy.take(x, indices, axis=axis)


class TakeAlongAxis(Operation):
    def __init__(self, axis=None):
        super().__init__()
        self.axis = axis

    def call(self, x, indices):
        return backend.numpy.take_along_axis(x, indices, axis=self.axis)

    def compute_output_spec(self, x, indices):
        x_shape = list(x.shape)
        indices_shape = list(indices.shape)
        if self.axis is None:
            x_shape = [None] if None in x_shape else [int(np.prod(x_shape))]

        if len(x_shape) != len(indices_shape):
            raise ValueError(
                "`x` and `indices` must have the same number of dimensions, "
                f"but receive shape {x_shape} and {indices_shape}."
            )

        del x_shape[self.axis]
        del indices_shape[self.axis]
        output_shape = broadcast_shapes(x_shape, indices_shape)
        size_on_axis = indices.shape[self.axis]
        if self.axis == -1:
            output_shape = output_shape + [size_on_axis]
        elif self.axis >= 0:
            output_shape.insert(self.axis, size_on_axis)
        else:
            output_shape.insert(self.axis + 1, size_on_axis)

        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(
    [
        "keras.ops.take_along_axis",
        "keras.ops.numpy.take_along_axis",
    ]
)
def take_along_axis(x, indices, axis=None):
    
    if any_symbolic_tensors((x, indices)):
        return TakeAlongAxis(axis=axis).symbolic_call(x, indices)
    return backend.numpy.take_along_axis(x, indices, axis=axis)


class Tan(Operation):
    def call(self, x):
        return backend.numpy.tan(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.tan", "keras.ops.numpy.tan"])
def tan(x):
    
    if any_symbolic_tensors((x,)):
        return Tan().symbolic_call(x)
    return backend.numpy.tan(x)


class Tanh(Operation):
    def call(self, x):
        return backend.numpy.tanh(x)

    def compute_output_spec(self, x):
        dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx()))
        if dtype == "int64":
            dtype = backend.floatx()
        else:
            dtype = dtypes.result_type(dtype, float)
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.tanh", "keras.ops.numpy.tanh"])
def tanh(x):
    
    if any_symbolic_tensors((x,)):
        return Tanh().symbolic_call(x)
    return backend.numpy.tanh(x)


class Tensordot(Operation):
    def __init__(self, axes=2):
        super().__init__()
        self.axes = axes

    def call(self, x1, x2):
        return backend.numpy.tensordot(x1, x2, axes=self.axes)

    def compute_output_spec(self, x1, x2):
        x1_shape = list(getattr(x1, "shape", []))
        x2_shape = list(getattr(x2, "shape", []))
        dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        if not isinstance(self.axes, int):
            x1_select_shape = [x1_shape[ax] for ax in self.axes[0]]
            x2_select_shape = [x2_shape[ax] for ax in self.axes[1]]
            if not shape_equal(
                x1_select_shape, x2_select_shape, allow_none=True
            ):
                raise ValueError(
                    "Shape mismatch on `x1[axes[0]]` and `x2[axes[1]]`, "
                    f"received {x1_select_shape} and {x2_select_shape}."
                )

            for ax in self.axes[0]:
                x1_shape[ax] = -1
            for ax in self.axes[1]:
                x2_shape[ax] = -1

            x1_shape = list(filter((-1).__ne__, x1_shape))
            x2_shape = list(filter((-1).__ne__, x2_shape))

            output_shape = x1_shape + x2_shape
            return KerasTensor(output_shape, dtype=dtype)

        if self.axes <= 0:
            output_shape = x1_shape + x2_shape
        else:
            output_shape = x1_shape[: -self.axes] + x2_shape[self.axes :]

        return KerasTensor(output_shape, dtype=dtype)


@keras_export(["keras.ops.tensordot", "keras.ops.numpy.tensordot"])
def tensordot(x1, x2, axes=2):
    
    if any_symbolic_tensors((x1, x2)):
        return Tensordot(axes=axes).symbolic_call(x1, x2)
    return backend.numpy.tensordot(x1, x2, axes=axes)


class Tile(Operation):
    def __init__(self, repeats):
        super().__init__()
        self.repeats = repeats

    def call(self, x):
        return backend.numpy.tile(x, self.repeats)

    def compute_output_spec(self, x):
        x_shape = list(x.shape)
        repeats = self.repeats
        if len(x_shape) > len(repeats):
            repeats = [1] * (len(x_shape) - len(repeats)) + repeats
        else:
            x_shape = [1] * (len(repeats) - len(x_shape)) + x_shape

        output_shape = []
        for x_size, repeat in zip(x_shape, repeats):
            if x_size is None:
                output_shape.append(None)
            else:
                output_shape.append(x_size * repeat)
        return KerasTensor(output_shape, dtype=x.dtype)


@keras_export(["keras.ops.tile", "keras.ops.numpy.tile"])
def tile(x, repeats):
    
    if any_symbolic_tensors((x,)):
        return Tile(
            repeats,
        ).symbolic_call(x)
    return backend.numpy.tile(x, repeats)


class Trace(Operation):
    def __init__(self, offset=0, axis1=0, axis2=1):
        super().__init__()
        self.offset = offset
        self.axis1 = axis1
        self.axis2 = axis2

    def call(self, x):
        return backend.numpy.trace(
            x, offset=self.offset, axis1=self.axis1, axis2=self.axis2
        )

    def compute_output_spec(self, x):
        x_shape = list(x.shape)
        x_shape[self.axis1] = -1
        x_shape[self.axis2] = -1
        output_shape = list(filter((-1).__ne__, x_shape))
        output_dtype = backend.standardize_dtype(x.dtype)
        if output_dtype not in ("int64", "uint32", "uint64"):
            output_dtype = dtypes.result_type(output_dtype, "int32")
        return KerasTensor(output_shape, dtype=output_dtype)


@keras_export(["keras.ops.trace", "keras.ops.numpy.trace"])
def trace(x, offset=0, axis1=0, axis2=1):
    
    if any_symbolic_tensors((x,)):
        return Trace(offset, axis1, axis2).symbolic_call(x)
    return backend.numpy.trace(x, offset=offset, axis1=axis1, axis2=axis2)


class Tri(Operation):
    def call(self, N, M=None, k=0, dtype=None):
        return backend.numpy.tri(N, M=M, k=k, dtype=dtype)

    def compute_output_spec(self, N, M=None, k=0, dtype=None):
        if M is None:
            M = N
        dtype = dtype or backend.floatx()
        return KerasTensor((N, M), dtype=dtype)


@keras_export(["keras.ops.tri", "keras.ops.numpy.tri"])
def tri(N, M=None, k=0, dtype=None):
    
    return backend.numpy.tri(N, M=M, k=k, dtype=dtype)


class Tril(Operation):
    def __init__(self, k=0):
        super().__init__()
        self.k = k

    def call(self, x):
        return backend.numpy.tril(x, k=self.k)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, dtype=x.dtype)


@keras_export(["keras.ops.tril", "keras.ops.numpy.tril"])
def tril(x, k=0):
    
    if any_symbolic_tensors((x,)):
        return Tril(k=k).symbolic_call(x)
    return backend.numpy.tril(x, k=k)


class Triu(Operation):
    def __init__(self, k=0):
        super().__init__()
        self.k = k

    def call(self, x):
        return backend.numpy.triu(x, k=self.k)

    def compute_output_spec(self, x):
        return KerasTensor(x.shape, dtype=x.dtype)


@keras_export(["keras.ops.triu", "keras.ops.numpy.triu"])
def triu(x, k=0):
    
    if any_symbolic_tensors((x,)):
        return Triu(k=k).symbolic_call(x)
    return backend.numpy.triu(x, k=k)


class Vdot(Operation):
    def call(self, x1, x2):
        return backend.numpy.vdot(x1, x2)

    def compute_output_spec(self, x1, x2):
        dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        return KerasTensor([], dtype=dtype)


@keras_export(["keras.ops.vdot", "keras.ops.numpy.vdot"])
def vdot(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Vdot().symbolic_call(x1, x2)
    return backend.numpy.vdot(x1, x2)


class Vstack(Operation):
    def call(self, xs):
        return backend.numpy.vstack(xs)

    def compute_output_spec(self, xs):
        first_shape = xs[0].shape
        total_size_on_axis = 0
        dtypes_to_resolve = []
        for x in xs:
            if not shape_equal(x.shape, first_shape, axis=[0], allow_none=True):
                raise ValueError(
                    "Every value in `xs` must have the same shape except on "
                    f"the `axis` dim. But found element of shape {x.shape}, "
                    f"which is different from the first element's "
                    f"shape {first_shape}."
                )
            if total_size_on_axis is None or x.shape[0] is None:
                total_size_on_axis = None
            else:
                total_size_on_axis += x.shape[0]
            dtypes_to_resolve.append(getattr(x, "dtype", type(x)))
        output_shape = list(first_shape)
        output_shape[0] = total_size_on_axis
        output_dtype = dtypes.result_type(*dtypes_to_resolve)
        return KerasTensor(output_shape, output_dtype)


@keras_export(["keras.ops.vstack", "keras.ops.numpy.vstack"])
def vstack(xs):
    
    if any_symbolic_tensors((xs,)):
        return Vstack().symbolic_call(xs)
    return backend.numpy.vstack(xs)


class Where(Operation):
    def call(self, condition, x1=None, x2=None):
        return backend.numpy.where(condition, x1, x2)

    def compute_output_spec(self, condition, x1, x2):
        condition_shape = getattr(condition, "shape", [])
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(condition_shape, x1_shape)
        output_shape = broadcast_shapes(output_shape, x2_shape)
        output_dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1) if x1 is not None else "int"),
            getattr(x2, "dtype", type(x2) if x2 is not None else "int"),
        )
        return KerasTensor(output_shape, dtype=output_dtype)


@keras_export(["keras.ops.where", "keras.ops.numpy.where"])
def where(condition, x1=None, x2=None):
    
    if (x1 is None and x2 is not None) or (x1 is not None and x2 is None):
        raise ValueError(
            "`x1` and `x2` either both should be `None`"
            " or both should have non-None value."
        )
    if any_symbolic_tensors((condition, x1, x2)):
        return Where().symbolic_call(condition, x1, x2)
    return backend.numpy.where(condition, x1, x2)


class Subtract(Operation):
    def call(self, x1, x2):
        return backend.numpy.subtract(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        x1_sparse = getattr(x1, "sparse", False)
        x2_sparse = getattr(x2, "sparse", False)
        output_sparse = x1_sparse and x2_sparse
        dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        return KerasTensor(output_shape, dtype=dtype, sparse=output_sparse)


@keras_export(["keras.ops.subtract", "keras.ops.numpy.subtract"])
def subtract(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Subtract().symbolic_call(x1, x2)
    return backend.numpy.subtract(x1, x2)


class Multiply(Operation):
    def call(self, x1, x2):
        return backend.numpy.multiply(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        x1_sparse = getattr(x1, "sparse", True)
        x2_sparse = getattr(x2, "sparse", True)
        output_sparse = x1_sparse or x2_sparse
        dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
        )
        return KerasTensor(output_shape, dtype=dtype, sparse=output_sparse)


@keras_export(["keras.ops.multiply", "keras.ops.numpy.multiply"])
def multiply(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Multiply().symbolic_call(x1, x2)
    return backend.numpy.multiply(x1, x2)


class Divide(Operation):
    def call(self, x1, x2):
        return backend.numpy.divide(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        output_dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
            float,
        )
        x1_sparse = getattr(x1, "sparse", False)
        x2_sparse = getattr(x2, "sparse", False)
        output_sparse = x1_sparse and not x2_sparse
        return KerasTensor(
            output_shape, dtype=output_dtype, sparse=output_sparse
        )


@keras_export(["keras.ops.divide", "keras.ops.numpy.divide"])
def divide(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Divide().symbolic_call(x1, x2)
    return backend.numpy.divide(x1, x2)


class TrueDivide(Operation):
    def call(self, x1, x2):
        return backend.numpy.true_divide(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        output_dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)),
            getattr(x2, "dtype", type(x2)),
            float,
        )
        x1_sparse = getattr(x1, "sparse", False)
        x2_sparse = getattr(x2, "sparse", False)
        output_sparse = x1_sparse and not x2_sparse
        return KerasTensor(
            output_shape, dtype=output_dtype, sparse=output_sparse
        )


@keras_export(
    [
        "keras.ops.true_divide",
        "keras.ops.numpy.true_divide",
    ]
)
def true_divide(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return TrueDivide().symbolic_call(x1, x2)
    return backend.numpy.true_divide(x1, x2)


class Power(Operation):
    def call(self, x1, x2):
        return backend.numpy.power(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        output_dtype = dtypes.result_type(
            getattr(x1, "dtype", type(x1)), getattr(x2, "dtype", type(x2))
        )
        return KerasTensor(output_shape, dtype=output_dtype)


@keras_export(["keras.ops.power", "keras.ops.numpy.power"])
def power(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return Power().symbolic_call(x1, x2)
    return backend.numpy.power(x1, x2)


class Negative(Operation):
    def call(self, x):
        return backend.numpy.negative(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.negative", "keras.ops.numpy.negative"])
def negative(x):
    
    if any_symbolic_tensors((x,)):
        return Negative().symbolic_call(x)
    return backend.numpy.negative(x)


class Square(Operation):
    def call(self, x):
        return backend.numpy.square(x)

    def compute_output_spec(self, x):
        sparse = getattr(x, "sparse", False)
        dtype = backend.standardize_dtype(x.dtype)
        if dtype == "bool":
            dtype = "int32"
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.square", "keras.ops.numpy.square"])
def square(x):
    
    if any_symbolic_tensors((x,)):
        return Square().symbolic_call(x)
    return backend.numpy.square(x)


class Sqrt(Operation):
    def call(self, x):
        x = backend.convert_to_tensor(x)
        return backend.numpy.sqrt(x)

    def compute_output_spec(self, x):
        dtype = (
            backend.floatx()
            if backend.standardize_dtype(x.dtype) == "int64"
            else dtypes.result_type(x.dtype, float)
        )
        sparse = getattr(x, "sparse", False)
        return KerasTensor(x.shape, dtype=dtype, sparse=sparse)


@keras_export(["keras.ops.sqrt", "keras.ops.numpy.sqrt"])
def sqrt(x):
    
    if any_symbolic_tensors((x,)):
        return Sqrt().symbolic_call(x)
    x = backend.convert_to_tensor(x)
    return backend.numpy.sqrt(x)


class Squeeze(Operation):
    def __init__(self, axis=None):
        super().__init__()
        self.axis = axis

    def call(self, x):
        return backend.numpy.squeeze(x, axis=self.axis)

    def compute_output_spec(self, x):
        input_shape = list(x.shape)
        sparse = getattr(x, "sparse", False)
        if self.axis is None:
            output_shape = list(filter((1).__ne__, input_shape))
            return KerasTensor(output_shape, dtype=x.dtype, sparse=sparse)
        else:
            if input_shape[self.axis] != 1:
                raise ValueError(
                    f"Cannot squeeze axis {self.axis}, because the dimension "
                    "is not 1."
                )
            del input_shape[self.axis]
            return KerasTensor(input_shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.squeeze", "keras.ops.numpy.squeeze"])
def squeeze(x, axis=None):
    
    if any_symbolic_tensors((x,)):
        return Squeeze(axis=axis).symbolic_call(x)
    return backend.numpy.squeeze(x, axis=axis)


class Transpose(Operation):
    def __init__(self, axes=None):
        super().__init__()
        self.axes = axes

    def call(self, x):
        return backend.numpy.transpose(x, axes=self.axes)

    def compute_output_spec(self, x):
        output_shape = operation_utils.compute_transpose_output_shape(
            x.shape, self.axes
        )
        sparse = getattr(x, "sparse", False)
        return KerasTensor(output_shape, dtype=x.dtype, sparse=sparse)


@keras_export(["keras.ops.transpose", "keras.ops.numpy.transpose"])
def transpose(x, axes=None):
    
    if any_symbolic_tensors((x,)):
        return Transpose(axes=axes).symbolic_call(x)
    return backend.numpy.transpose(x, axes=axes)


class Mean(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            axis = [axis]
        self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.mean(x, axis=self.axis, keepdims=self.keepdims)

    def compute_output_spec(self, x):
        ori_dtype = backend.standardize_dtype(x.dtype)
        compute_dtype = dtypes.result_type(x.dtype, "float32")
        if "int" in ori_dtype or ori_dtype == "bool":
            result_dtype = compute_dtype
        else:
            result_dtype = ori_dtype
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=result_dtype,
        )


@keras_export(["keras.ops.mean", "keras.ops.numpy.mean"])
def mean(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return Mean(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.mean(x, axis=axis, keepdims=keepdims)


class Var(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            axis = [axis]
        self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.var(x, axis=self.axis, keepdims=self.keepdims)

    def compute_output_spec(self, x):
        output_dtype = backend.result_type(getattr(x, "dtype", type(x)), float)
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=output_dtype,
        )


@keras_export(["keras.ops.var", "keras.ops.numpy.var"])
def var(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return Var(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.var(x, axis=axis, keepdims=keepdims)


class Sum(Operation):
    def __init__(self, axis=None, keepdims=False):
        super().__init__()
        if isinstance(axis, int):
            axis = [axis]
        self.axis = axis
        self.keepdims = keepdims

    def call(self, x):
        return backend.numpy.sum(x, axis=self.axis, keepdims=self.keepdims)

    def compute_output_spec(self, x):
        dtype = dtypes.result_type(getattr(x, "dtype", backend.floatx()))
        
        if dtype in ("bool", "int8", "int16"):
            dtype = "int32"
        elif dtype in ("uint8", "uint16"):
            dtype = "uint32"
        
        if backend.backend() == "torch" and dtype == "uint32":
            dtype = "int32"
        return KerasTensor(
            reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims),
            dtype=dtype,
        )


@keras_export(["keras.ops.sum", "keras.ops.numpy.sum"])
def sum(x, axis=None, keepdims=False):
    
    if any_symbolic_tensors((x,)):
        return Sum(axis=axis, keepdims=keepdims).symbolic_call(x)
    return backend.numpy.sum(x, axis=axis, keepdims=keepdims)


class Zeros(Operation):
    def call(self, shape, dtype=None):
        return backend.numpy.zeros(shape, dtype=dtype)

    def compute_output_spec(self, shape, dtype=None):
        dtype = dtype or backend.floatx()
        return KerasTensor(shape, dtype=dtype)


@keras_export(["keras.ops.zeros", "keras.ops.numpy.zeros"])
def zeros(shape, dtype=None):
    
    return backend.numpy.zeros(shape, dtype=dtype)


class Ones(Operation):
    def call(self, shape, dtype=None):
        return backend.numpy.ones(shape, dtype=dtype)

    def compute_output_spec(self, shape, dtype=None):
        dtype = dtype or backend.floatx()
        return KerasTensor(shape, dtype=dtype)


@keras_export(["keras.ops.ones", "keras.ops.numpy.ones"])
def ones(shape, dtype=None):
    
    return backend.numpy.ones(shape, dtype=dtype)


class Eye(Operation):
    def call(self, N, M=None, k=0, dtype=None):
        return backend.numpy.eye(N, M=M, k=k, dtype=dtype)

    def compute_output_spec(self, N, M=None, k=0, dtype=None):
        if M is None:
            M = N
        dtype = dtype or backend.floatx()
        return KerasTensor((N, M), dtype=dtype)


@keras_export(["keras.ops.eye", "keras.ops.numpy.eye"])
def eye(N, M=None, k=0, dtype=None):
    
    return backend.numpy.eye(N, M=M, k=k, dtype=dtype)


class FloorDivide(Operation):
    def call(self, x1, x2):
        return backend.numpy.floor_divide(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        x1_sparse = getattr(x1, "sparse", False)
        x2_sparse = getattr(x2, "sparse", False)
        output_sparse = x1_sparse and not x2_sparse
        return KerasTensor(output_shape, dtype=x1.dtype, sparse=output_sparse)


@keras_export(["keras.ops.floor_divide", "keras.ops.numpy.floor_divide"])
def floor_divide(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return FloorDivide().symbolic_call(x1, x2)
    return backend.numpy.floor_divide(x1, x2)


class LogicalXor(Operation):
    def call(self, x1, x2):
        return backend.numpy.logical_xor(x1, x2)

    def compute_output_spec(self, x1, x2):
        x1_shape = getattr(x1, "shape", [])
        x2_shape = getattr(x2, "shape", [])
        output_shape = broadcast_shapes(x1_shape, x2_shape)
        return KerasTensor(output_shape, dtype="bool")


@keras_export(["keras.ops.logical_xor", "keras.ops.numpy.logical_xor"])
def logical_xor(x1, x2):
    
    if any_symbolic_tensors((x1, x2)):
        return LogicalXor().symbolic_call(x1, x2)
    return backend.numpy.logical_xor(x1, x2)