Search code examples
keraskeras-layer

Convert a tensor axis into strings and concatenate the axis reshaping the tensor?


If my last Keras Layer X outputs a tensor which looks, e.g. like this:

{
  {4, [22, 16,  11, 33], 24},
  {4, [12, 33,  87, 17], 14},
  {3, [92, 407, 25, 27], 34}
}

How can I add one more Layer Y that converts the output of X like this:

{
  {4, "22|16|11|33",  24},
  {4, "12|33|87|17",  14},
  {3, "92|407|25|27", 34}
}

In other words, I need to turn the second dimension into a string, with all values concatenated.


Solution

  • I'm not sure if Keras has method for this specific problem. A possible solution (if you can use list), is the following implementation:

    # Imagine you have a output layer like this:
    a = [
      [4, [22, 16,  11, 33], 24],
      [4, [12, 33,  87, 17], 14],
      [3, [92, 407, 25, 27], 34]
    ]
    
    # "transpose" the list and get the second element
    column1 = list(zip(*a))[1]
    
    # Join all elements with "|"
    newColumn1 = ['|'.join(str(e) for e in row) for row in column1]
    
    # Put back the modified column
    b =  list(zip(*a))
    b[1] = newColumn1
    
    # "Untranspose" your list
    a2 =  list(zip(*b))
    a2
    

    Your output will be:

    [(4, '22|16|11|33', 24), (4, '12|33|87|17', 14), (3, '92|407|25|27', 34)]