代码之家  ›  专栏  ›  技术社区  ›  E.M.

生成单热编码的字符串表示

  •  3
  • E.M.  · 技术社区  · 16 年前

    dict 将字母映射到预定义的“ one-hot “这封信的表述。举例来说 字典 应该看起来像这样:

    { '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', # ...
    }
    

    字母表中的每个字母都有一个位(表示为字符)。因此,每个字符串将包含25个零和1个1。的位置 1

    # 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))
    

    有没有一种更有效/更干净/更Python化的方法来做同样的事情?

    4 回复  |  直到 15 年前
        1
  •  7
  •   Peter Mortensen Pieter Jan Bonestroo    15 年前

    我觉得这更易读:

    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) .

        2
  •  2
  •   Laurence Gonsalves    16 年前

    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))
    
        3
  •  1
  •   Jason Baker    16 年前
    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))
    

    特别是,有一个 大量 Introduce Explaining Variable extract method .

    这里有一个例子:

    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))
    

    虽然你可能不同意我的名字。

        4
  •  -1
  •   bcat    16 年前