-1

I was writing code in Matlab and had to return a matrix which gave a 0 or 1 to represent elements in the original matrix.

I wanted to know if there is a python equivalent of the above without running nested loops to achieve the same result.

c = [2; 1; 3]
temp = eye(3,3)
d = temp(c,:)

the d matrix needs to tell me what number was present in my original matrix. i = 1, j = 2 if 1 tells me the first element of the original matrix was 2

  • I did put an answer, but on second thoughts, I don't think it generates the same output as you . Could you display `d` to show an example of the desired output? Is the idea to return an array of the size of `c` where the elements equal to `k` are replaced by `1` and the others by `0`? – Mathieu Sep 28 '20 at 08:33
  • what you are looking for is called `one-hot` encoding (or alternatively `one-of-K`). I'm sure there's hundreds of duplicates here. – Tasos Papastylianou Sep 28 '20 at 08:34
  • One-hot encoding: https://stackoverflow.com/questions/29831489/convert-array-of-indices-to-1-hot-encoded-numpy-array – Mathieu Sep 28 '20 at 08:36

1 Answers1

1

The "direct" equivalent of that code is this (note the 0-indexing, compared to matlab's 1-indexing)

import numpy
c    = numpy.array( [1, 0, 2] )
temp = numpy.eye( 3 )
d    = temp[c, :]

Here is the link to the documentation on how to index using 'index arrays' in the official numpy documentation

However, in general what you are doing above is called "one hot" encoding (or "one-of-K", as per Bishop2006). There are specialised methods for one hot encoding in the various machine learning toolkits, which confer some advantages, so you may prefer to look those up instead.

Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57
  • Brilliant! I wrote the same code. Almost. In my case, however, I didn't replace the 3 in the c array. Completely forgot that Matlab indexing is different from Python's – user3075599 Sep 28 '20 at 09:32