Is there an eye function in the ndarray API?


#1

I couldn’t find a function to generate an identity matrix of a particular size in the ndarray API - am I just missing it?


#2

My current solution is -

mx.nd.one_hot(mx.nd.arange(N), N)

Is this really the best way to do this?


#3

Currently there’s no eye method, beyond mxnet.nd.identity.

Just ran a few benchmarks on this, and I think you already have the best option (staying within Python).

I tried starting with mxnet.nd.zeros and setting the diagonal to 1, and using mxnet.nd.scatter_nd, but both were slower in Python. You’d get much better results by dropping down into the C++ code, and setting the diagonal there.


#4

So the way I did it is fine? Not having an eye function is strange-


#5

Certainly does the job; and it looks quick to me. Only other avenue I can think of would be to create a sparse matrix but I agree, an eye function would be more elegant. You might want to raise a Github issue for this.


#6

Not yet. See https://github.com/apache/incubator-mxnet/issues/3199


#7

You are right, this is missing.
I wrote useful customop’s, to make a diagonal matrix from a vector and extract a diagonal from a matrix. Can point you to the code if you are interested.


#8

@mseeger that would be great! What did you think of the kronecker product hack (another question)? Btw - this is actually really fast the way I did it


#9

I worked on eye API in https://github.com/apache/incubator-mxnet/pull/8225. I will finish it as soon as possible. Thanks.