0

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.

1 Answers1

0

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)]
Leonardo Mariga
  • 1,166
  • 9
  • 17
  • Is it possible to write a custom Keras layer that'd do that like you described? The problem is that I need to add the layer that does this transformation and then save the new modified model as an H5 file. –  Sep 10 '19 at 12:53
  • 1
    Yes, that is possible =) you have to implement this algorithm in a [Custom Keras Layer](https://keras.io/layers/writing-your-own-keras-layers/). There are many examples online that might help you doing that [try this answer here](https://stackoverflow.com/a/54197775/11522398). Remember to implement [get_config()](https://stackoverflow.com/questions/57506707/how-to-load-the-keras-model-with-custom-layers-from-h5-file-correctly) in your layer so that you can save and load your .h5 file correctly. – Leonardo Mariga Sep 10 '19 at 13:06