Create a string representation of a single-string encoding

In Python, I need to generate dictone that matches a letter with a predefined " one-hot " representation of this letter. As an illustration, dictshould look like this:

{ 'A': '1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0',
  'B': '0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0', # ...
}

There is one bit (represented as a character) per letter of the alphabet. Therefore, each line will contain 25 zeros and one 1. The position 1is determined by the position of the corresponding letter in the alphabet.

I came up with code that generates this:

# Character set is explicitly specified for fine grained control
_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
n = len(_letters)
one_hot = [' '.join(['0']*a + ['1'] + ['0']*b)
            for a, b in zip(range(n), range(n-1, -1, -1))]
outputs = dict(zip(_letters, one_hot))

Is there a more efficient / cleaner / more pythonic way to do the same?

+3
source share
4 answers

, :

from string import ascii_uppercase

one_hot = {}
for i, l in enumerate(ascii_uppercase):
    bits = ['0']*26; bits[i] = '1'
    one_hot[l] = ' '.join(bits)

, ['0']*26 ['0']*len(alphabet).

+7

Python 2.5 :

from string import ascii_uppercase

one_hot = {}
for i, c in enumerate(ascii_uppercase):
    one_hot[c] = ' '.join('1' if j == i else '0' for j in range(26))
+2
one_hot = [' '.join(['0']*a + ['1'] + ['0']*b)
            for a, b in zip(range(n), range(n-1, -1, -1))]
outputs = dict(zip(_letters, one_hot))

In particular, there is a lot of code in these two lines. You can try refactoring Enter an explanatory variable . Or perhaps an extraction method .

Here is an example:

def single_onehot(a, b):
    return ' '.join(['0']*a + ['1'] + ['0']*b)

range_zip = zip(range(n), range(n-1, -1, -1))
one_hot = [ single_onehot(a, b) for a, b in range_zip]
outputs = dict(zip(_letters, one_hot))

Although you may not agree with my name.

+1
source

It seems pretty clear, concise and pythonic to me.

0
source

Source: https://habr.com/ru/post/1719795/


All Articles